我有一个看起来像这样的产品表
ProductId Cost
1 200
2 800
3 630
,我有一个statusProduct像这样:
StatusId ProductId StatusDate ProductStatus
1 ,1 ,1-1-17 ,1
2 ,1 ,2-12-17 ,2
3 ,2 ,21-5-17 ,1
4 ,3 ,11-5-18 ,1
5 ,2 ,18-5-18 ,2
6 ,2 ,10-8-18 ,1
我需要查询每个月(月1号)的SUM等于“ ProductStats”为产品成本的1,因此查询应如下所示:
Year Month Costs
2017 1 200
2017 2 200
2017 3 200
2017 4 200
2017 5 200
2017 6 1000
2017 7 1000
2017 8 1000
2017 9 1000
2017 10 1000
2017 11 1000
2017 12 1000
2018 1 800
答案 0 :(得分:0)
您想加入两个表并进行分组,诸如此类。一个额外的挑战可能是您日期列的数据类型。 (VARCHAR?)。然后事情可能会变得有点丑。
SELECT '20' + RIGHT (StatusDate, 2) AS YEAR,
CASE WHEN LEFT (RIGHT ('StatusDate', 5), 1) = '-' THEN RIGHT (LEFT (RIGHT ('StatusDate', 5), 2), 1)
ELSE LEFT (RIGHT ('StatusDate', 5), 2) END AS MNTH,
SUM (Cost) AS TotalCosts
FROM TableA AS A
INNER JOIN TableB AS B ON B.ProductId = A.ProductId
GROUP BY '20' + RIGHT (StatusDate, 2),
CASE WHEN LEFT (RIGHT ('StatusDate', 5), 1) = '-' THEN RIGHT (LEFT (RIGHT ('StatusDate', 5), 2), 1)
ELSE LEFT (RIGHT ('StatusDate', 5), 2)
更好的选择是更改数据类型。
祝你好运!
答案 1 :(得分:0)
假设Simon的评论是正确的,您可以尝试执行以下操作:
SELECT DATEPART(year, StatusDate) As 'Year', DATEPART(month, StatusDate) AS 'Month', SUM(Cost) As 'Cost' FROM
Products p
INNER JOIN
StatusProducts sp
ON
p.ProductId = sp.ProductId
WHERE
sp.ProductStatus = 1
GROUP BY
DATEPART(year, StatusDate), DATEPART(month, StatusDate)
答案 2 :(得分:0)
您需要使用窗口功能来获得运行总计
DECLARE @Years TABLE ([year] int)
DECLARE @months TABLE([month] INT)
INSERT INTo @years([year])
VALUES(2017),(2018)
INSERT INTo @months([month])
VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)
select Y.YEAR,M.MONTH,ISNULL(SUM(Costs) OVER(Partition By Y.Year ORDER BY Y.YEAR,M.MONTH),0) Costs from @years Y
CROSS JOIN @months M
LEFT JOIN (
select YEAR(STatusDate) Year,MONTH(StatusDate) Month,SUM(Cost) Costs from products P
JOIN StatsProduct PS ON P.id= PS.productID
GROUP BY YEAR(STatusDate) ,MONTH(StatusDate)) ProdStats
ON ProdStats.Year=Y.Year and ProdStats.Month=M.Month