读取多行的sql查询

0md85ypi  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(358)

我有一张table,上面有每天可用的工具。这就是结构

|   Tool_ID  |     Date         |   Available   |
---------------------------------------
    |    1       |     20180501     |       1         |
    |    1       |     20180502     |       3         |
    |    1       |     20180503     |       1         |
    |    2       |     20180501     |       1         |
    |    2       |     20180502     |       0         |
    |    2       |     20180503     |       2         |

我们可以假设toolid1是锤子,toolid2是铁砧。
我想不花一点时间就弄清楚这3天是否有可用的工具。例如,在5月2日没有铁砧可用的同时,至少有1个toolid=1的锤子可用。
有没有一种方法可以在sql查询中找到答案?

uqdfh47h

uqdfh47h1#

好, group by 以及 min() 请记住:

select tool_id,
       (case when count(*) < 3 then 0
             else min(available)
        end) as min_available_for_all_three_days
from tools t
where date >= '20180501' and date < '20180504'
group by tool_id;

这假设如果缺少一行,则该工具不可用。

mv1qrgav

mv1qrgav2#

select IF(
    (select count(*) 
     from tools 
     where (date >= '20180501' and date <= '20180503')
         and tool_id = 1 and available > 0
    ) = 3,
    (
        (select count(*) 
         from tools 
         where (date >= '20180501' and date <= '20180503')
             and tool_id = 2 and available > 0
        ) = 3,
        "Yes all the tools are available",
        "Tool 2 not available"
    ),

    "Tool 1 not available"
);
b0zn9rqh

b0zn9rqh3#

select tool_id from
(
select tool_id,date,sum(available) as tot_avl_on_day from tools
group by tool_id,date
)t
where tot_avl_on_day=0;

这将检查任意天数,以及是否所有天数都有可用的工具。

wwwo4jvm

wwwo4jvm4#

它将可用天数与日期范围中的天数匹配。您可能需要将日期值转换为日期类型。

SELECT
    `Tool_ID`,
    SUM(IF(`Available` > 0,1,0)) as `daysAvailable`
FROM `Tools`
WHERE `Sate` BETWEEN '2018-05-01' AND '2018-05-03'
    AND `daysAvailable` = DATEDIFF('2018-05-03','2018-05-01');

相关问题