我在一家律师事务所工作,该事务所的案件管理系统将接口链接到SQL数据库。我正在SSRS中编写查询以运行报告。我正在试着做一份关于病例信息的报告。其中一些信息在"cases"表(或vcases视图)中是正确的,但我也试图链接来自"demands_offers"表的信息。每个案例都可以有多个需求和优惠,所以我在连接中使用MAX函数,只提取每个案例的最新需求记录。不幸的是,这样做消除了没有要求的情况。我需要所有的案子都来。
我曾尝试使用嵌套在MAX函数中的CASE语句将NULLS或空字段转换为随机的早期日期,但我仍然无法使所有案例都显示在报告中。
有什么想法吗?我是SQL的新手,没有受过正式的培训。如有任何帮助,我们将不胜感激。您可以看到下面的代码。(附言:我认为我没有创建临时表的权利。)
SELECT vc.case_number AS "Matter ID", vc.style, vc.atty2_name AS "Handling Attorney", m.max_demands_date, do.demands, do.demands_notes, sa.authorized,
(SELECT TOP 1 vl.computename
FROM vcases vca
LEFT OUTER JOIN case_parties cp
ON vca.case_sk = cp.case_sk
JOIN case_parties cpp
ON cp.parent_sk = cpp.case_parties_sk
JOIN vlegal_entity vl
ON vl.legal_entity_sk = cp.entity_sk
JOIN vlegal_entity vlp
ON vlp.legal_entity_sk = cpp.entity_sk
WHERE (vca.case_sk = vc.case_sk) AND (cpp.role_sk = '3557') AND (cp.role_sk = '3986') ) AS "Plaintiff//'s Attorney",
(SELECT cp.reference_number
FROM cases AS ca
LEFT OUTER JOIN case_parties AS cp
ON ca.case_sk = cp.case_sk
WHERE (cp.role_sk = '3706')
AND (ca.case_sk = vc.case_sk)) AS "Claim Number"
FROM
vcases vc
LEFT OUTER JOIN
case_parties cp ON vc.case_sk = cp.case_sk
LEFT OUTER JOIN
vlegal_entity vl ON cp.entity_sk = vl.legal_entity_sk
LEFT OUTER JOIN
settle_authority sa ON vc.case_sk = sa.case_sk
LEFT OUTER JOIN
demands_offers do ON vc.case_sk = do.case_sk
INNER JOIN
(SELECT DISTINCT max(
(CASE WHEN do.demands_date = '' THEN '1/1/1900 00:00:00'
ELSE do.demands_date
END)
) as "max_demands_date", vc.case_sk
FROM vcases AS vc
JOIN demands_offers AS do ON vc.case_sk = do.case_sk
GROUP BY vc.case_sk) AS m
ON vc.case_sk = m.case_sk AND
do.demands_date = m.max_demands_date
WHERE (vc.closed_ind = 'O') AND (cp.role_sk = '3816') AND (vl.client_number = 'EAS-01') AND (vc.lawtype_code <> 'FA')
ORDER BY vc.case_number
您的查询可能会被编写得更紧凑、性能更好,但首先,这是在没有要求的情况下删除行的部分:
INNER JOIN
(SELECT DISTINCT max(
(CASE WHEN do.demands_date = '' THEN '1/1/1900 00:00:00'
ELSE do.demands_date
END)
) as "max_demands_date", vc.case_sk
FROM vcases AS vc
JOIN demands_offers AS do ON vc.case_sk = do.case_sk
GROUP BY vc.case_sk) AS m
ON vc.case_sk = m.case_sk AND
do.demands_date = m.max_demands_date
它需要
LEFT JOIN
(SELECT DISTINCT max(
(CASE WHEN do.demands_date = '' THEN '1/1/1900 00:00:00'
ELSE do.demands_date
END)
) as "max_demands_date", vc.case_sk
FROM vcases AS vc
JOIN demands_offers AS do ON vc.case_sk = do.case_sk
GROUP BY vc.case_sk) AS m
ON vc.case_sk = m.case_sk AND
do.demands_date = m.max_demands_date
原因是(A INNER JOIN B)
只有在可以将A中的行与B中的行匹配时才保留记录。当没有需求时,派生表(子查询)会为max_demands_date
返回NULL,而do.demands_date = m.max_demands_date
无法匹配该值。这将导致case
记录被删除。