Sql 从union table get error中选择count“列按…的顺序无效”

Sql 从union table get error中选择count“列按…的顺序无效”,sql,sql-server,Sql,Sql Server,你能帮我修一下吗 无论如何,我不想分组,我想搜索所有 我搜索了几个小时,但没有找到答案 谢谢您的帮助。您需要按非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

你能帮我修一下吗

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

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


谢谢您的帮助。

您需要按非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

无论何时计算数据,都应该有一个group by子句,以便调用表中的列

按非指定id对其进行分组


当您使用诸如count、max、sum、avg之类的聚合函数时,您需要按所需列进行分组

首先,为什么您需要按顺序进行分组,因为您只需要计数

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

我害怕重复这些答案。首先,您的主要查询是获取count,它只给出一行。若我猜对了,那个么您需要使用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
为什么要从父项为162的注释中选择not_id以合并所有行

如果您指定UNION,则表示您

将所有行合并到结果中。这包括副本

因此,如果你有:

not_id
1
2
3
运行union后,根据上述查询结果,您将获得

not_id
1
2
3
1
2
3
这意味着计数后,您将增加x2

下一件事,你运行计数与订单,为什么?在这种情况下,COUNT将输出1个值,因此orderby在该查询中没有意义

此查询将执行您需要的操作:

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

您正在计算所有数据。您没有按“不”分组_id@Nebi:为什么我需要分组?我想全部选择。谢谢?在order语句之前需要一个Group by not_id首先,为什么需要order by,因为您只需要count?@hungndv如果您想全部计数,那么只需删除order by语句即可。您将获得一行中所有的计数。如果您想要所有非\u id的计数,则需要按非\u id分组
not_id
1
2
3
1
2
3
select COUNT(not_id) as [cnt]
from notes 
where parent_not_id = 162