如何修改以下代码以忽略0行,并显示每周输出

时间:2015-08-07 10:19:16

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我的以下查询给出了图1中所示的输出。我想更改它以便它给出图2中的输出。我想显示周向(即使值为0)这是查询。请帮忙。

SELECT @MaxDate = @MaxDate
    ,@MinDate = dateadd(week, (@LastXWeeks + 1), @MaxDate);

WITH AllDates
AS (
    SELECT @MinDate AS xDate

    UNION ALL

    SELECT Dateadd(day, 1, xDate)
    FROM AllDates AS ad
    WHERE ad.xDate < @MaxDate
    )
SELECT 'playing' AS activity
    ,ad.xDate
    ,Isnull(t.TimePerDay, 0) AS TimePerDay
FROM AllDates AS ad WITH (NOLOCK)
LEFT JOIN @test AS t ON ad.xDate = t.DATE

Figure 1

Figure 2

2 个答案:

答案 0 :(得分:3)

您想要每周结果,因此按周分组:

WITH AllDates
AS (
    SELECT @MinDate AS xDate

    UNION ALL

    SELECT Dateadd(day, 1, xDate)
    FROM AllDates AS ad
    WHERE ad.xDate < @MaxDate
    )
SELECT 
  'playing' AS activity
  ,min(ad.xDate) -- or max or the week number, whichever you like best
  ,Isnull(sum(t.TimePerDay), 0) AS TimePerDay
FROM AllDates AS ad WITH (NOLOCK)
LEFT JOIN @test AS t ON ad.xDate = t.DATE
GROUP BY datepart(wk, ad.xDate);

答案 1 :(得分:0)

试试这个

SELECT @MaxDate = @MaxDate
    ,@MinDate = dateadd(week, (@LastXWeeks + 1), @MaxDate);

WITH AllDates
AS (
    SELECT @MinDate AS xDate

    UNION ALL

    SELECT Dateadd(day, 1, xDate)
    FROM AllDates AS ad
    WHERE ad.xDate < @MaxDate
    )
SELECT * FROM
(
SELECT 'playing' AS activity
    ,ad.xDate
    ,Isnull(t.TimePerDay, 0) AS TimePerDay
FROM AllDates AS ad WITH (NOLOCK)
LEFT JOIN @test AS t ON ad.xDate = t.DATE
) as t WHERE TimePerDay<>0