【问题标题】:Summing Results in a Table for Repeated Values将重复值的结果汇总到表中
【发布时间】:2020-01-27 21:44:26
【问题描述】:

我目前处于一个我无法弄清楚的棘手情况,我希望大家能够帮助我解决以下问题:

我有一个包含大量列的数据集,但我只会显示与我的问题相关的列(我将它们重命名并将它们放入 Excel 文档中)。

我要做的是开发一个 SQL 查询来计算 PASS 结果的总数,然后计算给定 House Name 的 FAIL 结果的数量。每个结果对应一个特定的居民 ID,每个居民 ID 对应一个特定的房屋名称/房屋 ID。不幸的是,值 Room ID 需要在这个数据集中,并且每个唯一的 Room ID 还对应一个特定的 House Name/House ID。因此,对于给定房屋名称存在的每个唯一房间 ID,都会重复居民 ID。

例如,如果有 7 个房间 ID 与特定房屋名称/房屋 ID 关联,则与该特定房屋名称/房屋 ID 关联的每个唯一居民 ID 将重复 7 次,每个唯一房间 ID 一次。因此,结果也都重复了 7 次。我附上了下面的数据示例。

注意:此处并未包含所有数据。 AAAAAA 数据还有几行未显示,还有许多其他房屋名称/房屋 ID。

任何想法将不胜感激!

【问题讨论】:

  • 样本数据、期望的结果以及您当前的尝试都会有所帮助。
  • 听起来您可能只需要按房屋 ID 分组。

标签: sql sql-server duplicates counting distinct-values


【解决方案1】:

您要查找的是 GROUP BY。

如果不查看您的数据,很难提出确切的查询,但我已经创建了一些测试数据。

create table House (HouseId int, HouseName nvarchar(max));
insert into House (HouseId, HouseName) values (1,'House A'), (2, 'House B'), (3,'House C');

create table Room (RoomId int, RoomName nvarchar(max), HouseId int);
insert into Room (RoomId, RoomName, HouseId) 
values 
  (1,'Room 1 in house A', 1), (2,'Room 2 in house A', 1),
  (3,'Room 3 in house B', 2),(4,'Room 4 in house B', 2),
  (5,'Room 5 in house C', 3),(6,'Room 6 in house C', 3)

create table Resident (ResidentId int, ResidentName nvarchar(max), RoomId int, Result int);
insert into Resident (ResidentId, ResidentName, RoomId, Result)
values 
-- House A = 4 passed, 0 failed
(1, 'Resident 1 in Room 1', 1, 82), (2, 'Resident 2 in Room 1', 1, 76),
(3, 'Resident 3 in Room 2', 2, 91), (4, 'Resident 4 in Room 2', 2, 67),
-- House B = 2 passed, 2 failed
(5, 'Resident 5 in Room 3', 3, 60), (6, 'Resident 6 in Room 3', 3, 64),
(7, 'Resident 7 in Room 4', 4, 28), (8, 'Resident 8 in Room 4', 4, 42),
-- House C = 3 passed, 1 failed
(9, 'Resident 9 in Room 5', 5, 99), (10, 'Resident 10 in Room 5', 5, 57),
(9, 'Resident 11 in Room 6', 6, 75), (10, 'Resident 12 in Room 6', 6, 38)

那么您的查询将类似于:

select
  HouseName,
  [Passed] = SUM(x.Passed),
  [Failed] = SUM(x.Failed)
 from
   Resident re
   outer apply (
       --// Logic to determine if they passed or failed
       --// I arbitrarily chose the number 50 to be the threshold
      select [Passed] = case when re.Result >= 50 then 1 else 0 end,
       [Failed] = case when re.Result < 50 then 1 else 0 end
    ) x
   inner join Room r on r.RoomId = re.RoomId
   inner join House h on h.HouseId = r.HouseId
  group by
    h.HouseName

这是一个小提琴:http://sqlfiddle.com/#!18/30894/1

【讨论】:

  • 嗨,汤姆,谢谢!我尝试了几次将我的数据添加到问题中,但每次它实际上都不会出现。我一定会尝试一下,感谢您抽出宝贵的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 2019-03-26
  • 1970-01-01
  • 2016-11-22
  • 2016-09-17
  • 2019-01-02
  • 1970-01-01
相关资源
最近更新 更多