查询不将周值显示为0

时间:2015-05-13 12:52:23

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

app/assets/stylesheets/application.css

当我执行此查询时,我会获得第4周和第5周的值,但不会获得其他周的结果。像

SELECT datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, EntryDate), 0)), 0), EntryDate - 1) + 1 as week,
count(UserID) as balance
FROM table_points 
where right(convert(varchar, EntryDate, 106), 8)='Mar 2015'
GROUP BY datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, EntryDate), 0)), 0), EntryDate - 1) + 1

在前3个weeeks中,数据库中没有值,因此它不会显示值。任何人都可以为第1周,第2周和第3周带来0值。

我希望结果为

week balance
4    80
5    100

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

创建一个日历/日期表,包括所有可能的日期/周,然后从那里加入table_points表。 如果table_points中没有数据,那么这几周将返回0。

如果表格中没有日期,则无法选择这些日期并获得零。

示例:

SELECT d.week, count(t.UserID)
FROM dates d left join table_points t on
     d.date = t.EntryDate
where right(convert(varchar, d.date, 106), 8)='Mar 2015'
group by d.week

日期表对于许多应用程序非常有用,可以填写如下:

date       week year month WeekOfMonth DayOfWeek Day     Month
2015-03-01 18   2015 3     1           5         Friday  March
2015-03-02 18   2015 3     1           6         Friday  March
2015-03-03 18   2015 3     1           7         Sunday  March
2015-03-04 19   2015 3     2           1         Monday  March

答案 1 :(得分:0)

这与PSVSupporter的解决方案类似,但使用CTE获取日期列表而不是使用另一个表:

;WITH Dates AS (
        SELECT
         [Date] = CONVERT(DATETIME,'03/01/2015')
        UNION ALL SELECT
         [Date] = DATEADD(DAY, 1, [Date])
        FROM
         Dates
        WHERE
         Date < '03/31/2015'
)
SELECT 
datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, ds.Date), 0)), 0), ds.Date - 1) + 1 as week,
count(tp.UserID) as balance
FROM Dates ds
left join table_points tp on tp.EntryDate = ds.Date
WHERE right(convert(varchar, ds.Date, 106), 8)='Mar 2015'
GROUP BY datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, ds.Date), 0)), 0), ds.Date - 1) + 1

我从https://stackoverflow.com/a/7824893/3309109

中选择了CTE