如何获取SQL中多列的计数

时间:2013-11-28 23:47:03

标签: sql count database-table

假设我在SQL中有两个表。现在我想获得表1的计数和表2的计数的商。我该怎么做?

简而言之:

(# of rows in table 1) / (# of rows in table 2)

编辑: 这就是我试过的:

SELECT COUNT(t1.a) / COUNT(t2.a)
FROM table1 t1, table2 t2

3 个答案:

答案 0 :(得分:1)

以下是获得结果的一种方法:

SELECT c1.cnt / c2.cnt AS q
  FROM ( SELECT COUNT(1) AS cnt
           FROM table1
       ) c1
 CROSS
  JOIN ( SELECT COUNT(1) AS cnt
           FROM table2
       ) c2

获得等效结果的另一种方法:

SELECT (SELECT COUNT(1) FROM table1) / (SELECT COUNT(1) FROM table2) AS q

如果我还需要将表中的计数作为结果集中的单独列返回,我更喜欢第一个查询,例如:

 SELECT c1.cnt          AS table1_count
      , c2.cnt          AS table2_count
      , c1.cnt / c2.cnt AS q
   FROM ...

答案 1 :(得分:-1)

with 
    Ctable1 as
        (select count(*) as num1 from table1),
    Ctable2 as
        (select count(*) as num2 from table2)
select num1 / num2 as quotient
from Ctable1,Ctable2 

<强>记住:

  • 计算列时,具有“NULL”数据的行将不计算在内。 (如果使用Oracle,则可以使用count(a。*)
  • 像大多数语言一样在sql中划分,返回int。 (5/2 = 2而不是2.5)。

答案 2 :(得分:-1)

试试这个:

SELECT COUNT(table1.column) as 'Table 1 Count'
,COUNT(table2.column) as 'Table 2 Count'
,COUNT(table1.column) / COUNT(table2.column) as 'Quotient'
FROM table1, table2