在 SQL 中转置和添加新记录

问题描述

SELECT COUNT(disTINCT CASE WHEN customer_name = 'Alex' THEN item END) AS by_Alex,COUNT(disTINCT CASE WHEN customer_name = 'Bob' THEN item END) AS by_Bob,COUNT(disTINCT CASE WHEN customer_name = 'Jim' THEN item END) AS by_Jim
FROM sales;

输出这个结果

Outputs this result

如何安排此代码以转置为矩阵(w/2 列“名称”和“计数”) 并通过总结“by_Bob”(2)和“by_Alex”(3)并在“Count”列下添加5来添加一个名为“by_Christian”的新行?

解决方法

认为你只是想要聚合:

select name,count(*) as num_items,count(distinct item) as num_distinct_items
from sales
group by name;
,

您可以按如下方式进行聚合和UNION ALL

select name,count(distinct item) as cnt
  from sales
 where name in ('Alex','Bob','Jim')
group by name
UNION ALL
select 'Christian' AS name,count(DISTINCT CASE WHEN customer_name = 'Alex' THEN item END) 
        + count(DISTINCT CASE WHEN customer_name = 'Bob' THEN item END) as cnt
  from sales
 where name in ('Alex','Bob');