SQL显示数据行,即使没有值

时间:2015-08-12 14:26:26

标签: sql sql-server sql-server-2008

我正在尝试输出当月的每个日期,但去年每个日期的值都有,有些日期可能有0,所以仍然需要输出结果。

SQL Server 2008

我目前正在接受:

Day | Value
1   | 500
2   | 437
5   | 976

我更愿意:

        Day | Value
        1   | 500
        2   | 437
        3   | 0
        4   | 0
        5   | 976

这是我的SQL脚本:

SELECT SUM(O_VALUE) AS Value, DAY(O_DATE) AS Day
FROM dbo.table
WHERE (MONTH(O_DATE) = MONTH(GETDATE())) 
  AND (YEAR(O_DATE) = YEAR(GETDATE()) - 1)
GROUP BY O_DATE
ORDER BY O_DATE

2 个答案:

答案 0 :(得分:1)

我希望这会对你有所帮助

 -- declare the table
DECLARE @temp TABLE (
  d int,
  v int
)

INSERT INTO @temp VALUES (1, 500)
INSERT INTO @temp VALUES (2, 437)
INSERT INTO @temp VALUES (5, 976)

-- Common Table Expression
;WITH Missing (missnum, maxid)
AS (SELECT 1 AS missnum, (SELECT MAX(d)  FROM @temp)
UNION ALL
SELECT missnum + 1, maxid
FROM Missing
WHERE missnum < maxid)

-- select from table and Common Table Expression
SELECT * FROM @temp
UNION
SELECT missnum,0
FROM Missing
LEFT OUTER JOIN @temp tt ON tt.d = Missing.missnum
WHERE tt.d IS NULL
OPTION (MAXRECURSION 0);

答案 1 :(得分:1)

测试数据

DECLARE @TABLE TABLE([Day] INT, Value INT)

INSERT INTO @TABLE VALUES
(1    ,500),
(2    ,437),
(5    ,976)

查询

;WITH x AS
 (
  SELECT 1 AS [Days] UNION ALL SELECT 2 UNION ALL SELECT 3
  UNION ALL SELECT 4 UNION ALL SELECT 5 
  )
SELECT COALESCE(x.[Days] , t.[day]) AS [Day]
       ,ISNULL(t.Value,0) AS Value
FROM x LEFT JOIN @TABLE t   --<-- Instead of this table variable put your query as 
ON x.Days = T.[Day]            --as a sub-query here and join to that

结果

╔═════╦═══════╗
║ Day ║ Value ║
╠═════╬═══════╣
║   1 ║   500 ║
║   2 ║   437 ║
║   3 ║     0 ║
║   4 ║     0 ║
║   5 ║   976 ║
╚═════╩═══════╝