Pivot in SQL 2008 R2

后端 未结 1 996
说谎
说谎 2021-01-29 12:36

I have table like this;

Date        PlacementName    campaignID   Impressions   Clicks   TotalConversions  Activity

01/01/2014    USA             100           5000           


        
1条回答
  •  抹茶落季
    2021-01-29 12:45

    The easiest way to get the result would be to use an aggregate function along with a CASE expression to convert the rows of data into columns, but you could also apply the PIVOT function.

    select date,
      placementname,
      campaignid,
      impressions,
      clicks,
      sum(case when activity = 'Mobile Book' then TotalConversions else 0 end) MobileBook,
      sum(case when activity = 'Mobile TV' then TotalConversions else 0 end) MobileTV
    from yourtable
    group by date, placementname, campaignid, impressions, clicks;
    

    See SQL Fiddle with Demo

    select date, placementname, 
      campaignid, impressions,
      clicks,
      [Mobile Book], [Mobile TV]
    from
    (
      select date, placementname,
        campaignid, impressions,
        clicks, activity, totalconversions
      from yourtable
    ) d
    pivot
    (
      sum(totalconversions)
      for activity in ([Mobile Book], [Mobile TV])
    ) p
    

    See SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题