如何检查给定的日期是否至少包含为用户列出的每个文档组?

wh6knrhe  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(318)

我想开发一个sql查询来检查给定的日期是否至少在每个文档组中。下表为

DocID    UserID     StartDAte     EndDAte     OfficialName
1        1         10/1/18       10/3/18       A
2        1         10/5/18       10/10/18      A
3        1         10/1/18       10/9/18       B
4        1         10/1/18       10/9/18       C
5        1         10/1/18       10/5/18       D
6        1         10/7/18       10/20/18      D

有4个文档组,即a、b、c、d。需要检查给定的日期是否至少在每个组中的每个文档中。

eg date : 10/2/18 is in first record of A,B,C, and first record of D. So it is passed.
eg date : 10/4/18 is not in either of documents in A hence failed.
eg date : 10/8/18 is second document in A,B,C, and second document in D hence passed.
eg date : 10/6/18 is in A but not in D hence failed.

因为我必须为给定的用户和日期写这个,所以我必须使用“in”子句来表示“officialname”,但是如何在每个“officialname”组中的任何文件中为给定用户的所有文档添加“or”来检查日期?
感谢您的帮助。需要补充一些不清楚的东西。正式文件的数量不是固定的。可能是一个或多个。

gz5pxeao

gz5pxeao1#

我想你想要:

select (case when count(distinct t.officialname) = 4 then 'passed' else 'failed' end) as flag_4groups
from t
where @date <= t.startdate and
      @date >= t.enddate and
      t.user_id = @user;

如果您希望对所有用户(给定日期除外)使用此功能:

select t.user_id,
       (case when count(distinct t.officialname) = 4 then 'passed' else 'failed' end) as flag_4groups
from t
where @date <= t.startdate and
      @date >= t.enddate
group by t.user_id
abithluo

abithluo2#

聚合并获得组的不同计数。如果你得到4,你就有一场比赛,否则你就没有了。

SELECT count(DISTINCT t.officialname)
       FROM elbat t
       WHERE t.userid = <given user>
             AND t.startdate <= <given date>
             AND t.enddate >= <given date>;

您还可以添加 HAVING count(DISTINCT t.officialname) = 4 当且仅当没有匹配项时得到一个空集。

6jjcrrmo

6jjcrrmo3#

您可以使用:

SELECT count(DISTINCT t.officialname)
  FROM elbat t
  WHERE @date between t.startDate  AND t.enddate and
     t.userid = @userId;

相关问题