sql - 如何正确使用 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 才是正确的
解决方案
你似乎想要:
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%'
);
推荐阅读
- javascript - 为什么不使用 Object.prototype.toString() 来检查 redux 中的普通对象?
- arrays - 在perl中将哈希转换为数组
- express - 删除会话存储中的所有数据
- css - add circle with specific style to canvas
- gnuplot - 在 gnuplot 中堆叠图形
- sql - 我如何在 sql 的一个查询中带来以下报告?有没有办法在一个查询中同时包含两个数据日期?
- javascript - 使用其值查找某个复选框
- java - Pojo 类名序列化
- .net - 如何以编程方式将标签控件添加到 devexpress xtrareport 详细信息带
- android - 声纳 Android 错误的 Gradle 插件“属性名称具有无效字符 '$'”