我正在使用SSRS通过Matrix开发报告。
我每月对产品销售数量求和,但如果某个月销售数量为0,则单元格将为Nothing
。
我正在尝试使用Previous
函数来解决问题但这个函数似乎不适用于Matrix对象。
有没有办法做到这一点?
第一张表是当前的报告结果。 第二张表是我想要的。
答案 0 :(得分:0)
假设您有一个表格,其结构和内容如下:
CREATE TABLE a (date Date, product_name NVarchar(20), sale_qty Decimal(10,2))
INSERT INTO a (date, product_name, sale_qty) VALUES ('20130510','product A',1)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20130601','product A',0)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20130501','product B',5)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20140205','product A',1)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20140215','product A',1)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20140202','product B',2)
INSERT INTO a (date, product_name, sale_qty) VALUES ('20140301','product A',0)
然后下面的sql语句将为你工作(据我所知):
SELECT
y.Date2 AS 'yyyy/mm'
, y.product_name
, ISNULL(z.Month_sale_QTY,0) AS Month_sale_QTY
FROM
(SELECT
DATEADD(MONTH, x.number, y.StartDate) AS Date2
, (SELECT TOP 1 DATEADD(d,1-DATEPART(d,a.date),a.date) FROM a WHERE DATEADD(d,1-DATEPART(d,a.date),a.date) <= DATEADD(MONTH, x.number, y.StartDate) AND a.product_name = p.product_name AND ISNULL(a.sale_qty,0)<>0 ORDER BY 1 DESC) AS Date3
, p.product_name
FROM
master.dbo.spt_values x
INNER JOIN
(SELECT Dateadd(d,1-DATEPART(d, MIN(Date)), MIN(Date)) AS StartDate, MAX(Date) AS EndDate FROM a) AS y
ON x.number <= DATEDIFF(MONTH, y.StartDate, y.EndDate)
,(SELECT DISTINCT product_name FROM a) AS p WHERE x.type = 'P') y
LEFT JOIN
(SELECT
DATEADD(d,1-DATEPART(d,a.date),a.date) AS Date2
, a.product_name
, SUM(a.sale_qty) as Month_sale_QTY
FROM a
GROUP BY
DATEADD(d,1-DATEPART(d,a.date),a.date)
, a.product_name
) z ON y.Date3 = z.Date2 AND y.product_name = z.product_name
返回以下内容:
yyyy/mm product_name Month_sale_QTY
---------- -------------------- ---------------------------------------
2013-05-01 product A 1.00
2013-06-01 product A 1.00
2013-07-01 product A 1.00
2013-08-01 product A 1.00
2013-09-01 product A 1.00
2013-10-01 product A 1.00
2013-11-01 product A 1.00
2013-12-01 product A 1.00
2014-01-01 product A 1.00
2014-02-01 product A 2.00
2014-03-01 product A 2.00
2013-05-01 product B 5.00
2013-06-01 product B 5.00
2013-07-01 product B 5.00
2013-08-01 product B 5.00
2013-09-01 product B 5.00
2013-10-01 product B 5.00
2013-11-01 product B 5.00
2013-12-01 product B 5.00
2014-01-01 product B 5.00
2014-02-01 product B 2.00
2014-03-01 product B 2.00
我确信它可以使用窗口函数和/或CTE进行优化,但作为一种快速解决方案,这个也可以使用。