SQL Pivot - Union 2查询

时间:2018-02-26 15:56:06

标签: sql sql-server

我有以下查询创建一个数据透视表,第一行显示布料大小:S,M,L和XL。

SELECT * 
FROM (SELECT 
        [LOC],
        [QUANTITY],
        [SIZE]
  FROM [TABLE]

  WHERE [Item]= '123456') s 

  PIVOT (SUM([QUANTITY]) FOR [SIZE] IN ([S],[M],[L],[XL])) pvt

导致:

  LOC       S   M   L   XL
  USA       2   2   1
  EUR       1   2   2   1
  ASIA      1   2   2   1

因为某些产品有不同的尺寸表(例如:男士有:S,M,L。女性有:36,38,40),我想将上述查询与此结合起来,显示可用尺寸指定的产品。 所以第一行是基于Table-Sizing的可用大小。

  SELECT * FROM [TABLE-Sizing] WHERE [Item] = '123'

结果:

  34
  36
  38

我希望有人可以帮助我!

谢谢!

[EDIT1] 我尝试在第二个查询中使用UNION,但不知道在最后一行中要插入什么来使用它:

SELECT * 
FROM (SELECT 
        [LOC],
        [QUANTITY],
        [SIZE]
  FROM [TABLE]

  WHERE [Item]= '123456')
  UNION
  SELECT [SIZE]
  FROM [TABLE-SIZING] s 

  PIVOT (SUM([QUANTITY]) FOR [SIZE] IN (?????)) pvt

1 个答案:

答案 0 :(得分:0)

如上所述,您首先需要一系列可能性:

我会将所有这些结合成一个cte并在stuff语句中使用它代替table

--I used a classic stuff technique combined with quotename which brackets the answers

declare @possibilities varchar(max);
;with cte as (
select distinct size from table
union all
select distinct size from [different table]
)
select @possibilities = stuff( (select distinct ','+QUOTENAME(SIZE) from cte for xml path(''))
                ,1,1,'')

--Now create dynamic SQL

declare @sql varchar(max);
set @sql = 
'SELECT * 
FROM (SELECT 
        [LOC],
        [QUANTITY],
        [SIZE]
  FROM [TABLE]

  WHERE [Item]= '123456') s 

  PIVOT (SUM([QUANTITY]) FOR [SIZE] IN ('

+ @possibilities
+ ') pvt'

EXECUTE(@sql)