在SQL中用一行数据透视表
我有一份每周报告,在那里我必须分享我们的表现。我有以下疑问在SQL中用一行数据透视表,sql,sql-server,Sql,Sql Server,我有一份每周报告,在那里我必须分享我们的表现。我有以下疑问 SELECT COUNT(*) AS Transactions, COUNT(DISTINCT id) as Customers, SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN 1 ELSE 0 END) School_Supplies, SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN Payment ELSE
SELECT COUNT(*) AS Transactions,
COUNT(DISTINCT id) as Customers,
SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN 1 ELSE 0 END) School_Supplies,
SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN Payment ELSE 0 END) AS School_Supplies_Revenue
FROM dbo.Transactions
这给了我一张桌子
Transactions | Customers | School_Supplies | School_Supplies_Revenue
12845 | 9654 | 1546 | 8745
我希望桌子能像这样旋转
KPI | Value
Transactions | 12845
Customers | 9654
School_Supplies | 1546
School_Supplies_Revenue | 8745
我试着使用UNPIVOT,但不起作用。如何透视此表,使列名及其各自的值成为数据点
我的数据库如下所示:
[ID] | [Product] | [Cost per Item] | [Payment] | [Transaction Date]
001 | Paper | 2.15 | 5.54 | 2021-01-12
在SQL Server中,最简单的方法可能是
apply
:
SELECT v.*
FROM (SELECT COUNT(*) AS Transactions,
COUNT(DISTINCT id) as Customers,
SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN 1 ELSE 0 END) as School_Supplies,
SUM(CASE WHEN Product in ('Paper','Pen','Eraser') THEN Payment ELSE 0 END) AS School_Supplies_Revenue
FROM dbo.Transactions t
) t CROSS APPLY
(VALUES ('Transactions', Transactions),
('Customers', customers),
('School_Supplies', School_Supplies),
('School_Supplies_Revenue', School_Supplies_Revenue)
) v(kpi, value);
用您正在使用的数据库标记您的问题。
dbo.Transactions
表明它是。这也是Microsoft SQL Server用户将其数据库称为“SQL”的自定义设置,就像没有其他人使用该术语一样。这正是我所需要的,非常感谢。