我有一组动态的数据 X ,其形式为:
---------------------------------- x.id | x.allocated | x.unallocated ---------------------------------- foo | 2 | 0 bar | 1 | 2 ----------------------------------
我需要得到 Y 的结果(顺序不重要):
---------------------------------- y.id | y.state ---------------------------------- foo | allocated foo | allocated bar | allocated bar | unallocated bar | unallocated ----------------------------------
我有一个基于UTF的解决方案,但是我正在寻找超高效的解决方案,所以我很想知道是否存在一种基于语句的非过程方式来获得这种“按分组取消”效果?
感觉像是一个枢纽,但我的大脑现在无法到达那里。
使用Sql Server 2005,UNPIVOT和CTE,您可以尝试类似
DECLARE @Table TABLE( id VARCHAR(20), allocated INT, unallocated INT ) INSERT INTO @Table SELECT 'foo', 2, 0 INSERT INTO @Table SELECT 'bar', 1, 2 ;WITH vals AS ( SELECT * FROM ( SELECT id, allocated, unallocated FROM @Table ) p UNPIVOT (Cnt FOR Action IN (allocated, unallocated)) unpvt WHERE Cnt > 0 ) , Recurs AS ( SELECT id, Action, Cnt - 1 Cnt FROM vals UNION ALL SELECT id, Action, Cnt - 1 Cnt FROM Recurs WHERE Cnt > 0 ) SELECT id, Action FROM Recurs ORDER BY id, action