将来自2个不同查询的不同列合并为一个结果集

时间:2016-02-05 15:55:05

标签: sql-server tsql

有很多类似的问题,但不完全是我想要的,我会保留一个问题,所以请原谅我,如果这是重复的,因为我无法找到我想要的东西。

我有一个问题:

SELECT TOP 1 t1.Col1, t1.Col2, <need_to_append_here> 
FROM t1 
LEFT OUTER JOIN t2 
ON t1.Id = t2.Id 
WHERE t1.Id = 'x'
ORDER BY t2.Col2 DESC

如果你看到 need_to_append_here ,我需要一个完全不同的sql附加到结果中,所以我在结果集中得到4列:

SELECT t3.Col3, t3.Col4 FROM t3 WHERE t3.Id = 'z'

我应该看到一行有Col1,Col2,Col3,Col4

更新 我能够通过执行类似

的操作来使用第二个查询中的单个列
SELECT * FROM (SELECT TOP 1 t1.Col1, t2.Col2, (SELECT t3.Col3..) Col3
FROM ....

但是我无法在第二个选择中包含2列

3 个答案:

答案 0 :(得分:2)

你可以加入(或左联),因为你正在做TOP 1

SELECT TOP 1
        t1.Col1,
        t1.Col2,
        t3.Col3,
        t3.Col4
FROM    t1
        LEFT OUTER JOIN t2 ON t1.Id = t2.Id
        LEFT OUTER JOIN t3 ON t3.Id = 'z'
WHERE   t1.Id = 'x'
ORDER BY t2.Col2 DESC

答案 1 :(得分:1)

如果附加查询只返回一行,您可以使用CROSS JOIN将其附加到原始查询中:

SELECT TOP 1 t1.Col1, t1.Col2, t3.Col3, t3.Col4
FROM t1 
LEFT OUTER JOIN t2 ON t1.Id = t2.Id 
CROSS JOIN (
   SELECT t3.Col3, t3.Col4 
   FROM t3 
   WHERE t3.Id = 'z') AS t3(Col3, Col4)
WHERE t1.Id = 'x'
ORDER BY t2.Col2 DESC

答案 2 :(得分:0)

您可以将此作为示例使用:

select t1.ks, t1.[# Tasks], coalesce(t2.[# Late], 0) as [# Late]
from 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
left join
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
on
    t1.ks = t2.ks