我有一个名为LEDGER
的表。它有三列名为PATID
,CODE
和TRANDATE
。
示例数据:
PATID CODE TRANDATE
1 Z1110 07-15-1970
1 D3330 07-15-1970
1 Z0330 07-15-1970
2 Z1298 07-20-1970
2 Z0987 07-20-1970
2 Z0330 07-20-1970
2 D1092 07-20-1970
3 Z0330 08-20-1980
3 Z1110 02-11-1982
我需要一个返回PATID
的查询,如果他们有CODE
Z0330
但Z1110
并且两个代码都出现在同一个TRANDATE
。如果存在这种情况,我只想要一个PATID
返回。在上面的示例中,输出应为:
PATID CODE TRANDATE
2 Z0330 07-20-1970
3 Z0330 07-20-1980
如何编写查询来执行此操作?
答案 0 :(得分:3)
您可以使用having
子句聚合获得所需内容:
select patid, 'Z0330' as code, transdate
from example
group by patid, transdate
having sum(case when code = 'Z0330' then 1 else 0 end) > 0 and
sum(case when code = 'Z1110' then 1 else 0 end) = 0;
答案 1 :(得分:0)
试试这个,先选择代码为'z1110'的trandates,然后选择prev查询中没有transadate的行。
SELECT * FROM LEDGER WHERE TRANDATE NOT IN(
SELECT TRANDATE FROM LEDGER WHERE CODE = 'Z1110'
)
AND CODE = 'Z3330'
答案 2 :(得分:0)
这个怎么样?
SELECT DISTINCT PATID, TRANDATE
FROM LEDGER L1
where not exists (select 1 from LEDGER L2
where L1.TRANDATE = L2.TRANDATE
and L2.CODE = 'Z1110' );
答案 3 :(得分:0)
这对你有用。如果您想要每个月的旧日,请将订单更改为ASC。目前,查询检索每个月的最后一天。
此处提供了示例SQL FIDDLE DEMO
;WITH cte_Result AS
(
SELECT ROW_NUMBER() OVER(
PARTITION BY CODE,
CONVERT(VARCHAR(7), TRANDATE, 120) ORDER BY TRANDATE DESC
) AS ID,
PATID,
CODE,
TRANDATE
FROM LEDGER
WHERE CODE = 'Z0330'
)
SELECT PATID,
CODE,
TRANDATE
FROM cte_Result
WHERE ID = 1