0

假设我有一个表(关系)

MyTab(ID1,ID2,IsMarked, data,....)

示例数据可能如下所示:

1,  1, 1, ...
1,  2, 0, ...
1,  3, 0, ...

2,  34, 1, ...

3,  4, 0, ...

4,  546, 0, ...
4,  8, 0, ...

每个只能标记一个ID1。我想获取标记1为所有 Entity 的数据ID1。如果没有标记记录,则获取第一个或其中任何一个。

对于上述样本数据,结果应为:

1,  1, 1, ...

2,  34, 1, ...

3,  4, 0, ...

4,  546, 0, ...

联合可能是一个解决方案,但太长并且可能性能不佳。我的想法是按ID1IsMarkeddesc 对数据进行排序,为 each 获取第一个 1 ID1,但是如何SQL为这种情况编写 a 呢?

4

2 回答 2

3

对于每个 ID1 只能标记一个,以下应该有效:

;with cte as (
    select *, rn=row_number() over (partition by ID1 order by IsMarked desc)
)
select *
from cte
where rn=1
于 2013-08-19T19:52:55.580 回答
0

在黑暗中拍摄:

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);
于 2013-08-19T19:45:51.643 回答