我看到了一些与此问题类似的帖子。我已经尝试过使每个人适应自己的需求,但是我提出了一些建议。希望有人可以在此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 : 如何将整个语句转换为插入语句,以定期从视图捕获数据。这将进入一个名为apt_total的表。我尝试了一些变体,但是没有什么能接近工作的。
非常感谢您的协助。
答案 0 :(得分:0)
您要使用SUM(IF()),如果条件匹配,则将SUM为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 INTO apt_total更改为以下内容:
INSERT INTO apt_total (col1, col2, col3.....)