【问题标题】:Return unique rows in SQL Server 2008返回 SQL Server 2008 中的唯一行
【发布时间】:2013-04-09 10:08:50
【问题描述】:

我有一个带有 2 个 ID 列的 SQL Server 表:Employee_ID & Type_ID

我的表格包含 4 行:

Row 1 (Employee ID: 904, Type_ID: 3)
Row 2 (Employee ID: 904, Type_ID: 7)
Row 3 (Employee ID: 905, Type_ID: 7)
Row 4 (Employee ID: 905, Type_ID: 7)

我想返回所有员工可用的所有类型 ID。所以只需ID 7

所以我希望返回 ID 为 7 的 1 行,因为它适用于两个员工(904 和 905)

如果我运行以下 SQL:

SELECT 
    Type_ID, Count(Type_ID) as MyCount 
FROM 
    EmployeeType
WHERE 
    Employee_ID  IN (904, 905)  
GROUP BY 
    Type_ID

这会返回 2 行

Row 1 (Type_ID: 3, MyCount: 1)
Row 2 (Type_ID: 7, MyCount: 3)

但我只有最高计数的记录(Type_ID 7)。 我尝试添加:

HAVING MAX(Count(CostCentre_ID))

但这显然是非法代码。

如何在我的 SQL 中执行此操作?

【问题讨论】:

  • "deleted" 意味着row 2 的时间戳比row 1 更新=> 它用新值覆盖旧的type_ID 3 - 7?或者有没有row_id 专栏?或者你怎么知道行的顺序?
  • 刚刚更新,如果第 1 行被删除,应该会读到。
  • @user1131657 我不知道您当前的查询有什么问题。
  • 无法从已删除的行中提取信息...预期输出和实际输出是什么?
  • @user1131657 即使包含3 的行被删除,您仍按type_id 分组,并且您的查询仍然有效——sqlfiddle.com/#!3/72ef9/1

标签: sql sql-server-2008 count group-by


【解决方案1】:

受 Barry 的回答启发,即使有这样的“重复”行,也能得到正确的结果:

declare @t table (
  employeeid int, typeid int, notes int
)
insert into @t
  select 904, 3, 0 union
  select 904, 5, 0 union
  select 904, 5, 1 union
  select 904, 7, 0 union
  select 905, 7, 0 union
  select 905, 7, 1 union
  select 908, 3, 0 union
  select 908, 5, 0 union
  select 908, 7, 0 union
  select 908, 9, 0 union
  select 908, 3, 0

获取所有typeids 存在的所有employeeids:

select typeid
from @t
group by typeid
having count(distinct employeeid) = (
  select count(distinct employeeid)
  from @t)

【讨论】:

    【解决方案2】:

    我假设您要查找的TypeId 分配给所有EmployeeId

    Declare @t table
    (
    EmployeeId int,
    TypeId int
    )
    Insert Into @t
    Select 904, 3
    Union 
    Select 904, 5
    Union 
    Select 904, 7
    Union 
    Select 905, 5
    Union 
    Select 905, 7
    Union 
    Select 908, 3
    Union 
    Select 908, 7
    
    
    Select Distinct a.TypeId
    From @t a
    Join 
    (
        Select TypeId,
                COUNT(*) Over(Partition by TypeId)as [Occurs]
        From @t
    )b on a.TypeId = b.TypeId
    
    Where b.Occurs = (Select COUNT(Distinct(EmployeeId))
                    From @t
                    )
    

    这将返回 7,因为这是分配给所有员工的唯一 TypeId

    【讨论】:

    • and a.EmployeeId in (904, 905) - 或者a 表有什么用处?
    • @deathApril 我在EmployeeId 上留下了过滤,因为我假设可能有很多员工,因此查询将计算分配给所有员工的TypeId,无论有多少员工。
    • 那么为什么不从没有ab 表开始呢?
    • 请注意,在此问题未涵盖的特殊情况下,这可能会给出错误的结果:sqlfiddle.com/#!3/d41d8/12191/0
    【解决方案3】:

    你可以试试这个:

    SELECT Type_ID, Occurance FROM 
    (
    SELECT Type_ID, Count(Employee_ID) OVER (PARTITION BY Employee_ID) AS Occurance
    FROM EmployeeType
    ) T
    WHERE T.Occurance > 2
    

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      相关资源
      最近更新 更多