透视ID和日期

时间:2015-06-09 20:31:02

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

我有这个数据集,我试图为下面的数据创建一个数据透视表。我试图为每种类型的日期输入时遇到一些问题。

 Member ID  Type     Date
   1         A     12/5/2014
   1         b     3/6/2014
   2         a     6/9/2015
   2         b     3/2/2015
   2         c     6/1/2014
   3         a     6/5/2014
   3         c     7/6/2014
   4         c     9/13/2014
   5         a     7/25/2014
   5         b     6/24/2014
   5         c     2/24/2014

然后

我希望它能作为数据透视表出现,如下所示:

   Member ID    A       A date       B        B date      c     C date
   1           Yes      12/5/2014   yes      3/6/2014    Null    Null
   2           Yes      6/9/2015    yes      3/2/2015    Yes    6/1/2014
   3           Yes      6/5/2014    Null      Null       Yes    7/6/2014
   4           Null       Null      Null      Null       Yes    9/13/2014
   5           Yes      7/25/2014   yes      6/24/2014   Yes    2/24/2014

我到目前为止还不包括日期

     SELECT
      MemberID 
     ,Type
     --,Date

     into #Test9

      FROM [Data].[dbo].[Test]

我创建Temp表然后尝试在没有日期的情况下进行透视

     Select *
      From #Test9
        Pivot ( count(type)
         for type in (a]
          ,[b]
          ,[c])) as pvt

请有人帮忙。

2 个答案:

答案 0 :(得分:1)

假设每个成员每个类型只有一个值,您可以使用条件聚合来获得所需的结果:

select 
    memberid,
    max(case when type='a' then 'Yes' end) as "a",
    max(case when type='a' then date end) as "a date",
    max(case when type='b' then 'Yes' end) as "b",
    max(case when type='b' then date end) as "b date",
    max(case when type='c' then 'Yes' end) as "c",
    max(case when type='c' then date end) as "c date"
from your_table
group by MemberID

Sample SQL Fiddle

如果您没有固定数量的类型,可以很容易地将其转换为动态查询; Stack Overflow上有很多很好的答案,它们演示了如何,包括我经常链接到的规范SQL Server Pivot question

答案 1 :(得分:1)

declare @t table(memberid int,[type] char(1),[date] date)
insert into @t(MemberID,[Type],[Date]) values
  ( 1,'A','12/5/2014'),
   (1,'b','3/6/2014'),
   (2,'a','6/9/2015'),
(2,'b','3/2/2015'),
(2,'c','6/1/2014'),
(3,'a','6/5/2014'),
(3,'c','7/6/2014'),
(4,'c','9/13/2014'),
(5,'a','7/25/2014'),
(5,'b','6/24/2014'),
(5,'c','2/24/2014')

select memberid, case when len(a)>0 then 'Yes' end as [A date],a,
case when len(b)>0 then 'Yes' end as [B date],b,
case when len(c)>0 then 'Yes' end [c date] ,c from @t t
pivot( max([date]) for [type] in (a,b,c)) p