如何在SQL Server中将多个并集语句转换为单行

时间:2019-05-14 12:53:57

标签: sql-server

如何将查询转换为具有不同列名的单行。

 Select count(distinct accountid) as x
 from table1
 where active = 1
 and expiredate >= GetDate()
 and acceptedon is not null
 union
 Select count(distinct accountid) as x
 from table1
 where active = 1
 and expiredate <= GetDate()
 and acceptedon is not null

我明白了

x

5

4

我想要

x    y

5    4

1 个答案:

答案 0 :(得分:3)

您想要简单的条件聚合:

Select count(distinct case when expiredate >= GetDate() then accountid end) as x,
       count(distinct case when expiredate <= GetDate() then accountid end) as y
from table1
where active = 1 and acceptedon is not null;