[英]query to find data based on max of one field and specific value of another
My SQL skills are minimal so I hope someone will help me. 我的SQL技能很少,所以我希望有人能帮助我。 I am writing a PHP script in which I need to do some SQL queries:
我正在编写一个PHP脚本,其中需要执行一些SQL查询:
I have a table called product_status, which has three 4 columns: id prod_id status_date status_code 我有一个名为product_status的表,该表具有3个4列:id prod_id status_date status_code
So if we consider a product with id 1000, the table would have entries like: 因此,如果我们考虑ID为1000的产品,则该表将具有以下条目:
id prod_id status_date status_code
1 1000 2015-09-01 08:20:35 100
2 1000 2015-09-01 09:22:40 200
3 1000 2015-09-01 09:35:51 300
4 1000 2015-09-01 09:42:55 400
Now, considering that say 300 is the status code for 'out-of-stock'. 现在,假设说300是“缺货”的状态码。 I want to write a query, where for a given date, it gives me all products that were NOT out-of-stock at the end of that day.
我想写一个查询,对于给定的日期,它可以为我提供当天结束时没有缺货的所有产品。 In other words it should give me products 1000 if I query it for date '2015-09-01' since 300 is NOT the LAST entry for that product for that date in this table.
换句话说,如果我为日期“ 2015-09-01”查询产品,它应该给我产品1000,因为300不是该表中该日期该产品的最后条目。
I am unable to write a query that works for this :( My query is: 我无法编写对此有效的查询:(我的查询是:
select prod_id, status from product_status
where status_code != 300
group by prod_id, status
having date(max(status_date)) = '2015-09-01'
This returns me products which have statuses other than 300 as final status for the given day as well... Can anyone help correct my SQL? 这也会返回给定日期的最终状态不是300的产品。有人可以帮助纠正我的SQL吗?
you want to filter by status, not group by it in this query, like this: 您想要按状态过滤,而不是按以下查询进行分组:
select prod_id, status from product_status
where status_code != 300
group by prod_id
having date(max(status_date)) = '2015-09-01'
Try this query 试试这个查询
SELECT prod_id,
SUBSTRING_INDEX(GROUP_CONCAT(status_date ORDER BY status_date DESC), ',', 1) as max_date,
SUBSTRING_INDEX(GROUP_CONCAT(status_code ORDER BY status_date DESC), ',', 1) as recent_code
FROM product_status
GROUP BY prod_id
HAVING recent_code != '300' AND date(max_date) = '2015-09-01'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.