简体   繁体   English

在使用order by时将select语句嵌套在from子句中

[英]Nest select statement in from clause while using order by

In SQL Server I try to include a select statement into a from clause while using an order by statement and I get an error "Incorrect syntax near the keyword 'group'". 在SQL Server中,我尝试在使用order by语句时将select语句包含在from子句中,并且出现错误“关键字'group'附近的语法不正确”。

select name, value, count(distinct id) as results
from (select 'test' as name, 'test 2' as value, 5 as id)
group by name, value

What is the problem with my syntax and how to do what I am trying to? 我的语法有什么问题,我该怎么做?

the inner select statement is just a dummy example. 内部的select语句只是一个虚拟的例子。 In my case I do have a select statement with many rows where only the id is different. 就我而言,我确实有一条select语句,其中有许多行,其中只有id是不同的。

Thanks! 谢谢!

You need to give the subquery an alias, eg 您需要给子查询一个别名,例如

select name, value, count(distinct id) as results
from (select 'test' as name, 'test 2' as value, 5 as id) AS t -- Alias Here
group by name, value;

This sucessfully returns: 成功返回:

name    value       results
------------------------------
test    test 2      1

You miss the subquery alias: 您错过了子查询别名:

select 
    name, value, count(distinct id) as results
from 
    (select 'test' as name, 'test 2' as value, 5 as id) SQ
group by 
    name, value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM