如何根据其他列值汇总table?

How to summarize table based on other column values?

有一个decisiontable如下:

Id                decision                  
1                   NULL
1                   NULL
1                   yes
1                   NULL
2                   no
2                   no
2                   no
3                   yes
3                   no
3                   yes

结果应该return:

Id                decision                  
1                   Decision Pending
2                   no
3                   yes

因此对于 decision table 中的每个 ID:

azure sql 查询什么才能得到上述结果?

P.S。我是 SQL 的新手,所以很难理解。

SELECT 
  id,
  CASE
    WHEN COUNT(*) > COUNT(decision)
      THEN 'pending'
      ELSE MAX(decision)
  END
    AS decision
FROM
  decision
GROUP BY
  id

GROUP BY id 确保每个 id.

得到一行

COUNT(*) 告诉您 id.

有多少行

COUNT(decision) 告诉您其中有多少行有 NOT NULL 个决定。

COUNT(*) > COUNT(decision) 因此 TRUE 如果组中的任何决定是 NULL

MAX(decision) returns yes 如果组中有任何 yes 值,no 仅当没有任何 [=21] =]组中的值。

一种方法是比较 count(*)count(decision),后者显示某行是否为空,并使用 内联 if 来简洁地知道使用聚合

select id, Iif(Count(*)=Count(decision),Max(decision),'Decision Pending')
from Decision
group by id