如果这是重复的话我很抱歉。请指出我正确的问题。我正在使用SQL SERVER 2008.我使用下面的查询,因为我需要从3个表中获取数据。
SELECT qc.FileID as [FileID],
qc.QID1 as [QID1],
xqs.SID1 as [SID1],
xqc.CID1 as [CID1],
xqs.Comments as [SComments],
xqc.Comments as [CComments]
FROM QCTable(nolock) qc
JOIN QCSectionTable (nolock) xqs ON qc.QCID = xqs.QCID
LEFT JOIN QCChargeTable (nolock) xqc ON xqc.QCXrefID = xqs.QCXrefID
对于上面我就是这样 FieID1 SID1 SID1 CID1 SComments CComments
我有一行如下
FileID1 QID1 SID1 CID1 SComments CComments
我需要将上面的行拆分为
FileID1 QID1 SID1 null SComments
FileID1 QID1 SID1 CID1 CComments
提前致谢。
答案 0 :(得分:3)
最简单的方法是union all
:
select FileID1, QID1, SID1, null as cId1, SComments
from table t
union all
select FileID1, QID1, SID1, cId1, CComments
from table t;
如果您有大量数据,使用cross apply
或cross join
执行此操作可能会快一点:
select v.*
from table t cross apply
(values (FileID1, QID1, SID1, null, SComments),
(FileID1, QID1, SID1, cId1, CComments)
) v(FileID1, QID1, SID1, cId1, CComments);
优点是这只能扫描一次表。
答案 1 :(得分:1)
SELECT FileID1, QID1, DID1, null, SComments
FROM table
UNION ALL
SELECT FileID1, QID1, SID1, CID1, CComments
FROM table
答案 2 :(得分:1)
你可以使用UNION ALL
执行类似的操作:
SELECT
qc.FileID AS [FileID1]
,qc.QID1 AS [QID1]
,xqs.SID1 AS [SID1]
,NULL AS [CID1] --assigning default value as null
,xqs.Comments AS [SComments]
FROM QCTable(NOLOCK) qc
JOIN QCSectionTable(NOLOCK) xqs ON qc.QCID = xqs.QCID
LEFT JOIN QCChargeTable(NOLOCK) xqc ON xqc.QCXrefID = xqs.QCXrefID
UNION ALL
SELECT
qc.FileID AS [FileID1]
,qc.QID1 AS [QID1]
,xqs.SID1 AS [SID1]
,xqc.CID1 AS [CID1]
,xqc.Comments AS [CComments]
FROM QCTable(NOLOCK) qc
JOIN QCSectionTable(NOLOCK) xqs ON qc.QCID = xqs.QCID
LEFT JOIN QCChargeTable(NOLOCK) xqc ON xqc.QCXrefID = xqs.QCXrefID