[英]SQL count stays per day query not working as expected
Let's assume I manage medical patient stays information system. 让我们假设我管理医疗病人住宿信息系统。
I want to get the patient count per day with the following minimal structure : 我想通过以下最小结构获得每天的患者数量:
stay
table has begin
and end
datetime columns stay
表有begin
和end
日期时间列 $first_day
and $last_day
limits $first_day
和$last_day
限制 The following snippet is NOT what I want, since it only counts entries per day, and not present stays per day: 以下代码段不是我想要的,因为它只计算每天的条目数,而不是每天的住宿数:
SELECT
DATE_FORMAT(`stay`.`begin`, '%Y-%m-%d') AS `date`,
COUNT(`stay`.`stay_id`) AS `total`
FROM `stay`
WHERE `stay`.`begin` <= '$first_day'
AND `stay`.`end` >= '$last_day'
GROUP BY `date`
ORDER BY `date`
Last but not least, I'm looking for a full SQL query. 最后但同样重要的是,我正在寻找一个完整的SQL查询。
It goes without saying that making one SQL query for each day would be totally trivial. 不言而喻,每天制作一个SQL查询将是完全无关紧要的。
Use of temporary (dates ?) table is clearly an option. 使用临时(日期?)表显然是一种选择。
A quick Google around leads me to this page: What is the most straightforward way to pad empty dates in sql results (on either mysql or perl end)? 一个快速的谷歌引导我到这个页面: 什么是在SQL结果(在mysql或perl端)填充空日期最直接的方法?
What I would suggest is that you either follow the advice in that question, or construct your own loop in PHP. 我建议您遵循该问题中的建议,或者在PHP中构建自己的循环。
As you mentioned using a temporary table of all dates in the range you want is one way to handle this. 正如您所提到的,使用所需范围内所有日期的临时表是处理此问题的一种方法。 If you created a table of date called
foo
with all dates between $first_day
and $last_day
inclusive (see here ). 如果你创建了一个名为
foo
的日期表,所有日期都在$first_day
和$last_day
之间(见这里 )。
Then you can write your query like: 然后你可以编写你的查询,如:
SELECT f.date, count(s.stay_id)
FROM foo f
JOIN stay s ON s.begin <= f.date AND s.end >= date
GROUP BY f.date
ORDER BY f.date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.