我在SQL中的表中包含这些数据:
Product Size Colour Number
------- ---- ------ ------
Jacket S Red 3
Jacket M Red 2
Jacket S Green 5
Shirt S Blue 1
Shirt L Blue 9
我想通过将所有相同的产品行组合成这样的东西来动态转换它,而不知道我可能有多少行:
Product SRed MRed SGreen SBlue LBlue
------- ---- ---- ------ ----- -----
Jacket 3 2 5
Shirt 1 9
这可能吗?如何?
由于
答案 0 :(得分:0)
I'm not sure if you are looking for something dynamic or static, but this will solve a static issue:
declare @SRed As int
set @SRed = (Select Number from YourTable where Size = 'S' and Colour = 'Red' and Product = 'Jacket')
declare @MRed As int
set @MRed = (Select Number from YourTable where Size = 'M' and Colour = 'Red' and Product = 'Jacket')
declare @SGreen As int
set @SGreen = (Select Number from YourTable where Size = 'S' and Colour = 'Green' and Product = 'Jacket')
declare @SBlue As int
set @SBlue = (Select Number from YourTable where Size = 'S' and Colour = 'Blue' and Product = 'Shirt')
declare @LBlue As int
set @LBlue = (Select Number from YourTable where Size = 'L' and Colour = 'Blue' and Product = 'Shirt')
Create Table #Jacket(Product varchar(20), SRed int, MRed int, SGreen int, IsInTable int)
insert into #Jacket(Product, SRed, MRed, SGreen)
Values(
'Jacket',
@SRed,
@MRed,
@SGreen
)
insert into #Jacket(Product, SRed, MRed, SGreen)
Values(
'shirt',
0,
0,
0
)
Create Table #Shirt(Product varchar(20), SBlue int, LBlue int)
insert into #Shirt(Product, SBlue, LBlue)
Values(
'Shirt',
@SBlue,
@LBlue
)
insert into #Shirt(Product, SBlue, LBlue)
Values(
'Jacket',
0,
0
)
Select s.Product, j.SRed, j.MRed, j.SGreen, s.SBlue, s.LBlue
from #Shirt s
left outer join #Jacket j on j.Product = s.Product