我正在try 创建一个包含代码N09的表,其中一个学生被分配了一组包含N09的代码,并且"Status Complete"是YES.我想使用GROUP_CONCAT查看每个集合是否包含N09.我看到了与此类似的问题,但不幸的是,它没有达到我对表2的目标,因为它导致了一个问题.我遇到的这个问题是,计数时一直显示1而不是2、3.它还一直显示N09,而不是显示N09及其GROUP_CONCAT函数集合中的其他代码.在SQLite中,是否有代码可以实现表2的目标?如果我的问题不清楚,请随意 comments ,因为我是新来的.

表2的目标:

Student ID Status Complete Status Date Status Time Code Count Group_Concat(Code)
1 yes 03/03/2021 00:00:00 N09 1 N09
2 yes 03/04/2021 10:03:10 N09 2 N09, M33
3 yes 03/04/2021 01:00:10 N09 3 N09, Y03, B55

问题:

Student ID Status Complete Status Date Status Time Code Count Group_Concat(Code)
1 yes 03/03/2021 00:00:00 N09 1 N09
2 yes 03/04/2021 10:03:10 N09 1 N09
3 yes 03/04/2021 01:00:10 N09 1 N09

样本数据:

Student ID Status Complete Status Date Status Time Code
1 yes 03/03/2021 00:00:00 N09
2 yes 03/04/2021 10:03:10 N09
2 yes 03/04/2021 10:03:10 M33
3 yes 03/04/2021 01:00:10 N09
3 yes 03/04/2021 01:00:10 Y03
3 yes 03/04/2021 01:00:10 B55

代码:

CREATE TABLE table2 AS
select   Student_ID
        ,Status_Complete  
        ,Status_Date
        ,Status_TIME
        ,Code
        ,count(Code) /*over (partition by Student_ID,Code)*/ as 'Count'
        ,GROUP_CONCAT(Code)
from table1
where Code in ('N09') AND Status_Complete = 'yes'
group by Student_ID, Status_Date, Status_TIME, 'Count'
HAVING 'Count'> 0 
ORDER BY Student_ID;

推荐答案

You should group by Student_ID only since you want only 1 row for each student.
The columns Status_Date and Status_TIME of the results that you want seem to be the min values of each student (I assume that the dates have the proper format of YYYY-mm-dd which is the only valid date format for SQLite).
Also, the condition Code = 'N09' should be checked in the HAVING clause:

CREATE TABLE table2 AS
SELECT Student_ID, Status_Complete, 
       MIN(Status_Date) Status_Date, 
       TIME(MIN(Status_Date || ' ' || Status_TIME)) Status_TIME, 
       COUNT(*) count,
       GROUP_CONCAT(Code) Codes
FROM table1
WHERE Status_Complete = 'yes'
GROUP BY Student_ID
HAVING SUM(Code = 'N09') > 0
ORDER BY Student_ID;

See the demo.

Never use single quotes for column names.
'Count' is a string literal when used in code. It never refers to a column alias.

Sql相关问答推荐

Postgres从组中 Select 具有相反排序顺序的行

PG SQL中按条件聚合值

在postgres中动态计算出现次数并插入到json中

如何在幂函数中正确使用Power()和Exp()

提高写密集型表的查询性能

Lag()函数的差异:R与SQL(将R代码转换为SQL)

部分匹配表中元素的MariaDB查询查找结果

SQL:计算与另一列中给定值互斥的匹配项

如何嵌套两条SQL语句

基于多列比较连接两个表

正在try 从SQL获取最新的ID和一个唯一名称

属于(日期)范围类型及其交集的总权重​

多条件SQL排序行为

带日期函数的复合索引不允许只扫描索引吗?

用VB.NET在Dapper中实现MS Access数据库顺序透视

使用多个WITH子查询的替代方法

给定 3 个键列,从一个表中 Select 另一表中不存在的所有数据

按公司和产品查询最近发票的平均价格的SQL查询

如何获得上个月和下个月之间的销售额差异

连续日期的SQL