我在一家律师事务所工作,该案件管理系统将接口链接到SQL数据库。我在SSRS中编写查询来运行报告。我正在尝试运行案例信息报告。一些信息正好在“案例”表(或vcases视图)中,但我也试图链接来自“requirements_offers”表的信息。每个案例都有多个需求和优惠,因此我在联接中使用MAX函数来仅提取每个案例的最新需求记录。不幸的是,这样做可以消除没有要求的情况。我需要出现所有案例。
我尝试使用嵌套在MAX函数中的CASE语句将NULLS或空字段转换为随机的早期日期,但我仍然无法将所有案例都显示在报告中。
有什么想法吗?我是SQL的相对新手,没有正式的培训。任何帮助将不胜感激。你可以看到下面的代码。 (P.S.我认为我没有权利创建临时表。)
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
答案 0 :(得分:1)
你的查询可能写得更紧凑,性能更好,但是要启动你,这就是删除行没有要求的部分:
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
记录被删除。