SQL中两列的元素商

时间:2012-06-05 01:37:24

标签: sql database

如何组合两个SELECT语句返回的列来提供元素商?

查询1:

SELECT COUNT(*) AS count
FROM table1
WHERE col2 = 1 AND col3 > 5
GROUP BY col4
ORDER BY col4

查询2:

SELECT COUNT(*) AS count
FROM table1
WHERE col2 = 1
GROUP BY col4
ORDER BY col4

所以,如果他们返回的内容如下:

Query 1        Query 2
count           count
-----------------------
1              5
2              4

我会得到:

quotient
-------
0.2
0.5

3 个答案:

答案 0 :(得分:2)

对于问题的4列版本,我们可以假设商在col4中具有相同值的组之间。所以,答案就变成了:

SELECT col4, SUM(CASE WHEN col3 > 5 THEN 1 ELSE 0 END) / COUNT(*) AS quotient
  FROM table1
 WHERE col2 = 1
 GROUP BY col4;

我在输出中保留了col4,因为我不认为比率(商)在没有确定哪个商与哪些值相关联的情况下会有用,尽管从理论上讲,答案不需要输出中的那一列。

答案 1 :(得分:1)

如果您的实际查询无法按照其他答案进行简化,您可以加入子查询,如下所示:

select j1.count / j2.count as quotient
from (
   SELECT col4, COUNT(*) AS count
   FROM table1
   WHERE col2 = 1 AND col3 > 5
   GROUP BY col4      
) j1
join (
   SELECT col4, COUNT(*) AS count
   FROM table1
   WHERE col2 = 1
   GROUP BY col4
) j2 on j1.col4=j2.col4

答案 2 :(得分:1)

在这种情况下,您根本不需要两个单独的查询:

SELECT   SUM(col3 > 5) / COUNT(*)
FROM     table1
WHERE    col2 = 1
GROUP BY col4
ORDER BY col4