MSSQL:如何添加一个总和另外三个列的列

时间:2018-02-07 13:34:22

标签: sql sql-server

我有一个包含三列的表

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列中添加col1col2col3中的值总和?

2 个答案:

答案 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