MySQL查询日期计数

时间:2014-11-08 21:04:54

标签: mysql

我正在尝试找出以下语句的查询:

获取每个地点的指定日期的宠物总数。包括那天剩下的那些。每个预订的日期是开始和结束日期。

我还没有关于数据的数据库,但是这里大致了解了这个表的样子:

| pet | arriveDate | leaveDate  | location |
+-----+------------+------------+----------+
| 1   | 2014-11-01 | 2014-11-19 | Cat Pen  |
+-----+------------+------------+----------+
| 2   | 2014-11-02 | 2014-11-17 | Dog Pen  |
+-----+------------+------------+----------+
| 3   | 2014-11-05 | 2014-11-10 | Cat Pen  |
+-----+------------+------------+----------+
| 4   | 2014-11-06 | 2014-11-19 | Cat Pen  |
+-----+------------+------------+----------+
| 5   | 2014-11-08 | 2014-11-26 | Dog Pen  |
+-----+------------+------------+----------+
| 6   | 2014-11-14 | 2014-11-16 | Cat Pen  |
+-----+------------+------------+----------+

对于'2014-11-08',输出将为:

|    date    | cat pens | dog pens |
+------------+----------+----------+
| 2014-08-11 |     3    |    2     |

1 个答案:

答案 0 :(得分:1)

好吧,您可以在执行任何操作之前编写只会选择所需行的查询。你想得到之前或某个日期已经到过的宠物,还没有离开。您可以在where子句中对其进行过滤,如下所示:

SELECT *
FROM myTable
WHERE arriveDate <= '2014-11-08' AND leaveDate >= '2014-11-08';

然后,您可以将SUM()聚合函数与case语句一起使用以获取每个位置的数字。它看起来像这样:

SELECT '2014-11-08' AS date, 
  SUM(CASE WHEN location = 'Cat Pen' THEN 1 ELSE 0 END) AS CatPens,
  SUM(CASE WHEN location = 'Dog Pen' THEN 1 ELSE 0 END) AS DogPens
FROM myTable
WHERE arriveDate <= '2014-11-08' AND leaveDate >= '2014-11-08';

以下是SQL Fiddle示例。