开发者

SQL View Conditional Selection

I am trying to create a view that pulls a particular record. The problem I am running into is that there are 2 records to choose from and a status flag that is either 1 or 2. It should pull the 1 record i开发者_Python百科f it exists, and if not the 2 record.

Is this possible from a view?


try sorting by status value, or group and return the min


Select B.*
FROM
    (Select 
       ID
       ,MIN(Flag) Flag
    From TableName
    Group by ID) A
    LEFT JOIN TableName B on A.ID=B.ID and A.Flag=B.Flag


pull select top 1 and order it by the status flag.


select * from table
where Status = 1

union

select * from table t
where status = 2 
    and not exists (select * from table t2 where t.id = t2.id and Status = 1)

Note that this approach works best when you have an id column to compare against. It is a different flavor of what Faiz wrote.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜