0

我写了一个 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

因此,结果必须按“购物车”表中的“日期”列分组。但是查询生成了错误消息“列 'Carts.Date' 在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。” 我被困在当前的环境中,我需要你的帮助来解决这个问题。

4

1 回答 1

1

在我的问题中,我只想对一列“日期”进行分组,但如果我在 group by 语句中只插入一列日期,则会产生错误。因此,我会将连接表中的所有列插入到 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 子句的第一位,这样它就会先对该列进行分组,然后再对另一列进行分组。通过这样做,我可以根据需要控制组信息​​。

于 2013-03-14T08:57:20.837 回答