我有此数据:
ID PERSNR YEARNR MONTHNR DAYNR ABSTIME ABSID ABSCALC TypeLine
---------------------------------------------------------------------
1 26 2018 12 3 480 3 11 0
2 26 2018 12 3 480 3 11 1
5 26 2018 10 1 60 1 31 0
8 26 2018 10 3 60 1 31 0
13 69 2018 12 3 480 3 11 0
14 69 2018 12 3 480 3 11 1
19 69 2018 9 3 60 3 31 1
22 69 2018 9 3 60 3 31 0
23 69 2018 9 3 420 21 11 0
26 69 2018 9 6 120 21 31 1
29 69 2018 9 10 120 21 31 1
32 69 2018 9 4 480 21 11 1
我需要确定以下情况:
同时具有TypeLine 0和1的行 结果ID:1和2; 13和14、19和22
仅具有TypeLine的行0 结果ID:5; 8; 23
仅具有TypeLine的行1 结果ID:26、29、32
我不确定要创建这3个脚本,但是找不到解决方案。
你能帮我吗?
答案 0 :(得分:1)
这是您想要的吗?
select (case when cnt_type_0 > 0 and cnt_type_1 > 0
then 'Condition 1'
when cnt_type_1 = 0
then 'Condition 2'
when cnt_type_0 = 0
then 'Condition 3'
end) as condition,
t.*
from (select t.*,
count(*) over (partition by ID, PERSNR, YEARNR, MONTHNR, DAYNR, ABSTIME, ABSID, ABSCALC) as cnt,
sum(case when TypeLine = 0 then 1 else 0 end) over (partition by ID, PERSNR, YEARNR, MONTHNR, DAYNR, ABSTIME, ABSID, ABSCALC) as cnt_type_0,
sum(case when TypeLine = 1 then 1 else 0 end) over (partition by ID, PERSNR, YEARNR, MONTHNR, DAYNR, ABSTIME, ABSID, ABSCALC) as cnt_type_1
from t
) t
where cnt >= 2;
您可以将条件添加到WHERE
子句中,以获取仅一种类型的行。
答案 1 :(得分:0)
尝试这样的事情:
SELECT DISTINCT ID,
PERSNR,
YEARNR,
MONTHNR,
DAYNR,
ABSTIME,
ABSID,
ABSCALC,
iif(count(TypeLine) >= 2, 'duplicate', iif(min(TypeLine) = 1, '1', '0')) as status
FROM table
GROUP BY ID, PERSNR, YEARNR, MONTHNR, DAYNR, ABSTIME, ABSID, ABSCALC
答案 2 :(得分:0)
假设源数据正确,则可以运行以下3个查询。 #1当前回答正确,但是#2和#3在当前版本的问题中具有不同的DAYNUM,因此您不会使用这些示例值返回任何内容...
--1
SELECT T1.ID AS [T1_ID], T2.ID AS [T2_ID]
FROM [tablename] T1 INNER JOIN [tablename] T2 ON T1.PERSNR = T2.PERSNR
AND T1.YEARNR = T2.YEARNR AND T1.MONTHNR = T2.MONTHNR
AND T1.DAYNR = T2.DAYNR AND T1.ABSTIME = T2.ABSTIME
AND T1.ABSID = T2.ABSID AND T1.ABSCALT = T2.ABSCALT
AND (T1.TypeLine = 0 AND T2.TypeLine = 1
OR
T1.TypeLine = 1 AND T2.TypeLine = 0
)
AND T1.ID < T2.ID
--2
SELECT T1.ID AS [T1_ID], T2.ID AS [T2_ID]
FROM [tablename] T1 INNER JOIN [tablename] T2 ON T1.PERSNR = T2.PERSNR
AND T1.YEARNR = T2.YEARNR AND T1.MONTHNR = T2.MONTHNR
AND T1.DAYNR = T2.DAYNR AND T1.ABSTIME = T2.ABSTIME
AND T1.ABSID = T2.ABSID AND T1.ABSCALT = T2.ABSCALT
AND T1.TypeLine = 0 AND T2.TypeLine = 0
AND T1.ID < T2.ID
--3
SELECT T1.ID AS [T1_ID], T2.ID AS [T2_ID]
FROM [tablename] T1 INNER JOIN [tablename] T2 ON T1.PERSNR = T2.PERSNR
AND T1.YEARNR = T2.YEARNR AND T1.MONTHNR = T2.MONTHNR
AND T1.DAYNR = T2.DAYNR AND T1.ABSTIME = T2.ABSTIME
AND T1.ABSID = T2.ABSID AND T1.ABSCALT = T2.ABSCALT
AND T1.TypeLine = 1 AND T2.TypeLine = 1
AND T1.ID < T2.ID