MYSQL用于计数的多个条件语句

时间:2017-04-11 05:21:03

标签: mysql

我是MYSQL的新手,在这个网站上看了很多答案,但无法让以下工作......

表是“成员” 3个字段是“id”(整数);和2个日期字段“dob”和“expiry” 我需要计算所有当前成员的记录数,即 expiry<curdate() 然后我需要知道具有以下条件的记录数: year(curdate())-year(dob) <25 as young year(curdate())-year(dob) >25 and <=50 as Medium year(curdate())-year(dob) >50 as Older

所以我希望得到一个包含许多列的行和每个条件的计数。

实际上,我正在过滤当前成员的年龄组。

我尝试了一个子查询,却未能将其发挥作用。

由于

1 个答案:

答案 0 :(得分:0)

如果你真的想要你提到的最终结果,你可以使用视图。实现结果需要很长的路要走。但是,这是方法。我创建了下表member并插入了如下数据。

CREATE TABLE member (
    id int(11) AUTO_INCREMENT PRIMARY KEY,
    dob date DEFAULT NULL,
    expiry date DEFAULT NULL
);

INSERT INTO member (id, dob, expiry) VALUES
    (1, '1980-01-01', '2020-05-05'),
    (2, '1982-05-05', '2020-01-01'),
    (3, '1983-05-05', '2020-01-01'),
    (4, '1981-05-05', '2020-01-01'),
    (5, '1994-05-05', '2020-01-01'),
    (6, '1992-05-05', '2020-01-01'),
    (7, '1960-05-05', '2020-01-01'),
    (8, '1958-05-05', '2020-01-01'),
    (9, '1958-07-07', '2020-05-05');

以下是包含数据的member表。

id |    dob      |    expiry
--------------------------------
1  | 1980-01-01  |  2020-05-05
2  | 1982-05-05  |  2020-01-01
3  | 1983-05-05  |  2020-01-01
4  | 1981-05-05  |  2020-01-01
5  | 1994-05-05  |  2020-01-01
6  | 1992-05-05  |  2020-01-01
7  | 1960-05-05  |  2020-01-01
8  | 1958-05-05  |  2020-01-01
9  | 1958-07-07  |  2020-05-05

然后,我为名为current_members的所有当前员工创建了一个单独的视图,如下所示。

CREATE VIEW current_members AS (SELECT * FROM member WHERE TIMESTAMPDIFF(YEAR, CAST(CURRENT_TIMESTAMP AS DATE), member.expiry) >= 0);

然后从该视图中查询,我创建了3个单独的视图,其中包含youngmiddleold的每个年龄段的计数,如下所示。

CREATE VIEW young AS (SELECT COUNT(*) as Young FROM (SELECT TIMESTAMPDIFF(YEAR, current_members.dob, CAST(CURRENT_TIMESTAMP AS DATE)) AS age FROM current_members HAVING age <= 25) yng);
CREATE VIEW middle AS (SELECT COUNT(*) as Middle FROM (SELECT TIMESTAMPDIFF(YEAR, current_members.dob, CAST(CURRENT_TIMESTAMP AS DATE)) AS age FROM current_members HAVING age BETWEEN 25 AND 50) mid);
CREATE VIEW old AS (SELECT COUNT(*) as Old FROM (SELECT TIMESTAMPDIFF(YEAR, current_members.dob, CAST(CURRENT_TIMESTAMP AS DATE)) AS age FROM current_members HAVING age >= 50) old);

最后,三个视图交叉连接,以便将每个年龄段的计数分成一个最终表的一行,如下所示。

SELECT * FROM young, middle, old;

这将为您提供以下结果。

Young | Middle | Old
----------------------
   2  |    4   |  3

建议:对于上述时间差异计算,您可以编写自己的存储程序以简化代码