除非还指定了TOP或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询等中无效。

时间:2018-05-05 06:40:08

标签: sql sql-server sql-server-2008 tsql

我正在尝试合并以下3个查询:

select distinct  
    col1 
from 
    [dbname] 

select  
    COUNT(*)col2  
from 
    [dbname]  
group by 
    col1 
order by 
    col1

select 
    (COUNT(**)-1) /  COUNT(distinct col3)
from 
    [dbname] 
group by 
    col1 
order by 
    col1

as:

select distinct col1 , 
        (select  COUNT(*)col2 from [dbname] group by col1 order by col1 )as something, 
        (select (COUNT(*)-1) /  COUNT(distinct col3)from [dbname] group by col1 order by col1) as something1 
from [dbname]

但是我收到以下错误:

  

ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP或FOR XML。

如何正确构建它?

2 个答案:

答案 0 :(得分:0)

您可以使用subquery

select col1, count(*) something1,
       count(*)-1 / (select count(distinct col3) from dbname where col1 = d.col1) something2
from dbname d
group by col1;

但是,您也可以将其直接转换为单SELECT语句

select col1, count(*) something1,
       (count(*)-1 / count(distinct col3)) something2
from dbname d
group by col1;

编辑请注意除以零错误,因此您可以加入case表达式

select col1, count(*) something1,
       coalesce((count(*)-1/(case when count(distinct col3) = 0 
                                  then null else count(distinct col3) end)), 0) something2
from dbname d
group by col1;

答案 1 :(得分:0)

查看您的查询似乎您可以使用单个选择避免对列值进行子选择

select col1, count(*) as col2, 
       (count(*)-1)/ count(distinct col3) as col_somethings
from [dbname]
group by col1 
order by col1