按结果替换不存在的组

时间:2017-04-27 12:57:36

标签: sql sql-server group-by

我需要运行这样的查询:

if ( grep { index( $string, $_ ) != -1 } @exampleWords ) { 
    ... 
}

问题是如果第3个月没有数据,它总共返回11行而不是12行。如何用值0替换丢失的日期?

2 个答案:

答案 0 :(得分:3)

您可以创建一个日历表并加入其中,或者您也可以使用这样的特殊日历:

declare @fromdate date = '20170101';
declare @thrudate date = '20171231';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate,@thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo 
                 cross join n as tenK  cross join n as hundredK
  order by [Date]
)
, cal as (
  select
      [Date]
    , [Month]=month([Date])
    , [Year] =year([Date])
  from dates
)

select
    c.[Year]
  , c.[Month]
  , Tons = sum(v.Tons)
from cal c 
  left join MyView v
    on c.[Date] = v.[Date]
where c.[Date] >= '20170101'
  and c.[Date] <= '20171231'
group by c.[Year], c.[Month]
order by c.[Year], c.[Month]

日历和数字表参考:

答案 1 :(得分:1)

您可以将结果连续几个月加入。

  SELECT
        C.M YourMonth,
        COALESCE(Result.TONS, 0) AS TONS
    FROM
    (VALUES(1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) C(M) LEFT JOIN 
    (
        SELECT 
            DATEPART(MONTH, T.Date) YourMonth,
            SUM(T.TONS) AS TONS
        FROM    
            MyView  T 
        WHERE Date BETWEEN '01.01.2017' and '12.31.2017'
        GROUP BY    
            DATEPART(MONTH, T.Date)
    ) Result ON C.M = Result.YourMonth
相关问题