怎么使用PIVOT转换SELECTSUM(CASE SummaryDate WHEN 2013-06-02 THEN RevenueMoney END) AS [今天],SUM(
怎么使用PIVOT转换
SELECT
SUM(CASE SummaryDate WHEN '2013-06-02' THEN RevenueMoney END) AS [今天],
SUM(CASE SummaryDate WHEN '2013-06-01' THEN RevenueMoney END) AS [昨天],
SUM(CASE SummaryDate WHEN '2013-05-31' THEN RevenueMoney END) AS [前天],
SUM(CASE SummaryDate WHEN '2013-05-26' THEN RevenueMoney END) AS [上周],
SUM(CASE SummaryDate WHEN '2013-05-02' THEN RevenueMoney END) AS [上月],
SUM(CASE SummaryDate WHEN '2013-05-02' THEN RevenueMoney END) AS [上年]
FROM dbo.Summary where SId = '001'
怎么使用PIVOT转换
[解决办法]--表一
if object_id('a1','u') is not null
drop table a1
create table a1
( BH varchar(10),SP varchar(20),GSBH varchar(10))
insert into a1 select '001','汽车','001' union all select '002','树','001' union all
select '003','汽车','002' union all select '004','自行车','002' union all
select '005','汽车','003' union all select '006','汽车','001'
--表二
if object_id('a2','u') is not null
drop table a2
create table a2
(BH varchar(10),GS varchar(20))
insert into a2 select '001','公司1' union all select '002','公司2' union all
select '003','公司3'
--表三
if object_id('a3','u') is not null
drop table a3
create table a3
(BH varchar(10),QY varchar(20),GSBH varchar(20))
insert into a3 select '001','区域1','001,002' union all select '002','区域2','001,003'
--表四
if object_id('a4','u') is not null
drop table a4
select a.BH,a.SP,a.GSBH,b.GS,c.QY
into a4 from a1 as a,a2 as b,a3 as c
where (a.GSBH = b.BH and b.BH = substring(c.GSBH,0,charindex(',',c.GSBH)))
or (a.GSBH = b.BH and b.BH = substring(c.GSBH,charindex(',',c.GSBH)+1,len(c.GSBH)-charindex(',',c.GSBH)))
--select * from a4
select *,p.树+p.汽车+p.自行车 as 总计
from
(
select QY,SP from a4) as p
pivot(count(SP) for SP in(汽车,树,自行车)) as p