首页 > 解决方案 > 如何正确使用 where order by have order by

问题描述

我目前从 SQL Server 中的查询中收到此错误:

'table1.nr'列在选择列表中无效,因为它不包含在聚合函数中,也不包含在 GROUP BY 子句中。

这是我来自 table1 的数据

nr      artnr   typNr
4747    mob100  3
4747    mob123  4
4842    mob122  1
2051    mob123  5
2051    mob125  5

这是我的查询:

SELECT nr
FROM table1
WHERE artnr LIKE '%Mob%'
GROUP BY typNr
HAVING COUNT(*) > 1
ORDER BY nr asc;

结果我只想得到

nr
4747

我的查询不正确,它需要被覆盖并且 typNr 是不同的,在这种情况下,只有我得到结果 nr 4747 才是正确的

标签: sqlsql-servertsqlgroup-bycount

解决方案


你似乎想要:

SELECT TOP (1) nr -- remove top clause if you want all rows
FROM table1
WHERE artnr LIKE '%Mob%'
GROUP BY nr
HAVING COUNT(DISTINCT typNr) > 1
ORDER BY nr;

如果您想要所有列,则可以使用exists

select t1.*
from tablet1 t1
where exists (select 1 
              from table1 t2 
              where t2.nr = t1.nr and 
                    t2.typNr <> t1.typNr and 
                    t2.artnr like '%mob%'
             );

推荐阅读