简体   繁体   English

SQL Server计数多个条件

[英]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 ? 对于下表,如何为选择查询编写子查询,以便在给定Num的Inv = Esc时返回标志列?

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 您可以尝试使用CASE WHEN

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

sqlfiddle sqlfiddle

If you want to update Flag column you can try this. 如果要更新Flag列,可以尝试此操作。

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. 这样可以确保该值始终准确-无需创建insertupdate触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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