mysql对过去30天错过约会的声明

v7pvogib  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(266)

我看到过一些类似这个问题的帖子。我试着使每一个都适合我的需要,但都有不足之处。希望有人能对mysql语句提供一些帮助:
父表:客户端

`id` int(11) NOT NULL AUTO_INCREMENT,

子表:约会

CREATE TABLE `appointment` (
  `aptID` int(11) NOT NULL AUTO_INCREMENT,
  `start_time` time DEFAULT NULL,
  `date` date DEFAULT NULL,
  `id` int(11) DEFAULT NULL,
  `reason` enum('Assessment','Follow-up') DEFAULT NULL,
  `outcome` enum('Show','No Show') DEFAULT NULL,
  `last30` int(5) DEFAULT NULL,
  PRIMARY KEY (`aptID`),
  KEY `fk_appointment_client1_idx` (`id`),
  CONSTRAINT `fk_appointment_client1` FOREIGN KEY (`id`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

我需要一份下列报告:
1) 过去30天的预约次数2)365天的预约次数3)有过的预约次数4)过去30天的错过预约次数
我创建了一个视图,除了最后一个(错过的约会)之外,它提供了所有信息,但我不知道如何合并错过的约会:

CREATE VIEW `total`
AS SELECT
   id AS id,
   name AS name,
    count(`C1`) AS `Last30days`,
    count(.`C2`) AS `Last365Days`,
    count(`C3`)  AS `Alltime`

FROM (select
client.id AS id,
client.name AS name,
(CASE WHEN DATEDIFF(CURDATE(), date) <= 30 THEN NULL end) AS `C1`,
(CASE WHEN DATEDIFF(CURDATE(), date) <= 365 THEN NULL end) AS `C2`,
(select count(*) from appointment where id=client.id) as `C3`

from 
(client left join appointment on((client.id = appointment.id))))
group by `total`.`id`;

问题1:如何将过去30天内错过的约会合并到此视图中?错过的预约将被视为过去30天内的预约,其结果变量为“不显示”。我想应该加上这两行:

count(`C4`) AS `Missed30`

(CASE WHEN DATEDIFF(CURDATE(), date) <= 365 where outcome = 'No Show' THEN NULL end)  AS `C4`

问题2:如何将整个语句转换为insert语句,以便定期从视图中捕获数据。这将进入一个名为apt\u total的表中。我试过几种不同的方法,但都没有成功。
谢谢,任何帮助都将不胜感激。

9vw9lbht

9vw9lbht1#

如果条件匹配,则要使用sum(if())和sum a 1。见下文。

SELECT
  id,
  name,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 30, 1, 0)) AS Last30Days,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 365, 1, 0)) AS Last365Days,
  COUNT(*) AS AllTime,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 30 AND outcome = 'No Show', 1, 0)) AS NoShow
 FROM
  appointments AS a
  INNER JOIN clients AS c ON a.id = c.id
 GROUP BY
  id

这会给你你要找的号码。如果要将select转换为insert,可以执行以下操作。

INSERT INTO apt_total
SELECT
  id,
  name,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 30, 1, 0)) AS Last30Days,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 365, 1, 0)) AS Last365Days,
  COUNT(*) AS AllTime,
  SUM(IF(DATEDIFF(CURDATE(), date) <= 30 AND outcome = 'No Show', 1, 0)) AS NoShow
 FROM
  appointments AS a
  INNER JOIN clients AS c ON a.id = c.id
 GROUP BY
  id

您需要确保列是相同的,否则将insert改为apt\u total,如下所示:

INSERT INTO apt_total (col1, col2, col3.....)

相关问题