简体   繁体   中英

SQL Server Count for multiple conditions

for the table below, how can I write a subquery for my select query so that I can return a flag column when the Inv = Esc for a given Num ?

In the example below, the second row is a match as well as the fifth row. Tried but keep getting boggled. Thanks.

**Additionally, there should be only one Flag for each Num.

    Num  |  Name   |Inv |Esc|Flag
1)  *785*   | AB7851     |155   |496  
2)  *785*   | AB7852     |**496 |496**  |**Hit**
3)  *785*   | AB7853     |518   |496  
4)  *785*   | AB7854     |769   |496  
5)  236 | AB785Q     |**155 |155**      |**Hit**
6)  236 | AB785R     |496   |155  
7)  236 | AB785S     |518   |155  
8)  236 | AB785T     |747   |155  
9)  236 | AB785U     |769   |155  

You can try to use CASE WHEN

SELECT t1.*,
       case when Inv = Esc then 'HIT' end  as 'flag'
FROM T t1 

sqlfiddle

If you want to update Flag column you can try this.

UPDATE T 
SET Flag =  (case when Inv = Esc then 'HIT' end )

I strongly advise you to do this using a computed column:

alter table t add flag as (case when inv = esc then 'hit' end);

A computed column is (generally) calculated when the table is queried. This ensures that the value is always accurate -- without having to create insert and update triggers.

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