Sql 查询以查找缺少的每月付款
Posted
技术标签:
【中文标题】Sql 查询以查找缺少的每月付款【英文标题】:Sql Query to find missing monthly payment 【发布时间】:2017-07-15 14:35:06 【问题描述】:我有一个 SQL 表,其中包含来自组成员的每月分期付款。
Member A : 10 ( Monthly Fee),
Member B : 15 ( Monthly Fee )
我的数据库表
我正在寻找一个可以返回如下的查询。 我需要得到如图所示的结果才能找到丢失的付款
【问题讨论】:
你也考虑年份吗? 是否有可能,例如,在 2017 年 1 月收到 2016 年 12 月的付款记录? 【参考方案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
【讨论】:
【参考方案2】:对于列名的动态列表,和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
【讨论】:
以上是关于Sql 查询以查找缺少的每月付款的主要内容,如果未能解决你的问题,请参考以下文章
Rails:如何构建每天/每月/每年的统计数据或如何缺少与数据库无关的 SQL 函数(例如:STRFTIME、DATE_FORMAT、DATE_TRUNC)
Oracle SQL:: 子查询中带有 orderby 的 Rownum 抛出缺少括号