在SQL Server中翻转数据

时间:2015-05-08 20:55:00

标签: sql sql-server

我有table a

Name  District Source  Revenue
Dave   34       A       120
John   36       B       140
Juyt   38       C       170 

table b

Name District Product Cost
Dave  34       A        50
John  36       B        40

我想要一个这样的观点。期望的观点如下。

Name  District Source  Revenue  A    B   Total Cost 
Dave   34       A       120     50   0     50
John   36       B       140     0    40    40 
Juyt   38       C       170     0    0     0

表b中的每次查找都没有修复产品数量。当您没有修复产品A,产品B等产品的数量时,有没有办法取消。我不想做动态SQL和动态unpivot。是否还有其他选项可以获得所需的视图?

1 个答案:

答案 0 :(得分:1)

根据你的样本数据,我已经给你输出

declare @t table (name varchar(10),District int,Source varchar(2),Revenue int)
insert into @t (name,District,Source,Revenue)values ('dave',34,'A',120),
('john',36,'B',140),('juyt',38,'C',170)

declare @tt table (name varchar(10),District int,product varchar(2),cost int)
insert into @tt (name,District,product,cost)values ('dave',34,'A',50),
('john',36,'B',40)


select A.name,A.District,A.Source,A.Revenue,A.A,A.B,
SUM(A + B) TotalCost from  (
select t.name,
t.District,
t.Source,
t.Revenue,
CASE WHEN tt.product = 'A' THEN cost ELSE 0 END A ,
CASE WHEN tt.product = 'B' THEN cost ELSE 0 END B 
 from @t t
 left join @tt tt on 
 t.name = tt.name 
 AND 
 t.District = tt.District )A
 GROUP BY A.name,A.District,A.Source,A.Revenue,A.A,A.B