mysql 按组列出的SQL标志

t3psigkw  于 2023-10-15  发布在  Mysql
关注(0)|答案(3)|浏览(95)
CREATE TABLE t
    (STUDENT int, SCORE int, DATE date)
;
    
INSERT INTO t
    (STUDENT, SCORE, DATE)
VALUES
    (1, 6, '2022-02-01 00:00:00'),
    (1, 2, '2022-03-12 00:00:00'),
    (1, 5, '2022-04-30 00:00:00'),
    (2, 2, '2022-04-12 00:00:00'),
    (2, 0, '2022-04-17 00:00:00'),
    (2, 7, '2022-05-08 00:00:00'),
    (3, 2, '2022-03-16 00:00:00'),
    (3, 6, '2022-03-18 00:00:00'),
    (3, 2, '2022-04-02 00:00:00'),
    (3, 9, '2022-04-27 00:00:00'),
    (4, 4, '2022-02-24 00:00:00'),
    (4, 0, '2022-02-26 00:00:00'),
    (5, 3, '2022-01-28 00:00:00'),
    (5, 0, '2022-02-21 00:00:00'),
    (5, 4, '2022-04-05 00:00:00')
;

我想创建一个这样的文件:

规则是:
1.当SCORE = 2时,求min(DATE),并与SCORE = 6 A时的min(DATE)进行比较。如果min(日期,评分= 2)< min(日期,评分= 6),则标志等于1 B。如果min(DATE,SCORE = 2)>= min(DATE,SCORE = 6),则FLAG等于0 A。如果有SCORE = 2的记录,但没有SCORE = 6的记录,则FLAG等于1

vybvopom

vybvopom1#

你可以在这里使用-MySQL CASE statement
下面是获取所需结果的查询。

WITH Score2And6 AS (
SELECT t.STUDENT,
       MIN(CASE WHEN t.SCORE = 2 THEN t.DATE ELSE NULL END) AS min_date_score_2,
       MIN(CASE WHEN t.SCORE = 6 THEN t.DATE ELSE NULL END) AS min_date_score_6
FROM t
WHERE t.SCORE IN (2, 6)
GROUP BY t.STUDENT)

SELECT score.STUDENT,
   CASE WHEN score.min_date_score_2 < score.min_date_score_6 OR score.min_date_score_6 IS NULL THEN 1
        ELSE 0
   END AS FLAG 
FROM Score2And6 score 
ORDER BY STUDENT ASC;

在这里,我使用了CTE(公共表表达式)来使查询更具可读性。
演示:https://onecompiler.com/mysql/3zpma8neh

qvtsj1bj

qvtsj1bj2#

在这里,您使用与LEFT JOIN相同的方法

SELECT t1.STUDENT,
CASE WHEN t2.min_date < t6.min_date OR t6.min_date IS NULL THEN 1
ELSE 0 END
FROM (SELECT STUDENT, min(DATE) as min_date
from t
where SCORE = 2
group by STUDENT) t2 LEFT JOIN 
(SELECT STUDENT, min(DATE) as min_date
from t
where SCORE = 6
group by STUDENT) t6 ON t2.STUDENT = t6.STUDENT
b1zrtrql

b1zrtrql3#

写查询时要有条理。一步一步来从您之前的请求中,您已经获得了创建查询所需的所有信息。

  • 你通过MIN(CASE WHEN score = n THEN date END)得到分数n的MIN(日期)
  • 您可以使用HAVING COUNT(CASE WHEN score = m THEN 1 END) > 0将结果限制为得分为m的学生

因此,对于所有得分为2的学生,获得得分2和6的日期是:

SELECT 
  student,
  MIN(CASE WHEN score = 2 THEN date END) AS min_date_2,
  MIN(CASE WHEN score = 6 THEN date END) AS min_date_6
FROM t
GROUP BY student
HAVING COUNT(CASE WHEN score = 2 THEN 1 END) > 0;

现在,您需要根据最小日期获取标志。你知道你可以使用CASE表达式来实现这个。有两个标志值:如果2分日期大于或等于6分日期,则为0,否则为1。
您可以在上面的查询中立即应用此方法

SELECT 
  student,
  CASE WHEN MIN(CASE WHEN score = 2 THEN date END) >=
            MIN(CASE WHEN score = 6 THEN date END)
    THEN 0
    ELSE 1
  END AS flag
...

或者使用CTE(WITH子句):

WITH cte AS ( <above query> )
SELECT
  student,
  CASE WHEN min_date_2 >= min_date_6 THEN 0 ELSE 1 END AS flag
FROM cte
ORDER BY student;

相关问题