简体   繁体   中英

MySQL: Group By Min & Max Value

I have below query

SELECT cped.entity_id, cped.value FROM sales_order so LEFT JOIN sales_order_item soi ON so.entity_id = soi.order_id LEFT JOIN catalog_product_entity_datetime cped ON soi.product_id = cped.entity_id AND cped.attribute_id IN (153,154)

Result:

entity_id   value   
2340        2017-03-01 00:00:00
2340        2017-03-16 00:00:00
2312        2017-03-01 00:00:00
2312        2017-03-31 00:00:00

Need output:

entity_id   value   
2340        2017-03-01 00:00:00 // Start Date
2340        2017-03-16 00:00:00 // End Date

So entity_id wise we have to compare min & max value with current date. It both are less than current date then result should display. I tried using having but not working properly.

If you want entities whose dates are before the current date, you can use aggregation:

SELECT cped.entity_id, GROUP_CONCAT(cped.value ORDER BY cped_value) as values
FROM sales_order so JOIN
     sales_order_item soi
     ON so.entity_id = soi.order_id JOIN
     catalog_product_entity_datetime cped
     ON soi.product_id = cped.entity_id AND
        cped.attribute_id IN (153,154)
GROUP BY cped.entity_id
HAVING  MAXcped_value) < CURDATE();  -- This condition is sufficient

This includes a second column with the values in a list.

If you really want the original rows, then you would put this as a subquery and join back the original values you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM