编写此脚本的更好方法是不返回聚合错误

时间:2016-09-29 12:43:07

标签: sql sql-server sql-server-2008 tsql

由于存在t3.Date,此脚本给出了一个聚合错误。 还有其他的写作方式吗?

id | student_id | lecturer_schedule_id | status | created_at
2  | 1          | 2                    | 1      | 2016-09-02
3  | 1          | 3                    | 1      | 2016-09-02
4  | 1          | 4                    | 0      | 2016-09-03

3 个答案:

答案 0 :(得分:1)

尝试使用以下脚本。

SELECT t1.ID, t1.Date, t2.Type, t1.Username
FROM t1
INNER JOIN t2
ON t1.CareID = t2.CareID AND 
t1.Date = t2.Date AND
t1.Username = t2.Username
LEFT JOIN t3
ON t1.CareID = t3.CareID AND t1.Username = t3.Username AND t1.Date <= t3.Date
GROUP BY t1.ID, t1.Date, t2.Type, t1.Username
HAVING COUNT(t1.ID) = 1  

答案 1 :(得分:1)

卸下:

 AND t1.Date <= t3.Date
来自HAVING子句的

并将其放在ON的{​​{1}}子句中:

LEFT JOIN

答案 2 :(得分:1)

你的拥有声明错过了别名,所以写一下Count(t1.Id),并删除AND t1.Date <= t3.Date使用并放入连接声明

SELECT 
    t1.ID, 
    t1.Date, 
    t2.Type, 
    t1.Username
FROM t1
INNER JOIN t2 ON t1.CareID = t2.CareID 
    AND t1.Date = t2.Date 
    AND t1.Username = t2.Username
LEFT JOIN t3 ON t1.CareID = t3.CareID 
    AND t1.Username = t3.Username
    AND t1.Date <= t3.Date
GROUP BY t1.ID, t1.Date, t2.Type, t1.Username
HAVING COUNT(t1.ID) = 1