如何按2条件查询组?

时间:2013-09-27 21:28:25

标签: mysql sql

我在这里有桌子。

enter image description here

我怎么能

SELECT 
    sum(gload1) as 'g1',
    sum(gload2) as 'g2'.
    sum(gload3) as 'g3',
    sum(gload4) as 'g4' 
FROM member 
WHERE age = 15-20,21-25,26-30 
GROUP BY gender;

结果如下:只是样本

enter image description here

我怎样才能这样查询。感谢advamce。

3 个答案:

答案 0 :(得分:2)

SELECT 
  CASE 
    WHEN `age`>=15 AND `age`<=20 THEN '15-20'
    WHEN `age`>=21 AND `age`<=25 THEN '21-25'
    WHEN `age`>=26 AND `age`<=30 THEN '26-30'
  END AS `AgeRange`,
  SUM(`gload1`) AS `g1`, 
  SUM(`gload2`) AS `g2`, 
  SUM(`gload3`) AS `g3`, 
  SUM(`gload4`) AS `g4`
FROM 
  member 
GROUP BY `AgeRange`

参见 SQL Fiddle

答案 1 :(得分:1)

您需要创建表示行的假表。试试这个:

SELECT AgeBrackets.Age as Age, sum(gload1) as gload1, sum(gload2) as gload2, sum(gload4) AS gload
FROM 
(SELECT '15-20' AS Age, 15 as stdt, 20 as eddt
UNION
SELECT '21-25', 21, 25
UNION
SELECT '26-30', 26, 30) AS AgeBrackets
JOIN member
ON member.age BETWEEN AgeBrackets.stdt AND AgeBrackets.eddt
GROUP BY Age
ORDER BY Age;

答案 2 :(得分:1)

试试这样:

SELECT
    CASE 
        WHEN age BETWEEN 15 AND 20 THEN '15-20'
        WHEN age BETWEEN 20 AND 30 THEN '20-30'
        ELSE '30-...'
    END as age_group,
    gender,
    sum(gload1) as gload1_total
FROM 
    member
GROUP BY 
    CASE 
        WHEN age BETWEEN 15 AND 20 THEN '15-20'
        WHEN age BETWEEN 20 AND 30 THEN '20-30'
        ELSE '30-...'
    END,
    gender

如果它不起作用,您可能必须执行子查询:内部查询将范围字符串添加到每一行,外部查询将按其分组。