【问题标题】:Pivot with ID and Dates使用 ID 和日期进行透视
【发布时间】:2015-06-09 20:31:01
【问题描述】:

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

 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

有人可以帮忙吗?

【问题讨论】:

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


    【解决方案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

    【讨论】:

      【解决方案2】:

      试试

      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
      

      【讨论】:

      • 谢谢,我很想尝试,但我无权声明或插入 @abdulnazar
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      相关资源
      最近更新 更多