如何形成子查询

时间:2014-03-08 11:57:41

标签: mysql

我想我需要一个子查询,虽然我已经阅读了子查询,但我还没有找到如何编写子查询的帮助。我有兴趣学习如何钓鱼,但我也很想要一条鱼,请:)

简单,1个数据表: lastname,(找到或未找到布尔值)

我希望在整个字母表中生成一些已被发现的统计数据。

Desired results:
A : 5 of 16 found, or about 31 percent
B : 2 of 4 found, or about 50 percent
C : 30 of 90 found, or about 30 percent
etc

我可以构建简单的SQL,我需要帮助形成子查询,如果这是需要的话。

我可以编写一个查询来列出姓氏的第一个字母找到的数量:

select substring(lastname,1,1) as lastinitial, count(*) from members where found !=0 and found is not null group by lastinitial;

我可以编写一个查询来列出最终总数的总数:

select substring(lastname,1,1) as lastinitial, count(*) from members group by lastinitial;

但是如何组合这两个查询以产生所需的结果呢?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可能不需要进行子查询。分组可以为每个名称提供找到和未找到的内容。只需将“找到”添加到分组中,您将获得每个名称的两条记录,一条用于找到,另一条用于找不到。您也不需要另外查询总数,只需添加找到的内容而不是一起找到。

SELECT SUBSTRING(lastname,1,1) AS lastinitial,
       (CASE WHEN found = 1 THEN 1 ELSE 0 END) AS found_val,
       COUNT(lastname) AS found_count
FROM members
GROUP BY lastinitial, found_val;

如果您希望每个字母都包含找到的和未找到的行,请尝试以下操作:

SELECT found_list.lastinitial, found_count, not_found_count
FROM (
    SELECT SUBSTRING(lastname,1,1) AS lastinitial, COUNT(lastname) AS found_count
    FROM members
    WHERE found = 1
    GROUP BY lastinitial
) AS found_list,
(
    SELECT SUBSTRING(lastname,1,1) AS lastinitial, COUNT(lastname) AS not_found_count
    FROM members
    WHERE found IS NULL OR found = 0
    GROUP BY lastinitial
) AS not_found_list
WHERE found_list.lastinitial = not_found_list.lastinitial

正如您所看到的,第一个查询更短,更优雅,而且执行速度更快。