Pivot in SQL 2008 R2

不问归期 提交于 2019-12-02 14:23:24

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!