使用PIVOT汇总每月购买的产品数量和产生的收入

时间:2018-01-16 20:40:08

标签: sql sql-server tsql

我搜索了这个网站并完成了谷歌搜索如何转动多个列(销售额和按月收入),但还没找到我想要的东西。我承认我还没有完全围绕PIVOT-ing,所以我可能还没有完全理解已经发布的解决方案。

我尝试做的是使用PIVOT构建查询,该查询将显示每月计数以及购买产品的月收入。

以下是数据的样子:

Product | MonthPurchased | InvoiceNmber | PaymentAmount
====================================================
Pencil          1             10001           1.00 
Pencil          2             10005           1.00 
Pen             1             10002           2.00  
Paper           2             10006           1.00  
Pen             1             10003           2.00
Paper           1             10004           1.00

以下是我放在一起的查询:

INSERT INTO #temp_nbcc_products
        ( [Product], [Month], t_invoice_num, t_payment_amount )

SELECT prd_name, DATEPART(mm, pyd_add_date), invoice_num, payment_amount
FROM product_table ...

SELECT [Product]
    , [1] AS Jan
    , [2] AS Feb
    , [3] AS Mar
    , [4] AS Apr
    , [5] AS May
    , [6] AS June
    , [7] AS July
    , [8] AS Aug
    , [9] AS Sept
    , [10] AS Oct
    , [11] AS Nov
    , [12] AS Dec
    , [1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] AS [Total Count]
FROM
    (
    SELECT t_payment_amount, t_invoice_num, [Month], [Product]
    FROM #temp_nbcc_products
    ) src

PIVOT

    (
     COUNT(t_invoice_num)
     FOR [Month] IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
    ) piv1

ORDER BY [Product] DESC;

以下是查询的输出:

Product | Jan | Feb | March .... Total Counts
=============================================
Pencil     1     1      0             2
Pen        2     0      0             2
Paper      1     1      0             2

我希望结果集看起来像这样:

Product | Jan | Revenue-Jan | Feb | Revenue-Feb .... TotalCounts | TotalRev
========================================================================
Pencil     1       1.00        1       1.00               2          2.00
Pen        2       4.00        0       0.00               2          4.00
Paper      1       1.00        1       1.00               2          2.00

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我认为条件聚合更容易:

SELECT product,
       sum(case when [Month] = 1 then 1 else 0 end) as jan,
       sum(case when [Month] = 1 then t_payment_amount else 0 end) as jan_revenue,
       sum(case when [Month] = 2 then 1 else 0 end) as feb,
       sum(case when [Month] = 2 then t_payment_amount else 0 end) as feb_revenue,
       . . .
FROM #temp_nbcc_products
GROUP BY product

答案 1 :(得分:0)

看起来你知道如何使用PIVOT。

使用GROUP BY只需在PIVOT之前制作基础数据集:

Product | MonthPurchased | TotalMonthCount| TotalPaymentAmount
====================================================
Pencil          1             2              1.00 
Pencil          2             2              1.00 

然后你可以为多列做PIVOT。

In Sql Server how to Pivot for multiple columns