我有一个SQL表,其中包含来自小组成员的每月分期付款。
Member A : 10 ( Monthly Fee),
Member B : 15 ( Monthly Fee )
我的数据库表
我正在寻找一个可以返回如下的查询。 我需要获得结果,如图中所示,找不到付款
答案 0 :(得分:1)
根据您的示例数据和所需的输出,您可以使用PIVOT
,但我总是建议您在演示文稿应用程序中PIVOT
数据,而不是数据库查询。
USE
tempdb
GO
IF OBJECT_ID('Payments', 'U') IS NOT NULL
DROP TABLE Payments
GO
CREATE TABLE Payments(
Serial# INT NOT NULL PRIMARY KEY
,Date DATE NOT NULL
,MemberName VARCHAR(20) NOT NULL
,Month VARCHAR(20) NOT NULL
,MonthlyFee INT NOT NULL
);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (1,'01/01/2017','Member A','January',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (2,'01/01/2017','Member B','January',15);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (3,'01/02/2017','Member A','February',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (4,'01/03/2017','Member B','March',15);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (5,'01/03/2017','Member A','March',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (6,'01/05/2017','Member A','May',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (7,'01/06/2017','Member A','June',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (8,'01/05/2017','Member B','May',15);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (9,'01/09/2017','Member A','September',10);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (10,'01/06/2017','Member B','June',15);
INSERT INTO Payments(Serial#,Date,MemberName,Month,MonthlyFee) VALUES (11,'01/10/2017','Member A','October',10);
SELECT
MemberName
, January
, February
, March
, April
, May
, June
, July
, August
, September
, October
, November
, December
FROM
(
SELECT
MemberName
, Month
, MonthlyFee
FROM
Payments
) AS P
PIVOT
(
SUM(MonthlyFee)
FOR [Month] IN
(
January
, February
, March
, April
, May
, June
, July
, August
, September
, October
, November
, December
)
) AS Pvt
答案 1 :(得分:0)
对于列名的动态列表,与mheptinstall的方法没有太大区别
Declare @cols1 varchar(max)
Declare @query nvarchar(max)
Select @cols1 = stuff((select top (12) ','+QuoteName(DateName(MONTH,(DateAdd(MM, Row_Number() over(order by (Select NULL))-1, '2017-01-01'))))
from master..spt_values for xml path('')),1,1,'')
Select @query = ' Select * from (
Select MemberName, [Month], MonthlyFee from Payments ) a
pivot(sum(MonthlyFee) for [Month] in ('+ @cols1 + ') ) p '
Exec SP_ExecuteSql @query