按天计算参与度

时间:2016-04-21 16:49:32

标签: sql sql-server tsql

我有一个解决这个问题的方法,但我不知道它是否是最好的方法,所以我正在寻找更好的选择。

我试图在两周之间计算参与度

所以两个人参加一项为期两周的运动

人A 人b

第1周

Day 1: A, b
DAY 2: A, b
Day 3: a, b
Day 4: a, b
Day 5: a, b

第2周

Day 1: A, B
DAY 2: A
DAY 3: A
Day 4: A, B
Day 5: B

所以我想知道与前一周相比我失去了多少参与者 所以输出看起来像

LOSS:第1天:0,第2天:1,第3天:1,第4天:0,第5天:1

所以我现在正在做的是在caluse中使用子查询,并且不使用和循环这些日子

DECLARE @days table (d TIN

INSERT INTO @days
     VALUES(1), (2), (3), (4), (5), (6), (7)

SELECT COUNT(Person), DayOfWeek
FROM participation
WHERE WEEK = Week1
AND DAY = @day
AND PERSON NOT IN (SELECT Person
                   FROM participation
                   WHERE WEEK = Week2
                   and Day = @day)

想出来

使用了与下面的答案非常相似的方法

  WITH CTE AS
(SELECT dayofweek, person
 FROM Participation
 Where week = week1)

   SELECT DayOfWeek, COunt(CTE.Person), COunt(a.Person)
   FROM CTE
   LEFT JOIN (SELECT DayOfWeek, Person
          FROM Participation
          where week = week2)a
   ON a.Person = CTE.Person
   and a.dayofweek = cte.dayofweek

我把它放到带有计算列的#table中,然后得到每天的分钟,我得到了答案。谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

您希望避免SQL中的循环 - 尽管我无法在您的代码中看到所述循环。您是否使用光标填充@day?

无论如何,我不确定您的数据类型(或表结构),但假设week是一个字符串,并且所有内容都存储在一个participation表中,那么这将使您获得从第1周到第2周的损失:

;with cte_people ( week, DayOfWeek, person_count)
as
(
     select  WEEK, DayOfWeek, count(person)
     from participation
     group by WEEK, DayOfWeek
)

select c1.DayOfWeek, c1.person_count - c2.person_count as loss
from cte_people c1
inner join cte_people c1
on c2.DayOfWeek = c1.DayOfWeek
and c2.week = 'Week2'
where c1.week = 'Week1'