查询过滤

时间:2011-11-04 16:31:50

标签: mysql sql database

我认为这不可能,但我想确定。

让我们说我想让用户的平均年龄假设一些条件。

SELECT avg(age) as avg_a FROM users where something something;

现在说客户希望得到平均年龄,男性的平均年龄和女性的平均年龄。

类似

SELECT avg(age) as avg_a, avg(age where female) avg_f, avg(age where male) avg_m FROM users where something something;

这样的事情是否可能甚至是明智的?

我该怎么做呢?或者我应该每次只运行3个查询?

3 个答案:

答案 0 :(得分:2)

是的,您可以在聚合函数中使用case语句。参见:

SELECT
    avg(age) avg_age,
    avg(case when gender = 'M' then age end) male_avg_age,
    avg(case when gender = 'F' then age end) female_avg_age
FROM users;

答案 1 :(得分:0)

SELECT 
  avg(age) as avg_a, 
  avg(select age from users where female) avg_f, 
  avg(select age from users where male) avg_m 
FROM users 
WHERE something something;

答案 2 :(得分:0)

为了获得每个性别的平均值和所有平均值,您必须在GROUP BY中使用WITH ROLLUP子句。

例如,以下是一些示例数据:

use junk
DROP TABLE IF EXISTS people;
CREATE TABLE people
(name VARCHAR(20),age INT,gender CHAR(1));
INSERT INTO people VALUES
('rolando'  ,46,'M'),
('pamela'   ,40,'F'),
('carlik'   ,23,'M'),
('javonne'  ,22,'M'),
('dominique',15,'F'),
('diamond'  ,13,'F');
SELECT * FROM people;

这是您需要的查询:

SELECT IFNULL(gender,'ALL') gender,AVG(age) average_age
FROM people GROUP BY gender WITH ROLLUP;

这是输出:

mysql> CREATE TABLE people
    -> (name VARCHAR(20),age INT,gender CHAR(1));
Query OK, 0 rows affected (0.08 sec)

mysql> INSERT INTO people VALUES
    -> ('rolando'  ,46,'M'),('pamela'   ,40,'F'),
    -> ('carlik'   ,23,'M'),('javonne'  ,22,'M'),
    -> ('dominique',15,'F'),('diamond'  ,13,'F');
Query OK, 6 rows affected (0.06 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM people;
+-----------+------+--------+
| name      | age  | gender |
+-----------+------+--------+
| rolando   |   46 | M      |
| pamela    |   40 | F      |
| carlik    |   23 | M      |
| javonne   |   22 | M      |
| dominique |   15 | F      |
| diamond   |   13 | F      |
+-----------+------+--------+
6 rows in set (0.00 sec)

mysql> SELECT IFNULL(gender,'ALL') gender,AVG(age) average_age
    -> FROM people GROUP BY gender WITH ROLLUP;
+--------+-------------+
| gender | average_age |
+--------+-------------+
| F      |     22.6667 |
| M      |     30.3333 |
| ALL    |     26.5000 |
+--------+-------------+
3 rows in set, 1 warning (0.00 sec)

另一种查询风格是:

SELECT A.avgage avg_a,F.avgage avg_f,M.avgage avg_m FROM
(SELECT AVG(age) avgage FROM people) A,
(SELECT AVG(age) avgage FROM people WHERE gender='F') F,
(SELECT AVG(age) avgage FROM people WHERE gender='M') M;

这是输出:

mysql> SELECT A.avgage avg_a,F.avgage avg_f,M.avgage avg_m FROM
    -> (SELECT AVG(age) avgage FROM people) A,
    -> (SELECT AVG(age) avgage FROM people WHERE gender='F') F,
    -> (SELECT AVG(age) avgage FROM people WHERE gender='M') M;
+---------+---------+---------+
| avg_a   | avg_f   | avg_m   |
+---------+---------+---------+
| 26.5000 | 22.6667 | 30.3333 |
+---------+---------+---------+
1 row in set (0.00 sec)

试一试!!!