1

如何组合两个SELECT语句返回的列以给出它们的元素商数?

查询一:

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
4

3 回答 3

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在输出中,因为我认为如果没有确定哪个商与哪些值相关联的东西,比率(商)将没有用,尽管理论上,答案不希望输出中的该列。

于 2012-06-05T01:57:48.983 回答
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
于 2012-06-05T01:46:40.383 回答
1

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

SELECT   SUM(col3 > 5) / COUNT(*)
FROM     table1
WHERE    col2 = 1
GROUP BY col4
ORDER BY col4
于 2012-06-05T01:55:57.953 回答