我想显示所有具有另一行中存在的序列的行。
如果我喜欢这样,那就可以了。
SELECT
[Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
HAVING COUNT(*) > 1
但是当我添加更多选择列
时SELECT [ID]
,[UUID]
,[Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
HAVING COUNT(*) > 1
我得到了
'ID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
为什么我不能选择更多列?
我想如何显示完整的行?
答案 0 :(得分:3)
您可以使用窗口功能执行此操作:
select *
from (
select *,
count(*) over (partition by [Serial]) as serial_count
from [x].[dbo].[Devices]
) t
where serial_count > 1;
这通常比加入带聚合的子选择更快。
答案 1 :(得分:2)
希望您需要此查询,它将显示具有另一行中存在的序列的所有行。
SELECT D1.[ID]
,D1.[UUID]
,D1.[Serial]
FROM [x].[dbo].[Devices] D1
JOIN ( SELECT [Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
HAVING COUNT(*) > 1 ) D2 ON D1.[Serial] = D2.[Serial]
答案 2 :(得分:1)
只要ID和UUID对于序列是唯一的,请尝试按所有列进行分组。
SELECT [ID]
,[UUID]
,[Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
,[ID]
,[UUID]
HAVING COUNT(*) > 1