即使他们没有进行交易,每月每笔交易的总和()

时间:2017-12-15 12:22:15

标签: sql sql-server

在我的SQL服务器中,我有2个表,付款和客户。付款包含客户的每笔交易。我想知道的是,即使他们没有进行交易,我每个月都能获得每月支付的金额(因此我也可以得到0)。

现在我得到了我想要的结果:

    SELECT Customer.FirstName, Customer.LastName, 
    YEAR(Payment.PaymentDate)AS YEARS, MONTH(Payment.PaymentDate) AS MONTHS,  
    SUM(Amount)AS Total 
    FROM Payment
    join Customer
    ON Customer.CustomerId = Payment.CustomerId
    GROUP BY Customer.FirstName, 
    Customer.LastName, MONTH(Payment.PaymentDate), YEAR(Payment.PaymentDate), 
    Payment.CustomerId
    ORDER BY YEARS desc, MONTHS desc

这给了我每个月每个客户支付的每笔金额。

 KATIE   ELLIOTT    2006    2   2.99
 DIANNE     SHELTON 2006    2   4.99
 NATALIE    MEYER   2006    2   5.98
 BETH   FRANKLIN    2006    2   2.99
 MIGUEL BETANCOURT  2006    2   3.98
 ALBERTO    HENNING 2006    2   2.99
 BEVERLY    BROOKS  2006    2   2.99

但是......有些客户有几个月他们没有进行交易。我希望那些以及数量为0的结果。

知道怎么做吗?

2 个答案:

答案 0 :(得分:2)

您可以使用cross join生成行。问题是如何获得月份列表。假设您每月至少有一笔交易,您可以使用现有数据:

SELECT c.FirstName, c.LastName, yyyymm.yyyy, yyyymm.mm,  
       SUM(p.Amount)AS Total 
FROM (SELECT DISTINCT YEAR(p.PaymentDate) as yyyy, MONTH(p.PaymentDate) as mm
      FROM Payment p
     ) yyyymm CROSS JOIN
     Customer c LEFT JOIN
     Payment p
     ON c.CustomerId = p.CustomerId AND
        YEAR(p.PaymentDate) = yyyymm.yyyy AND MONTH(p.PaymentDate) = yyyyymm.mm
GROUP BY c.FirstName, c.LastName, yyyymm.yyyy, yyyymm.mm
ORDER BY yyyymm.yyyy desc, yyyymm.mm desc;

答案 1 :(得分:-1)

参见下面的示例并相应更新:

IF OBJECT_ID('tempdb..#Transcation') IS NOT NULL
DROP TABLE tempdb..##Transcation;
GO

IF OBJECT_ID('tempdb..#Customer') IS NOT NULL
DROP TABLE tempdb..#Customer;
GO

CREATE TABLE #Customer (
RowNo INT IDENTITY(1,1),
CID INT,
NAME VARCHAR(256)
);
GO

INSERT INTO #Customer  VALUES(1,'A');
INSERT INTO #Customer  VALUES(2,'B');
INSERT INTO #Customer  VALUES(3,'C');
INSERT INTO #Customer  VALUES(4,'D');
GO

CREATE TABLE #Transcation (
RowNo INT IDENTITY(1,1),
CID INT,
[Year] INT,
[Month] INT,
Amount FLOAT
);
GO

INSERT INTO #Transcation VALUES (1,2017,1,5.6);
INSERT INTO #Transcation VALUES (2,2017,1,4.6);
INSERT INTO #Transcation VALUES (1,2017,2,5.6);
INSERT INTO #Transcation VALUES (2,2017,2,3.6);
INSERT INTO #Transcation VALUES (1,2017,3,5.6);
INSERT INTO #Transcation VALUES (2,2017,3,3.6);
INSERT INTO #Transcation VALUES (1,2017,4,6.6);
INSERT INTO #Transcation VALUES (2,2017,4,7.6);
INSERT INTO #Transcation VALUES (1,2017,5,8.6);
INSERT INTO #Transcation VALUES (2,2017,5,9.6);
GO

SELECT NAME, ISNULL([YEAR],0), ISNULL([Month],0), ISNULL(SUM(Amount) OVER (PARTITION BY NAME, [YEAR], [Month]),0)
FROM #Customer AS A LEFT JOIN
#Transcation AS B ON A.CID = B.CID