如果您想尝试,我会在此SQL Fiddle上构建架构。
我有以下数据
AutoID Apartment Flag Description
====== ========= ==== ===========
1 1 NO Device 1
2 1 NO Device 2
3 1 NO Device 3
4 2 NO Device 4
5 2 NO Device 5
6 3 NO Device 6
7 3 NO Device 7
8 3 YES Device 8
9 3 NO Device 9
我正在尝试使用以下规则获取数据
因此,如果我运行SQL语句,我最终将使用
AutoID Apartment Flag Description
====== ========= ==== ===========
1 1 NO Device 1
4 2 NO Device 4
8 3 YES Device 8
我一直试图用OVER()和PARTITION BY玩弄运气不好。非常感谢任何帮助或指导。
答案 0 :(得分:3)
;WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY Apartment
ORDER BY CASE WHEN [Flag] = 'YES' THEN 1 ELSE 2 END,
[AutoID])
FROM TableA
)
SELECT *
FROM CTE
WHERE RN = 1
Here is修改后的sqlfiddle
答案 1 :(得分:2)
第一步 - 为每个组中的订单号分配相同的公寓号
第二步 - 只选择第一步
select AutoID, Apartment, Flag, Description from (
select AutoID, Apartment, Flag, Description, row_number() over (partition by apartment order by Flag desc) rnum
from table1)
where rnum = 1