简体   繁体   中英

How do I apply a condition to a grouped query in T-SQL?

I am trying to figure out the most efficient way, using T-SQL , to group items in this table by ItemId, and select the first supported date value based on the bit value in the Supported column (or the last for the grouping, if none are marked as supported)

Table

ItemId  | Date      | Supported
===================================
1       | 1/1/2001  | 0
1       | 1/1/2002  | 1
1       | 1/1/2003  | 0
2       | 1/1/2001  | 0
2       | 1/1/2002  | 0
2       | 1/1/2003  | 0

Pseudo Code

SELECT MAX(Date WHERE Supported=1 (Or Last)) FROM Table GROUP BY ItemId

Desired Results

ItemId  | Date  
======================
1       | 1/1/2002  
2       | 1/1/2003

You can use coalesce() with group by :

select itemid,
       coalesce( min(case when supported = 1 then date end),
                 max(date)
               )
from t
group by itemid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM