我写了一个sql查询,它连接了很多表,我只想分组一列表。这是我的slq查询。
select us.Username, ro.Role, ca.CartName, ca.Date from Users us
left join Roles ro on ro.RoleID = us.RoleID
left join Carts ca on ca.UserId = us.ID
group by ca.Date;
以下是表格的破坏:
//表用户
ID Username RoleID
1 Tri 1
2 Lan 1
3 Nhu 1
4 Lac 1
5 Linhchi 2
//表格角色
RoleID Role Description
1 Admin Someone in administrator board
2 User Someone who has an account
3 Guess Someone who just view the website
//表格推车
CartId CartName CartDescription UserId Date
1 Computer Computer CMS 1 2/11/2013 12:00:00 AM
2 Desk Writing Desk 2 2/11/2013 12:00:00 AM
3 Print Paper Company's print paper 3 3/11/2013 12:00:00 AM
4 Headphone Small headphone 3 2/11/2013 12:00:00 AM
5 MP3Player MP3Player Portable 4 4/11/2013 12:00:00 AM
//运行查询后的DesireTable
Username Role CartName Date
Tri Admin Computer 2/11/2013 12:00:00 AM
Lan Admin Desk 2/11/2013 12:00:00 AM
Lan Admin Headphone 2/11/2013 12:00:00 AM
Nhu Admin Print Paper 3/11/2013 12:00:00 AM
Lac Admin MP3Player 4/11/2013 12:00:00 AM
因此结果必须按“购物车”表格中的“日期”列进行分组。但是查询生成了一条错误消息“Column'Carts.Date'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”我卡在当前上下文中,我需要你的帮助来解决这个问题。
答案 0 :(得分:1)
在我的问题中,我只想将一个列分组为“Date”,但如果我在group by语句中只插入一个Date,则会产生错误。因此,我将连接表中的所有列插入到group by子句中。
select us.Username, ro.Role, ca.CartName, ca.Date from Users us
left join Roles ro on ro.RoleID = us.RoleID
left join Carts ca on ca.UserId = us.ID
group by ca.Date, us.Username, ro.Role, ca.CartName;
将我想要分组的一个列分组的技巧是将该列放在group by子句的第一个位置,以便它首先将该列分组,然后再将另一个分组。通过这种方式,我可以根据需要控制组信息。