根据Priority -Sql选择行

时间:2015-11-06 08:40:39

标签: sql sql-server

我有一个案例,我想选择基于行的状态cloumn Priorty

First Priorty应为Customer_Status,状态为'已删除'

第二优先级应为Family_Status,其值为'已删除' [选择带有Family_Status ='已删除'的前1名]

如果所有Family_Status都是“open”,那么请选择top 1 Family_Status ='Open'

案例:1

CustomerID  FamilyId    Name         Customer_Status     Family_Status
-------     --------    ---------   ---------------      -----------
1000         101         Vk           Open               Deleted
1000         102         vk           Open               Open
1000         103         vk           Open               Open

在这种情况下,我需要结果

CustomerID  FamilyId    Name         Customer_Status     Family_Status
-------     --------    ---------   ---------------      -----------
1000         101         Vk           Open               Open

情况2

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ------------
1000          101         Vk           Open               Open
1000          102         vk           Deleted            Open
1000          103         vk           Open               Open

在这种情况下,我需要结果

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ------------
1000          102         vk           Deleted            Open

案例:3

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ------------
1000          101         Vk           Deleted            Open
1000          102         vk           Deleted            Open
1000          103         vk           Deleted            Open

输出:

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ------------
1000          101         Vk           Deleted            Open

案例:4

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ------------
1000          101         Vk           Open               Deleted
1000          102         vk           Open               Deleted
1000          103         vk           Open               Deleted

在这种情况下,我需要结果

 
CustomerID   FamilyId    Name         Customer_Status     Family_Status
-------                  ---------    ---------------     ---------
1000          101         Vk           Open               Deleted

任何人都可以帮助解决此问题

1 个答案:

答案 0 :(得分:1)

只需订购结果集:

SELECT TOP (1) *
FROM MyTable
ORDER BY Customer_Status, Family_Status DESC