从行单元格值中获取多行

时间:2016-02-23 05:59:30

标签: sql sql-server

我有这样的表

Id   Flag1   Flag2     Desc 
--   -----   ------    ----- 
1      1       1        XXX 
2      1       0        YYY

我想要这样的结果

Id   Flag1   Flag2     Desc
--   -----   ------    -----
1      1       1        XXX
1      1       1        XXX
2      1       0        YYY

其中flag的每个条目都为true。

怎么做?

2 个答案:

答案 0 :(得分:0)

WITH tbl(id,flag1,flag2,cnt,descp,idx) AS
  (SELECT id,
    flag1,
    flag2,
    CASE
      WHEN Flag1=1
      AND Flag2 =1
      THEN 2
      ELSE 1
    END cnt,
    descp,
    1
  FROM test2
  UNION ALL
  SELECT a.id,
    a.flag1,
    a.flag2,
    b.cnt,
    a.descp,
    b.idx+1
  FROM test2 a
  JOIN tbl b
  ON (a.id     =b.id
  AND b.idx+1 <= b.cnt)
  )
SELECT * FROM tbl ORDER BY id

查询的结果集

Result set of the query

答案 1 :(得分:0)

<强>更新

由于您有16个标志列,因此可以使用这样的数字表来减少总UNION ALL个查询。只需添加一行中的总标志,并将其与Numbers表的row_number进行比较。

<强>查询

;WITH Numbers AS (SELECT 1 rn UNION ALL SELECT 1 rn UNION ALL SELECT 1 rn UNION ALL SELECT 1 ),
Numbers1 AS (SELECT ROW_NUMBER()OVER(ORDER BY c1.rn) as rn FROM Numbers c1 CROSS JOIN Numbers c2)
SELECT Id, Flag1, Flag2, [Desc] FROM flagtable 
INNER JOIN Numbers1 N ON N.rn <= CONVERT(INT,flag1) + CONVERT(INT,flag2)
ORDER BY Id ASC

您可以使用UNION ALL。这样的事情。

<强>查询

SELECT Id, Flag1, Flag2, [Desc] FROM flagtable WHERE Flag1 = 1
UNION ALL
SELECT Id, Flag1, Flag2, [Desc] FROM flagtable WHERE Flag2 = 1
ORDER BY Id

<强>输出

Id  Flag1   Flag2   Desc
1   1   1   XXX
1   1   1   XXX
2   1   0   YYY