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

我必须找到饮水器以及每个饮水器在2020年前三个月订购的饮料总数。

到目前为止,这是我的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;

这是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)   );

这是已插入表ORDERS中的数据的示例:

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

值得注意的是,我正在使用MYSQL。任何帮助将不胜感激!

评论
  • eos_et
    eos_et 回复

    You need a lower-case d for the day of the month. 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;
    

    但是,将其更合理地写为:

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

    Here is a db<>fiddle.