0

この2つの質問がありますが、

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

なにか提案を?

4

1 に答える 1

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
于 2013-08-08T17:26:26.790 に答える