[英]How to write sql for this case?
Suppose I have a table(a relationship) like 假设我有一个表(一个关系)
MyTab(ID1,ID2,IsMarked, data,....)
the sample data maybe looks like: 样本数据可能看起来像:
1, 1, 1, ...
1, 2, 0, ...
1, 3, 0, ...
2, 34, 1, ...
3, 4, 0, ...
4, 546, 0, ...
4, 8, 0, ...
Only one could be marked for each ID1
. 每个
ID1
只能标记一个。 I want to get data marked as 1
for all Entities ID1
. 我想为所有实体
ID1
都将数据标记为1
。 If there is no marked record, get the first one or any one of them. 如果没有标记的记录,则获取第一个或其中一个。
For above sample data, the result should be: 对于上述样本数据,结果应为:
1, 1, 1, ...
2, 34, 1, ...
3, 4, 0, ...
4, 546, 0, ...
Union could be a solution, but is too long and may have bad performance. 联合可能是一个解决方案,但时间太长,可能会导致性能下降。 My idea is to sort the data by
ID1
and IsMarked
desc, the get the first 1 for each ID1
, but how to write a SQL
for this case? 我的想法是按
ID1
和IsMarked
desc对数据进行排序,为每个ID1
获取第一个1,但是在这种情况下如何编写SQL
?
For Only one could be marked for each ID1 the following should work: 对于每个ID1只能标记一个 ,以下各项应起作用:
;with cte as (
select *, rn=row_number() over (partition by ID1 order by IsMarked desc)
)
select *
from cte
where rn=1
Shot in the dark: 在黑暗中拍摄:
SELECT A.*
FROM MYTAB A
LEFT JOIN (
SELECT MAX(ID2) AS MAXID2, ID1
FROM MYTAB
WHERE ISMARKED=1
GROUP BY ID1
) B ON A.ID2=B.MAXID2 AND A.ID1=B.ID1
LEFT JOIN (
SELECT MAX(ID2) AS MAXID2, ID1
FROM MYTAB
WHERE ISMARKED=0
GROUP BY ID1
) C ON A.ID2=C.MAXID2 AND A.ID1=C.ID1
WHERE
(B.ID1 IS NOT NULL)
OR
(B.ID1 IS NULL AND C.ID1 IS NOT NULL);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.