使用SQL并希望对查询的结果进行排序-原始查询运行良好,但是按其分组后却无法运行。
使用SSMS '18-使用AdventureWorks
数据库。
SELECT
pp.BusinessEntityID,
pp.FirstName,
pp.MiddleName,
pp.LastName,
ppw.PasswordHash,
ppw.PasswordSalt,
pph.PhoneNumber
FROM
Person.Person AS pp
INNER JOIN
Person.Password AS ppw ON pp.BusinessEntityID = ppw.BusinessEntityID
INNER JOIN
Person.PersonPhone AS pph ON pp.BusinessEntityID = pph.BusinessEntityID
GROUP BY
pp.BusinessEntityID ASC, pp.FirstName, pp.MiddleName, pp.LastName,
ppw.PasswordHash, ppw.PasswordSalt, pph.PhoneNumber;
导致错误:
第156条消息,状态15,状态1,第21行
关键字“ ASC”附近的语法不正确。
如果删除了ASC关键字并按BusinessEntityID
降序分组,则代码将运行。我在这里错过一些理论吗?
答案 0 :(得分:1)
这将是按顺序而不是分组
SELECT
pp.BusinessEntityID,
pp.FirstName,
pp.MiddleName,
pp.LastName,
ppw.PasswordHash,
ppw.PasswordSalt,
pph.PhoneNumber
FROM
Person.Person as pp
inner join Person.Password as ppw on pp.BusinessEntityID=ppw.BusinessEntityID
inner join Person.PersonPhone as pph on pp.BusinessEntityID=pph.BusinessEntityID
order by pp.BusinessEntityID ASC, pp.FirstName, pp.MiddleName, pp.LastName, ppw.PasswordHash, ppw.PasswordSalt, pph.PhoneNumber;
但是如果您要使用分组方式,则为
SELECT
pp.BusinessEntityID,
pp.FirstName,
pp.MiddleName,
pp.LastName,
ppw.PasswordHash,
ppw.PasswordSalt,
pph.PhoneNumber
FROM
Person.Person as pp
inner join Person.Password as ppw on pp.BusinessEntityID=ppw.BusinessEntityID
inner join Person.PersonPhone as pph on pp.BusinessEntityID=pph.BusinessEntityID
group by pp.BusinessEntityID , pp.FirstName, pp.MiddleName, pp.LastName, ppw.PasswordHash, ppw.PasswordSalt, pph.PhoneNumber;
但是如果没有聚合,则分组更好,分组依据是聚合