返回查询结果像两个cols

时间:2013-08-08 17:23:29

标签: sql

我有这两个问题,

SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS male
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'M'
GROUP BY date, country_name
ORDER BY country_name

SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS female
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'F'
GROUP BY date, country_name
ORDER BY country_name

返回给我这样的东西:

date, country, male
2009-01-01, Spain, 34

date, country, female
2009-01-01, Spain, 12

但是我需要一个回复我的查询:

date, country, male, female
2009-01-01, Spain, 34, 12

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您可以将聚合函数与CASE表达式一起使用,以在单独的列中获取结果:

SELECT 
    date(d1.date) AS date, 
    d3.country_name AS country_name, 
    sum(case when d3.gender = 'M' then 1 else 0 end) AS male,
    sum(case when d3.gender = 'F' then 1 else 0 end) AS female
FROM f1
INNER JOIN d1 
    ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 
    ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 
    ON f1.id_user = d3.id_user 
GROUP BY date, country_name
ORDER BY country_name