分组并选择非null值(如果存在)

时间:2019-07-10 20:19:39

标签: sql sql-server

有没有一种方法可以执行group by并将非值用于列(如果有)。即

a  | b | c | d    | e       | f                   |
---------------------------------------------------
1  | 2 | 3 | x    | test1   | 2019-07-01 07:17:01 |
1  | 2 | 3 | NULL | test2   | 2019-07-01 10:23:11 |
1  | 2 | 3 | NULL | test3   | 2019-07-01 22:00:51 |
1  | 2 | 7 | NULL | testTet | 2019-07-01 23:00:00 |

在上面的例子中,如果d出现a=1,b=2,c=3,它将始终为x,否则可以为null。所以我的查询就像

select a,
       b,
       c,
       d,
       count(distinct e) as something
from tableX
where f between '2019-07-01 00:00:00' and '2019-07-01 23:59:59.999'
group by a,
         b,
         c,
         d

结果将是:

a  | b | c | d    | something |
------------------------------|
1  | 2 | 3 | x    | 1         |
1  | 2 | 3 | NULL | 2         |
1  |2  | 7 | NULL | 1         |

如果可以的话,这会很棒(因为对于每个group by组合,我都知道它为null或存在的唯一值):

a  | b | c | d    | something |
------------------------------|
1  | 2 | 3 | x    | 3         |
1  | 2 | 7 | NULL | 1         |

2 个答案:

答案 0 :(得分:3)

从您的样本数据中,我认为您不需要d子句中的group by
因此获得其最大值:

select 
  a, b, c, 
  max(d) d,
  count(distinct e) as something
from tableX
where f between '2019-07-01 00:00:00' and '2019-07-01 23:59:59.999'
group by a, b, c

答案 1 :(得分:1)

尝试如下

with cte as (select a,
       b,
       c,
       d,
       count(distinct e) as something
from tableX
where f between '2019-07-01 00:00:00' and '2019-07-01 23:59:59.999'
group by a,
         b,
         c,
         d) select a,b,c,max(d) as d,sum(something) from cte group by a,b,c