Sql查询读取多行

时间:2018-06-06 16:13:45

标签: mysql sql database

我有一张表存储了每天工具的可用性。 这是结构

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

我们可以假设 toolID 1是一个锤子, toolID 2是一个铁砧。

我想知道,如果工具在这3天内可用,不用一会儿就可以了。 例如,至少有1个 toolID = 1,锤子可用,同时5月2日没有铁砧。

有一种方法可以在SQL查询中找到它吗?

4 个答案:

答案 0 :(得分:0)

好了,group bymin()浮现在脑海中:

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;

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

答案 1 :(得分:0)

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;

这将检查任何天数以及是否有工具在所有日子都可用。

答案 2 :(得分:0)

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"
);

答案 3 :(得分:0)

这匹配了日期范围内天数的可用天数。您可能必须将日期值转换为日期类型。

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');