我有两个SELECTS,我将它合并为一个:
SELECT dbo.doss.dosno, dbo.doss.dosnm, SUM(dbo.kbpres.uur) AS somuur, SUM(dbo.kbpres.minuut) AS somminuut, CAST(SUM(dbo.kbpres.uur) + SUM(dbo.kbpres.minuut)
/ 60 AS VARCHAR(4)) + 'u ' + CAST(SUM(dbo.kbpres.minuut) % 60 AS VARCHAR(2)) + 'm' AS derivedColumn, SUM((dbo.kbpres.uur * 60 + dbo.kbpres.minuut)
* dbo.kbpres.prijs) AS TotalCost, dbo.doss.behdr, NULL AS FACKOSTEN
FROM dbo.kbpres INNER JOIN
dbo.doss ON dbo.kbpres.ino = dbo.doss.ino
WHERE (dbo.doss.dosno = '93690')
GROUP BY dbo.doss.dosno, dbo.doss.behdr, dbo.doss.dosnm
UNION
SELECT doss_1.dosno, doss_1.dosnm, NULL AS [somuur], NULL AS [somminuut], NULL AS [derivedColumn], NULL AS [TotalCost], doss_1.behdr, SUM(kbpres_1.prijs) AS FACKOSTEN
FROM dbo.kbpres AS kbpres_1 INNER JOIN
dbo.doss AS doss_1 ON kbpres_1.ino = doss_1.ino
WHERE (doss_1.dosno = '93690') AND (kbpres_1.soort = 'K')
GROUP BY doss_1.dosno, doss_1.dosnm, doss_1.behdr,kbpres_1.soort
单独他们导致一行。所以现在我把UNION产生了两行。但是如何将这个结果分成1行(1个结果)?
答案 0 :(得分:0)
您必须使用以下子查询:
选择a,b,c,(SELECT d,e,f FROM b WHERE blah blah)from a a blah blah GROUP by a.blah
答案 1 :(得分:0)
你能详细说明你要回来的两行,以及你期望回来的那一行吗?
现在回到两行并不奇怪,因为UNION
将汇总您的选择中具有不同值的所有行。 (请注意,如果您的两行相同,UNION
会将它们压缩为一行,而UNION ALL
仍会返回两者。)
我认为你需要做一些像
这样的事情
SELECT ...
FROM
(
-- your query
) q
GROUP BY ...
但同样,由于您的行具有不同的值,您最终可能会得到相同的结果集。我想发布前面提到的细节会给你更好的答案。我可能错过了你想要一起做的事情,但很难根据你帖子中的细节来判断。
答案 2 :(得分:0)
你将不得不摆脱联盟并加入联盟。只要具有唯一别名,您就可以多次加入同一个表。我建议您使用doss表执行from语句,然后执行两次kbpres连接。如下所示:
FROM dbo.doss
INNER JOIN dbo.kbpres ON dbo.doss.ino = dbo.kbpres.ino
INNER JOIN dbo.kbpres AS kbpres_1 ON dbo.doss.ino = dbo.AS kbpres_1.ino AND (kbpres_1.soort = 'K')