[英]SQL Server query: Incorrect syntax near the keyword 'Group'
I have two tables TableA
and TableB
.我有两个表
TableA
和TableB
。 They have a join on TableA.refID = TableB.SomeID
, then some other columns ( TableA.time
, TableB.kind
).他们在
TableA.refID = TableB.SomeID
上有一个连接,然后是其他一些列( TableA.time
, TableB.kind
)。
I would like make a query, order by time a and group them by type.我想进行查询,按时间排序并按类型分组。
This is the query I use (modified for a best showcase)这是我使用的查询(修改为最佳展示)
SELECT
*, TableA.time AS B, TableB.type AS A
FROM
TableB
INNER JOIN
TableB ON TableB.SomeID = TableA.refID
ORDER BY
B
GROUP BY
TableB.type
I get this exception:我得到这个例外:
Incorrect syntax near the keyword 'Group'.
关键字“组”附近的语法不正确。
How should I correct it?我应该如何纠正它?
ORDER BY
comes after GROUP BY
: ORDER BY
在GROUP BY
:
SELECT *, TableA.time AS B, TableB.type AS A
FROM TableB INNER JOIN
TableB ON TableB.SomeID = TableA.refID
GROUP BY TableB.type
ORDER BY B
The correct syntax is:正确的语法是:
SELECT..
FROM...
WHERE...
GROUP BY..
ORDER BY..
Three things wrong with your query:您的查询有以下三点错误:
You have a group by after an order by.在 order by 之后,您有一个 group by。 You can't order and then group you order grouped results
您无法订购然后分组您订购分组结果
You're selecting *
and grouping, that won't work.您正在选择
*
和分组,这是行不通的。
You're grouping on TableB.type
but TableA.time
is not an aggregate so it either needs to be part of a group or an aggregate.您正在对
TableB.type
分组,但TableA.time
不是聚合,因此它要么需要是组的一部分,要么是聚合的一部分。
Here is an example of what your procedure should look like:以下是您的程序应该是什么样子的示例:
SELECT
TableA.time AS B, TableB.type AS A
FROM
TableB
INNER JOIN
TableB ON TableB.SomeID = TableA.refID
GROUP BY
TableB.type, TableA.time
ORDER BY
TableA.time
OR或者
SELECT Max(TableA.time) AS B, TableB.type AS A
FROM TableB INNER JOIN
TableB ON TableB.SomeID = TableA.refID
GROUP BY TableB.type
ORDER BY Max(TableA.time)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.