我想要使用带有SSRS的图表来表示一些数据。在我生成此报告之前,我正在尝试考虑确实存在的数据。我已经设置了一个小型数据集市,它汇总了每日总数。对于某些组,特定周的数据不存在。我正在寻找一种方法来计算这些数据,所以当我开始生成报告时,线图表示实际数据,0表示确实存在的值。举个例子:
yearnbr weeknbr restaurant mealsserved
2014 1 Joes Pasta 5
2014 2 Joes Pasta 4
2014 4 Joes Pasta 2
通过上面的例子,第三周的数据不存在。我想生成一个可以在第3周插入0或null值的查询。当我生成报告时,第2周和第4周的数据连接。我需要在第3周插入0或Null。我使用的是SQL Server 2008 R2。
答案 0 :(得分:2)
您需要有一个结果集才能加入。
您可以动态生成它:
WITH weeks (w) AS
(
SELECT 1
UNION ALL
SELECT w + 1
FROM weeks
WHERE w < 54
)
SELECT *
FROM weeks
LEFT JOIN
sales
ON year = 2014
AND weeknbr = w
但表现会很糟糕。
最好使用数字创建和填充表格(一次):
CREATE TABLE num (n INT NOT NULL PRIMARY KEY)
WITH q (n) AS
(
SELECT 1
UNION ALL
SELECT n + 1
FROM q
WHERE n < 100000
)
INSERT
INTO num
SELECT n
FROM q
然后在上面的查询中使用它:
SELECT *
FROM num
LEFT JOIN
sales
ON year = 2014
AND weeknbr = n
答案 1 :(得分:1)
测试数据
DECLARE @TABLE TABLE
(
yearnbr INT,
weeknbr INT,
restaurant VARCHAR(20),
mealsserved INT
)
INSERT INTO @TABLE VALUES
(2014 ,1 ,'Joes Pasta',5),
(2014 ,2 ,'Joes Pasta',4),
(2014 ,4 ,'Joes Pasta',2)
查询
SELECT COALESCE(yearnbr,[Year]) AS yearnbr
,COALESCE(weeknbr,[Week]) AS weeknbr
,ISNULL(restaurant, '') AS restaurant
,ISNULL(mealsserved, 0) AS mealsserved
FROM @TABLE t RIGHT JOIN
(
VALUES (YEAR(GETDATE()), 1),
(YEAR(GETDATE()), 2),
(YEAR(GETDATE()), 3),
(YEAR(GETDATE()), 4)
) A([Year],[Week])
ON t.yearnbr = A.[Year] AND t.weeknbr = A.[Week]
结果
╔═════════╦═════════╦════════════╦═════════════╗
║ yearnbr ║ weeknbr ║ restaurant ║ mealsserved ║
╠═════════╬═════════╬════════════╬═════════════╣
║ 2014 ║ 1 ║ Joes Pasta ║ 5 ║
║ 2014 ║ 2 ║ Joes Pasta ║ 4 ║
║ 2014 ║ 3 ║ ║ 0 ║
║ 2014 ║ 4 ║ Joes Pasta ║ 2 ║
╚═════════╩═════════╩════════════╩═════════════╝
答案 2 :(得分:0)
您可以Join
到周数表。您可以尝试以下一个想法:
Declare @Week Table (N TinyInt Not Null)
Insert @Week Values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)
Select *
From Table T
Right Join
(
Select (A.N + (10 * B.N)) Week
From @Week A
Cross Join @Week B
) W On T.weeknbr = W.Week
Where W.Week Between 1 And 52
Order By W.Week