简体   繁体   English

如何查找 SQL 中日期之间的总行数?

[英]How to find the total number of rows between dates in SQL?

I have to find the drinker and the total number of drinks ordered by each drinker in the first three months of 2020.我必须找到饮酒者以及每个饮酒者在 2020 年前三个月订购的饮料总数。

Here is my SELECT statement so far: (It doesn't present any errors, but doesn't return anything either)到目前为止,这是我的 SELECT 声明:(它没有出现任何错误,但也没有返回任何内容)

SELECT DRINKER, COUNT(DRINK)
FROM ORDERS 
WHERE ODATE >= STR_TO_DATE('01-JAN-2020','%D-%M-%Y') 
AND ODATE <= STR_TO_DATE('31-MAR-2020','%D-%M-%Y')
GROUP BY DRINKER;

Here is the CREATE TABLE statement:这是 CREATE TABLE 语句:

CREATE TABLE ORDERS(    /* Drinkers visit pubs and consumes drinks */
DRINKER     VARCHAR(30) NOT NULL,   /* Drinker name */
PUB         VARCHAR(30) NOT NULL,   /* Pub name */
ODATE       DATE        NOT NULL,   /* Order date   */
DRINK       VARCHAR(30) NOT NULL,   /* Drink name   */
DRINK_NO    DECIMAL(2)  NOT NULL,   /* A sequence number of a drink */
    CONSTRAINT ORDERS_PKEY PRIMARY KEY(DRINKER, PUB, ODATE, DRINK, DRINK_NO),
    CONSTRAINT ORDERS_FKEY1 FOREIGN KEY(PUB, DRINK) REFERENCES SERVES(PUB, DRINK),
    CONSTRAINT ORDERS_FKEY2 FOREIGN KEY(DRINKER) REFERENCES DRINKERS(DRINKER)   );

Here is an example of the data that has been inserted into the table ORDERS:以下是已插入表 ORDERS 的数据示例:

INSERT INTO ORDERS VALUES('JOHN', 'LAZY LOBSTER', STR_TO_DATE('04-FEB-2020', '%d-%M-%Y'), 'RED WINE', 3);

It should also be worth noting that I am working in MYSQL.还应该值得注意的是,我在 MYSQL 工作。 Any help would be greatly appreciated!任何帮助将不胜感激!

You need a lower-case d for the day of the month.您需要一个小写的d来表示月份中的某天。 So this works:所以这有效:

SELECT DRINKER, COUNT(DRINK)
FROM ORDERS 
WHERE ODATE >= STR_TO_DATE('01-JAN-2020','%d-%M-%Y') AND
      ODATE <= STR_TO_DATE('31-MAR-2020','%d-%M-%Y')
GROUP BY DRINKER;

However, this is more sensibly written as:然而,这更明智地写成:

SELECT DRINKER, COUNT(DRINK)
FROM ORDERS 
WHERE ODATE >= '2020-01-01'AND
      ODATE <= '2020-03-31'
GROUP BY DRINKER;

Here is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM