Pivot in SQL 2008 R2

2019-03-07 02:31发布

I have table like this;

Date        PlacementName    campaignID   Impressions   Clicks   TotalConversions  Activity

01/01/2014    USA             100           5000          500        50        Mobile Book
01/02/2014    U.K             101           7000          250        30        Mobile Book
01/01/2014    USA             100           9000          800        40        Mobile TV
01/02/2014    U.K             101           6000          300        10        Mobile TV

I want to pivot table for 15-20 Activity from the real table because this is just example table.

I want my table look like below;

Date         PlacementName     CampaignID    Impressions    Clicks   Mobile Book  Mobile TV
01/01/2014    USA              100           5000           500       50           NULL
01/01/2014    U.K              100           9000           800       NULL         40
01/02/2014    USA              101           7000           250       30           NULL
01/02/2014    U.K              101           6000           300       NULL         10

This is the format I want in final table. I want to write query for this table.

1条回答
Viruses.
2楼-- · 2019-03-07 02:51

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

查看更多
登录 后发表回答