这里我有2个查询:
SELECT bk, search, ckey, dn
FROM
(SELECT t1_bk_no AS 'bk',
t1_full_key AS 'ckey',
CAST(t1_info1 AS VARCHAR(100)) AS [1],
CAST(t1_info2 AS VARCHAR(100)) AS [2],
CAST(t1_info3 AS VARCHAR(100)) AS [3],
CAST(t1_info4 AS VARCHAR(100)) AS [4],
CAST(t1_info5 AS VARCHAR(100)) AS [5]
FROM dbo.FirstTable) PNT
UNPIVOT( searcg FOR dn IN ( [1],[2],[3],[4],[5] ) ) AS UPV
WHERE search NOT IN ( '0', '999999999', '') AND search IS NOT NULL
和
SELECT bk, search, ckey, dn
FROM
(SELECT t2_bk_no AS 'bk',
t2_full_key AS 'ckey',
CAST(t2_info1 AS VARCHAR(100)) AS [6],
CAST(t2_info2 AS VARCHAR(100)) AS [7],
CAST(t2_info3 AS VARCHAR(100)) AS [8]
FROM dbo.SecondTable) PNT
UNPIVOT( search FOR dnIN ( [1],[5],[7] ) ) AS UPV
WHERE search NOT IN ( '0', '999999999', '') AND search IS NOT NULL
基本上我想加入这两个表。苦苦寻找将连接语句放在何处。
感谢任何帮助,谢谢。
答案 0 :(得分:0)
如果没有看到期望的结果,似乎您可以使用UNION ALL查询,因为列看起来是相同的:
SELECT bk, search, ckey, dn
FROM
(
SELECT t1_bk_no AS 'bk',
t1_full_key AS 'ckey',
CAST(t1_info1 AS VARCHAR(100)) AS [1],
CAST(t1_info2 AS VARCHAR(100)) AS [2],
CAST(t1_info3 AS VARCHAR(100)) AS [3],
CAST(t1_info4 AS VARCHAR(100)) AS [4],
CAST(t1_info5 AS VARCHAR(100)) AS [5]
FROM dbo.FirstTable
) PNT
UNPIVOT( search FOR dn IN ( [1],[2],[3],[4],[5] ) ) AS UPV
WHERE search NOT IN ( '0', '999999999', '') AND search IS NOT NULL
UNION ALL
SELECT bk, search, ckey, dn
FROM
(
SELECT t2_bk_no AS 'bk',
t2_full_key AS 'ckey',
CAST(t2_info1 AS VARCHAR(100)) AS [6],
CAST(t2_info2 AS VARCHAR(100)) AS [7],
CAST(t2_info3 AS VARCHAR(100)) AS [8]
FROM dbo.SecondTable
) PNT
UNPIVOT( search FOR dnIN ( [1],[5],[7] ) ) AS UPV
WHERE search NOT IN ( '0', '999999999', '') AND search IS NOT NULL;