每个月的INT细分总和

时间:2019-01-12 15:27:13

标签: tsql

查询,我用于查找一年中每个站点的总支出。如何按月细分每个产品的支出,即每个月作为一列?

e.DT是一个日期时间,但每个月只填充一次。

select s.StationID, sum(e.Spend)
from Station s with(nolock)
join Expenditure e with(nolock)
on e.ProductID = s.ProductID
where e.DT between '1 JAN 18' and '1 DEC 18'
group by s.StationID
order by sum(e.Spend) desc

2 个答案:

答案 0 :(得分:0)

将您的月/年数据点报告为单独的(而不是列)会容易得多。我建议以下查询:

SELECT
    s.StationID,
    LEFT(CONVERT(varchar, e.DT, 120), 7) AS ym,
    SUM(e.Spend) AS total_spend
FROM Station s WITH(nolock)
INNER JOIN Expenditure e WITH(nolock)
    ON e.ProductID = s.ProductID
WHERE e.DT BETWEEN '2018-01-01' AND '2018-12-01'
GROUP BY
    s.StationID,
    LEFT(CONVERT(varchar, e.DT, 120), 7)
ORDER BY
    s.StationID,
    SUM(e.Spend) DESC;

答案 1 :(得分:0)

以这种方式尝试PIVOT:

select ProductID, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
from (
    select Spend, month(DT) m, ProductID
    from Expenditure
    where DT between '1 JAN 18' and '1 DEC 18'
)  r
PIVOT
( sum(Spend)
    for m in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
)
 AS PivotTable;