6

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

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

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

5 回答 5

15
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

应该这样做。

于 2012-06-28T11:30:14.973 回答
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

其他答案也很完美:)

于 2012-06-28T11:52:44.843 回答
3

这个怎么样?

SELECT
    (SELECT COUNT(*) FROM tableCars) car_count,
    (SELECT COUNT(*) FROM tableBoats) boat_count,
    (SELECT COUNT(*) FROM tableTrees) tree_count
于 2012-06-28T11:57:28.470 回答
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%'
于 2013-09-09T14:15:19.227 回答
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
于 2012-06-28T11:36:27.823 回答