在数据透视查询中乘以列

时间:2016-01-05 09:26:40

标签: sql sql-server sql-server-2012

我在下面有以下查询,可以正常使用。

;with c as
(
    select company, regionId, isnull(profit, 0) profit from MyTable
    where pricedate = '2015-11-30'
)
select * from c as source pivot (max(profit ) for regionId in ([EU], [US], [JP])) as pvt

但我想对查询进行调整。

如果regionId等于US,我想将利润乘以0。 5当regionId等于EU时,我希望将利润乘以0.4&当它的JP多次获利0.1。

我不确定最好的方法吗?我应该在使用case语句的枢轴之前执行此操作还是有更好的方法来执行此操作?

2 个答案:

答案 0 :(得分:1)

试试这个,

    ;WITH c
     AS (SELECT company,
                regionId,
                Isnull(profit, 0) profit
         FROM   MyTable
         WHERE  pricedate = '2015-11-30')
SELECT c.company,
       c.regionid,
       CASE
         WHEN c.regionid = 'US' THEN c.profit * 0.5
         WHEN c.regionid = 'EU' THEN c.profit * 0.4
         WHEN c.regionid = 'JP' THEN c.profit * 0.1
         ELSE c.profit
       END AS profit
FROM   c
       PIVOT (Max(profit )
             FOR regionId IN ([EU],
                              [US],
                              [JP])) AS pvt 

答案 1 :(得分:0)

create table #mytable (company varchar(20), regionid varchar(10), profit money, pricedate date)

insert into 
#mytable

select 'csc', 'EU', 1000,'2015-11-30'
union
select 'csc', 'US', 2000,'2015-11-30'
union
select 'csc', 'JP', 3000,'2015-11-30'
union
select 'hp', 'EU', 5000,'2015-11-30'
union
select 'hp', 'US', 4000,'2015-11-30'
union
select 'hp', 'JP', 3000,'2015-11-30'
union
select 'csc', 'EU', 1100,'2015-11-30'
union
select 'hp', 'EU', 5600,'2015-11-30'



;with c as
(
    select company, regionId, 
     case WHEN regionid = 'US' THEN  isnull(profit, 0) * 0.5
         WHEN regionid  = 'EU' THEN  isnull(profit, 0) * 0.4
         WHEN regionid = 'JP' THEN    isnull(profit, 0) * 0.1
         ELSE  isnull(profit, 0)
         END
         AS profit 
         from #MyTable
    where pricedate = '2015-11-30'
)
select * from c as source pivot (max(profit ) for regionId in ([EU], [US], [JP])) as pvt