每周缺少值的T-SQL数据透视表

时间:2014-05-23 03:21:46

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

我是一个Transact SQL新手(SQL Server 2008)。

我有一个数据透视表,当我按日期范围搜索值时,会获得这些结果:

Person     | 2/10/14 | 2/18/14 
-----------+---------+---------
Jane Doe   | NULL    | QRS 
June Jones | NULL    | XYZ 
Tom Smith  | XYZ     | HIK 

但我需要它看起来像这样,June Jones的值为2/10/14:

Person     | 2/10/14 | 2/17/14 
-----------+---------+--------
Jane Doe   | NULL    | QRS 
June Jones | XYZ     | XYZ 
Tom Smith  | XYZ     | HIK  

问题是June Jones有一个XYZ事件,其start_dt为2/11/14,end_date为2/21/14,应该在'2/10/14'栏中,我的查询似乎丢失了它。 “2/17/14”栏目正在举办活动 我的代码:

WITH Numbers AS 
(
   SELECT '2/10/14' As n
   UNION
   SELECT '2/17/14' As n
) ,
Counted AS
(
  SELECT  s.[FirstName] + ' ' + s.[LastName] AS [Person],
  CASE WHEN s.[Event] = 'Thing1' THEN 'HIK'
       WHEN s.[Event] = 'Thing2' THEN 'QRS'
       WHEN s.[Event] = 'Thing3' THEN 'XYZ'
       ELSE NULL END AS [Info],          
      N.n AS DateWeek
  FROM  [dbo].[MyTable] s
      INNER JOIN Numbers N ON DATEADD(DD,5,N.n) BETWEEN  s.start_dt AND s.end_dt
      WHERE s.LastName in ('Doe', 'Jones', 'Smith')    
  GROUP BY s.[FirstName] + ', ' + s.[LastName], s.[Info], N.n

)
SELECT  [Person], '02/10/14', '2/17/14'
FROM  Counted
    PIVOT ( MAX(Info) FOR DateWeek IN ([2/10/14],  [2/17/14] ))
     AS PVT

我可能遗漏了一些显而易见的东西,但看不到它。

1 个答案:

答案 0 :(得分:-1)

对于第10个,它显示为null因为你的事件从11日开始。