从联合表中选择计数获取错误'列<名称>在ORDER BY中无效...'

时间:2016-10-20 09:08:36

标签: sql sql-server

你能帮忙解决这个问题吗?

enter image description here

无论如何,我不想分组,我想搜索所有。

我已经搜索了几个小时,但没有找到答案。

感谢您的帮助。

7 个答案:

答案 0 :(得分:1)

首先,为什么您需要order by,因为您只需要计数?

select count(*)
from (
  select not_id from notes where parent_not_id = 162
  union all
  select not_id from notes where parent_not_id = 162
) as T

如果您需要不同记录的计数,则只需要group by而不是order by

select count(*)
    from (
      select not_id from notes where parent_not_id = 162
      union all
      select not_id from notes where parent_not_id = 162
    ) as T
   group by not_id

答案 1 :(得分:0)

您需要按not_id对数据进行分组。像这样:

select count(*)
from (
  select not_id from notes where parent_not_id = 162
  union all
  select not_id from notes where parent_not_id = 162
) as T
group by not_id
order by not_id

答案 2 :(得分:0)

每当你计算数据时,你应该有一个group by子句来调用表的列,

not_id

分组

答案 3 :(得分:0)

select count(*)
from (
  select not_id from notes where parent_not_id = 162
  union all
  select not_id from notes where parent_not_id = 162
) as T
group by not_id
order by not_id

无论何时使用聚合函数,如count,max,sum,avg u都需要按所需列进行分组

答案 4 :(得分:0)

无需订购。您的输出只有一行。

select count(*)
from (
  select not_id from notes where parent_not_id = 162
  union all
  select not_id from notes where parent_not_id = 162
) as T

答案 5 :(得分:0)

我害怕重复这些答案。首先,你的主要查询是获取只能给出一行的计数。如果我猜对了,那么你需要用not_id来计算,你需要将查询写成

select count(*)
from (
  select not_id from notes where parent_not_id = 162
  union all
  select not_id from notes where parent_not_id = 162
) as T
group by T.not_id
order by T.not_id

答案 6 :(得分:0)

为什么要让select not_id from notes where parent_not_id = 162联合所有相同的行?

如果您指定UNION ALL,则表示您

  

将所有行合并到结果中。这包括重复。

所以,如果你有:

not_id
1
2
3

作为运行union之后的上述查询的结果,您将获得

not_id
1
2
3
1
2
3

这意味着在COUNT之后你会增加x2!

接下来你用ORDER BY运行COUNT,为什么?在这种情况下,COUNT将输出1个值,因此ORDER BY在该查询中没有意义。

此查询将满足您的需求:

select COUNT(not_id) as [cnt]
from notes 
where parent_not_id = 162