gpt4 book ai didi

sql-server - t-sql 数据透视表 - 月收入

转载 作者:行者123 更新时间:2023-12-01 14:56:57 24 4
gpt4 key购买 nike

我无法弄清楚如何为我的收入查询构建 PIVOT

首先,这是我的查询:

SELECT  DATENAME(month,
CONVERT(DATETIME, CONVERT(VARCHAR, TransactionMonth) + '/1'
+ '/2013')) AS MONTH ,
RevenueGroup ,
AMOUNT
FROM ( SELECT f.TransactionMonth ,
f.RevenueGroupID ,
'$'
+ CONVERT(VARCHAR, CAST(SUM(f.LineItemAmount) AS MONEY), -1) AS Revenue ,
MIN(f.RevenueGroup) AS RevenueGroup
FROM Financials(@StartDate, @EndDate, @SiteID) f
GROUP BY f.TransactionMonth ,
f.RevenueGroupID
) AS Rev
ORDER BY Rev.TransactionMonth DESC ,
CAST(Revenue AS MONEY) DESC

这是我的结果集:

MONTH       RevenueGroup         AMOUNT
December Dues - Collect $425,725.71
December NMS $78,444.17
December Personal Training $58,511.53
November Dues - Collect $425,683.75
November NMS $114,710.25
November Personal Training $66,277.49
October Dues - Collect $419,250.09
October NMS $96,098.86
October Personal Training $58,725.77

下面是结果集需要如何处理 sql PIVOT:

RevenueGroup        DECEMBER      NOVEMBER      OCTOBER
Dues - Collect $425,725.71 $425,683.75 $419,250.09
NMS $78,444.17 $114,710.25 $96,098.86
Personal Training $58,511.53 $66,277.49 $58,725.77

如何使用 T-SQL PIVOT 实现此目的?

最佳答案

测试数据

CREATE TABLE #MyTable ([MONTH] NVARCHAR(20),RevenueGroup NVARCHAR(100),AMOUNT NUMERIC(20,2))
GO
INSERT INTO #MyTable
VALUES
('December','Dues - Collect', 425725.71),
('December','NMS', 78444.17),
('December','Personal Training', 58511.53),
('November','Dues - Collect', 425683.75),
('November','NMS', 114710.25),
('November','Personal Training', 66277.49),
('October','Dues - Collect', 419250.09),
('October','NMS', 96098.86),
('October','Personal Training', 58725.77)

查询

SELECT RevenueGroup, [October],[November],[December]
FROM (SELECT * FROM #MyTable)t --<-- Your Existing Query can go in here but do not
PIVOT -- not do any formating like Dollar sign as you want
( -- sum the results by month later on
SUM(AMOUNT)
FOR [MONTH]
IN ([October],[November],[December])
)P

结果

╔═══════════════════╦═══════════╦═══════════╦═══════════╗
║ RevenueGroup ║ October ║ November ║ December ║
╠═══════════════════╬═══════════╬═══════════╬═══════════╣
║ Dues - Collect ║ 419250.09 ║ 425683.75 ║ 425725.71 ║
║ NMS ║ 96098.86 ║ 114710.25 ║ 78444.17 ║
║ Personal Training ║ 58725.77 ║ 66277.49 ║ 58511.53 ║
╚═══════════════════╩═══════════╩═══════════╩═══════════╝

关于sql-server - t-sql 数据透视表 - 月收入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com