我有这样的表
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。
怎么做?
答案 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
查询的结果集
答案 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