在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
有人可以帮忙吗?
答案 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);