如何在MS SQL中将行拆分为两行

时间:2015-10-02 09:18:08

标签: sql sql-server tsql

我得到一行,其中包含两列中的非零值:FixHoursAddHours

FixHours | AddHours | CalculatedValue
---------+----------+----------------
     0,5 |      1,5 |            16.5

如何将其拆分为两行,例如:

FixHours | AddHours | CalculatedValue
---------+----------+----------------
     0,5 |        0 |            16.5
       0 |      1,5 |            16.5

我有一个想法是找到该行并使用union运算符人为地制作第二行。但是我有很多行同时在两列中包含值。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

假设我正确理解你的问题,我认为你正在寻找的是这样的东西:

SELECT FixHours, AddHours, CalculatedValue
FROM tbl
WHERE FixHours = 0
OR AddHours = 0

UNION

SELECT FixHours, 0, CalculatedValue
FROM tbl
WHERE FixHours <> 0
AND AddHours <> 0

UNION

SELECT 0, AddHours, CalculatedValue
FROM tbl
WHERE FixHours <> 0
AND AddHours <> 0

答案 1 :(得分:1)

这样的事情应该这样做:

select
 case when x=1 THEN 0 ELSE fixHours END as fixHours,
 case when x=2 THEN 0 ELSE addHours END as addHours,
 calculatedValue
from input
 cross join (select 1 as x UNION select 2 as x)

答案 2 :(得分:1)

试试这个

SELECT FixHours, 0 AS AddHours, CalculatedValue
FROM table
UNION
SELECT 0, AddHours, CalculatedValue
FROM table

答案 3 :(得分:0)

SELECT Split.FixHours
      ,Split.AddHours
      ,YourTable.CalculatedValue
FROM YourTable
     CROSS APPLY (
         VALUES (FixHours, 0), (0, AddHours)
     ) AS Split(FixHours, AddHours)