简体   繁体   English

T-SQL选择具有相同列值的完整行

[英]T-SQL Select full rows with same column value

I want to show all rows that has a serial that exist in another row. 我想显示具有在另一行中存在的序列的所有行。

If I do like this it works 如果我喜欢它,它会起作用

SELECT 
      [Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
HAVING COUNT(*) > 1

But when I add more select columns 但是当我添加更多选择列时

SELECT [ID]
      ,[UUID]
      ,[Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
HAVING COUNT(*) > 1

I get 我懂了

'ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. “ ID”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

Why can't I select more columns? 为什么我不能选择更多列?

How am I suppose to show the full rows? 我应该如何显示完整的行?

You can do this with a window function: 您可以使用窗口函数执行此操作:

select *
from (
   select *, 
          count(*) over (partition by [Serial]) as serial_count
   from [x].[dbo].[Devices]
)  t
where serial_count > 1;

This is typically faster then joining to a sub-select with an aggregate. 通常,这要比通过聚合加入子选择更快。

Hope you need this query, it will show all the rows that has a serial that exist in another row. 希望您需要此查询,它将显示所有具有另一行中存在的序列的行。

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]

As long as ID and UUID are unique to the serial, try grouping by all columns. 只要ID和UUID对于序列而言是唯一的,请尝试按所有列进行分组。

SELECT [ID]
  ,[UUID]
  ,[Serial]
FROM [x].[dbo].[Devices]
GROUP BY Serial
  ,[ID]
  ,[UUID]
HAVING COUNT(*) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM