SQL一个查询中的多个select count语句

时间:2012-06-28 11:25:09

标签: sql database tsql

我的数据没有关系。只需要计算3个表中的各个列,并将它们作为视图显示在页面上。

到目前为止,这是代码,但不起作用:

SELECT COUNT(cars) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C,
 FROM tableCars

5 个答案:

答案 0 :(得分:14)

SELECT A, B, C
FROM (SELECT COUNT(cars) as A FROM tableCars) a
CROSS JOIN (SELECT COUNT(boats) as B FROM tableBoats) b
CROSS JOIN (SELECT COUNT(trees) as C FROM tableTrees) c

应该这样做。

答案 1 :(得分:14)

假设你有一个像这里的表(tableXxx表有一个名为xxx的字段),你的查询在AS C,之后有一个逗号,没有逗号,它有语法错误,它工作正常(至少使用sqlite,因为mssql不能在sqlfiddle上工作):

http://sqlfiddle.com/#!5/5fa6c/3

SELECT COUNT(cars) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C
FROM tableCars

顺便说一句,您可以将查询简化为

SELECT (SELECT COUNT(cars ) FROM tableCars ) AS A,
       (SELECT COUNT(boats) FROM tableBoats) AS B,
       (SELECT COUNT(trees) FROM tableTrees) AS C

其他答案也很完美:)

答案 2 :(得分:3)

这个怎么样?

SELECT
    (SELECT COUNT(*) FROM tableCars) car_count,
    (SELECT COUNT(*) FROM tableBoats) boat_count,
    (SELECT COUNT(*) FROM tableTrees) tree_count

答案 3 :(得分:1)

继Luc M的响应(提供单个列表)与具有单独值的列之后。 你可以想象这可能是多么有用......

SELECT C.Accountnum as AccountNum, C.Address as Address, 'C' as Source 
From CustTable C 
Where C.AccountNum like '000%' 
Union All 
Select V.Accountnum as AccountNum, V.Name as Address, 'V' as Source 
from VendTable V 
Where V.AccountNum like 'A%'

答案 4 :(得分:0)

SELECT *
FROM 
(
   SELECT 'Nb cars'  as description, COUNT(cars)  AS count_item FROM tableCars
   UNION ALL
   SELECT 'Nb boats' as description, COUNT(boats) AS count_item FROM tableBoats
   UNION ALL
   SELECT 'Nb tress' as description, COUNT(trees) AS count_item FROM tableTrees
) temp