我有一张下表:
| ClientID | Status | Date |
| ---------- | --------- | --------- |
| 1 | -1 | 3/1/2016 |
| 1 | 0 | 5/5/2016 |
| 2 | 0 | 3/21/2016 |
| 2 | -1 | 4/16/2016 |
| 2 | 0 | 5/1/2016 |
| 3 | 0 | 4/10/2016 |
| 3 | -1 | 5/6/2016 |
| 4 | 0 | 5/8/2016 |
我需要我的结果每个ClientID有一行,如果该ClientID在表的任何行上的状态为-1,则优先于值0.结果应为:
| ClientID | Status | Date |
| ---------- | --------- | --------- |
| 1 | -1 | 3/1/2016 |
| 2 | -1 | 4/16/2016 |
| 3 | -1 | 5/6/2016 |
| 4 | 0 | 5/8/2016 |
我已经尝试过,并在StackExchange上查看了其他类似的问题,但似乎无法得到我想要的结果。任何帮助表示赞赏。
答案 0 :(得分:1)
尝试将问题分解为逻辑步骤,然后尝试从那里进行优化:
--Prioritise on Status == -1
select *
from ClientTable
where Status=-1
UNION
--Add any remaining rows, I guess you are only interested in one, not sure which one so chose top one
select top 1 *
from ClientTable
where ClientID not in (
select ClientID
from ClientTable
where Status=-1
)
答案 1 :(得分:1)
我会这样试试:
zip