我有一个包含三列的表
SELECT
(SELECT COUNT(*) FROM Table1 WHERE IDU = 406536063) as 'col1',
(SELECT COUNT(*) FROM Table2 WHERE CustomerNr = 406536063) as 'col2',
(SELECT COUNT(*) FROM Table3 WHERE CustomerNr = 406536063) as 'col3'
如何在MSSQL第4列中添加col1
,col2
,col3
中的值总和?
答案 0 :(得分:4)
您还可以将查询移至FROM
子句:
SELECT col1, col2, col3, (col1 + col2 + col3)
FROM (SELECT COUNT(*) as col1 FROM Table1 WHERE IDU = 406536063) t1 CROSS JOIN
(SELECT COUNT(*) as col2 FROM Table2 WHERE CustomerNr = 406536063) t2 CROSS JOIN
(SELECT COUNT(*) as col3 FROM Table3 WHERE CustomerNr = 406536063) t3;
虽然我在SELECT
中使用子查询,但我通常将它们放在FROM
子句中。
答案 1 :(得分:2)
使用cte可能会有所帮助:
;with cte (col1,col2,col3) as
(
SELECT
(SELECT COUNT(*) FROM Table1 WHERE IDU = 406536063) as 'col1',
(SELECT COUNT(*) FROM Table2 WHERE CustomerNr = 406536063) as 'col2',
(SELECT COUNT(*) FROM Table3 WHERE CustomerNr = 406536063) as 'col3'
)
select col1+col2+col3
from cte