Py学习  »  DATABASE

如何在一个read语句中读取mySQL表中的多个字符串和日期?

PCG • 5 年前 • 1583 次点击  

DOC_OwnerID   DOC_type    DOC_start_date    DOC_end_date   
100            JANUARY     1/1/2017          12/31/2018
100            JANUARY     1/1/2018          12/31/2019
100            DRIVER      1/5/2018          1/4/2019 
100            LICENSE     2/5/2015          2/5/2016
100            LICENSE     4/5/2018          2/5/2019
200            JANUARY     1/2/2017          1/2/2018
200            DRIVER      1/2/2018          1/2/2019  

在我的应用程序逻辑中,我需要找到任何所有者(DOC_OwnerID)在给定的时间段内拥有三个基本的强制文档(一月、驾驶证、驾照)。计数3是必要的,表明业主有三个文件。(每个时间段的文档名称都是唯一的)

例如:OwnerID=100,Date=4/9/2018

true =>     100            JANUARY     1/1/2018          12/31/2019
true =>     100            DRIVER      1/5/2018          1/4/2019 
true =>     100            LICENSE     4/5/2018          2/5/2019

应返回3以显示三份文件在给定日期内均有效。我可以使用COUNT,但由于DPC_类型不唯一,如何选择记录。

我可以在我的申请中通过阅读所有记录为业主。我怎么能在sql中同时做到这一点呢?

谢谢, 普布杜

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54908
 
1583 次点击  
文章 [ 2 ]  |  最新文章 5 年前
forpas
Reply   •   1 楼
forpas    6 年前

您想返回表中的所有有效行,对吗?
doc_owner_id 满足表中条件的:

select t.* 
from tablename t inner join (
  select doc_owner_id 
  from tablename
  where 
    str_to_date('4/9/2018', '%m/%d/%Y') between doc_start_date and doc_end_date
    and
    doc_type in ('JANUARY', 'DRIVER', 'LICENCE')
  group by doc_owner_id
  having count(distinct doc_type) = 3
) g on g.doc_owner_id = t.doc_owner_id
where
  str_to_date('4/9/2018', '%m/%d/%Y') between t.doc_start_date and t.doc_end_date
  and
  t.doc_type in ('JANUARY', 'DRIVER', 'LICENCE')
GMB
Reply   •   2 楼
GMB    6 年前

您可以使用聚合:

SELECT DOC_OwnerID
FROM mytable
WHERE  @mydate >= DOC_start_date AND @mydate <= DOC_end_date
GROUP BY DOC_OwnerID
HAVING
    MAX(DOC_type = 'JANUARY') = 1
    AND MAX(DOC_type = 'DRIVER') = 1
    AND MAX(DOC_type = 'LICENSE') = 1

DOC_OwnerID 是的,对于给定的 @mydate 参数,三个都有 DOC_type