将列转换为行

时间:2018-04-20 17:53:17

标签: sql sql-server

在SQL Server中,我编写了以下查询

SELECT 
    COUNT(DISTINCT Category) AS Categories,
    COUNT(DISTINCT [Order Number]) AS Orders,
    COUNT(DISTINCT Product) AS Products
FROM
    Associate 

,输出如下

Categories    Orders     Products
---------------------------------
   17         13050        37

但我想要这样的结果

#Object#    |   #Count#
------------+-----------
Categories  |     17
Orders      |  13050
Products    |     37

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以使用union all或取消结果:

with c as (
      select count(distinct Category) AS Categories,
             count(distinct [Order Number]) AS Orders,
             count(distinct Product) AS Products
      from Associate 
     )
select v.*
from c cross apply
     (values ('Categories', Categories),
             ('Orders', Orders),
             ('Products', Products)
     ) v(which, cnt);

这通常是最有效的选择。但是,count(distinct)相当昂贵,因此对表的三次扫描可能不是一个很大的性能影响。所以:

select 'Categories' as which, count(distinct Category) as cnt
from Associate union all
select 'Orders', count(distinct [Order Number])
from Associate union all
select 'Products', count(distinct Product);