积极答复者
多表联合查询时使用groupby的问题

问题
-
有表A表B,数据如下:
表A
ID LogonTime LogoffTime
001 2008-10-10 10:2:9 2008-10-10 12:2:9
002 2008-10-10 12:2:59 2008-10-10 14:3:00
001 2008-10-10 14:3:50 2008-10-10 16:4:00
002 2008-10-10 16:4:45 2008-10-10 18:5:00
。 。 。
。 。 。
。 。 。
表B
ID beginTime count
001 2008-10-10 10:30:00 90
001 2008-10-10 11:00:00 200
002 2008-10-10 12:30:00 150
002 2008-10-10 13:00:00 120
。 。 。
。 。 。
。 。 。
预得到如下结果
表C
ID LogonTime LogoffTime count
001 2008-10-10 10:2:9 2008-10-10 12:2:9 290
002 2008-10-10 12:2:59 2008-10-10 14:3:00 270
001 2008-10-10 14:3:50 2008-10-10 16:4:00 0
002 2008-10-10 16:4:45 2008-10-10 18:5:00 0
。 。 。
。 。 。
。 。 。
我写的Sql语句如下:
Select A.ID, A.LogonTime, A.LogoffTime, Sum(B.count)
from A left join B
on A.ID=B.ID and B.beginTime>A.LogonTime and B.beginTime<A.LogoffTime
Group by (B.ID, A.LogonTime, A.LogoffTime)
为什么不行呢,有语法错误,该怎样得到我想要的结果呢,谢谢!
guiwenyang
答案
-
这是因为在SELECT子句的字段列表中,除了聚集函数以外,其他所出现的字段一定要在GROUP BY子句中有定义才行。如GROUP BY A, B, 那么 SELECT SUM(A), C 就有问题,因为C不在GROUP BY 中,但是SUM(A)是可以的。针对你的例子,可以用如下查询语句:
Select A.ID, A.LogonTime, A.LogoffTime , ISNULL(SUM(B.count), 0) AS count from A left join B on A.ID=B.ID and B.beginTime>A.LogonTime and B.beginTime<A.LogoffTime Group by A.ID, A.LogonTime, A.LogoffTime
下面是查询结果:
1 2008-10-10 10:02:09.000 2008-10-10 12:02:09.000 290 1 2008-10-10 14:03:50.000 2008-10-10 16:04:00.000 0 2 2008-10-10 12:02:59.000 2008-10-10 14:03:00.000 270 2 2008-10-10 16:04:45.000 2008-10-10 18:05:00.000 0 - 已建议为答案 Ya Yu 2009年2月20日 6:41
- 已标记为答案 KeFang Chen 2009年2月20日 6:49
全部回复
-
这是因为在SELECT子句的字段列表中,除了聚集函数以外,其他所出现的字段一定要在GROUP BY子句中有定义才行。如GROUP BY A, B, 那么 SELECT SUM(A), C 就有问题,因为C不在GROUP BY 中,但是SUM(A)是可以的。针对你的例子,可以用如下查询语句:
Select A.ID, A.LogonTime, A.LogoffTime , ISNULL(SUM(B.count), 0) AS count from A left join B on A.ID=B.ID and B.beginTime>A.LogonTime and B.beginTime<A.LogoffTime Group by A.ID, A.LogonTime, A.LogoffTime
下面是查询结果:
1 2008-10-10 10:02:09.000 2008-10-10 12:02:09.000 290 1 2008-10-10 14:03:50.000 2008-10-10 16:04:00.000 0 2 2008-10-10 12:02:59.000 2008-10-10 14:03:00.000 270 2 2008-10-10 16:04:45.000 2008-10-10 18:05:00.000 0 - 已建议为答案 Ya Yu 2009年2月20日 6:41
- 已标记为答案 KeFang Chen 2009年2月20日 6:49