T-SQL将行拆分成多行?

时间:2013-08-05 22:59:06

标签: sql sql-server tsql

我在sql db中有这样的表。

Category Series Value
  1        A    100
  2        B    200
  2        C    300

如何选择这样投射?

Category Series Value
  1        A    100
  1        B    0
  1        C    0
  2        A    0
  2        B    200
  2        C    300

1 个答案:

答案 0 :(得分:2)

为了获得结果,您需要生成每个系列的所有类别的列表。您可以使用CROSS JOIN来获得结果:

select distinct c.category, s.series
from yourtable s
cross join yourtable c

完成此操作后,您可以在categoryseries上将其加入到您的表格中:

select sc.category,
  sc.series,
  coalesce(t.value, 0) value
from 
(
  select distinct c.category, s.series
  from yourtable s
  cross join yourtable c
) sc
left join yourtable t
  on sc.series = t.series
  and sc.category = t.category;

请参阅SQL Fiddle with Demo

相关问题