V
V
vlad_lutsky2017-09-15 01:22:52
MySQL
vlad_lutsky, 2017-09-15 01:22:52

How to build a MySql query?

The task is to build a table of the number of cases by date of birth (columns - years);
The bottom line - we take data from the `apointments` table (visits) and the `pations` table (visitors) and see if the visitor was at the reception, if so, then we group all his visits ... MAGIC ... at the output we get the number of sick people ( who has ever visited a first-aid post) by year of birth:
1992 - 2
1995 - 4
1996 - 2
, etc.
Database:

mysql_query(" CREATE TABLE IF NOT EXISTS `pations` (
    `id` MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `fio` VARCHAR(255) NOT NULL UNIQUE,
    `male` VARCHAR(255) NOT NULL,
    `age` DATE NOT NULL
  ) ENGINE=INNODB", $db);

  mysql_query(" CREATE TABLE IF NOT EXISTS `apointments` (
    `id` MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `date` DATE NOT NULL UNIQUE,
    `idp` VARCHAR(255) NOT NULL,
    `idd` VARCHAR(255) NOT NULL,
    `enter` VARCHAR(255) NOT NULL
  ) ENGINE=INNODB", $db);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2017-09-15
@vlad_lutsky

Take apointments, join pations, group by visitor id, extract year from date of birth. You group the received data by year, do count. Something like this:

SELECT `year`, COUNT(*)
FROM (
  SELECT YEAR(p.age) AS `year`, p.id
  FROM apointments a
  JOIN pations p ON p.id = a.idp
  GROUP BY p.id
) t
GROUP BY `year`

R
Rsa97, 2017-09-15
@Rsa97

SELECT YEAR(`p`.`age`) as `year`, COUNT(DISTINCT `p`.`id`) as `count`
  FROM `apointments` AS `a`
  JOIN `pations` AS `p` ON `p`.`id` = `a`.`idp`
  GROUP BY YEAR(`p`.`age`)

Only the query is not fast, grouping by function does not use indexes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question