简体   繁体   中英

Select and group MySql table

I need a little help to count and group some MySql table records according of a range of dates given. The table strcutre is this:

在此输入图像描述

In advance, thank you for your help

This shoud give you the result that you need:

SELECT
  d1.dt,
  COUNT(DISTINCT t1.recid) AS departures,
  COUNT(DISTINCT t2.recid) AS returns,
  COUNT(DISTINCT t1.recid) + COUNT(DISTINCT t2.recid) AS total
FROM (SELECT departure_date AS dt FROM yourtable
      UNION SELECT return_date FROM yourtable) d1
  LEFT JOIN yourtable t1 ON d1.dt = t1.departure_date
  LEFT JOIN yourtable t2 ON d1.dt = t2.return_date
GROUP BY
  d1.dt

The first subquery will return all dates, not duplicated, present in your table (departures and returns).

I'm then trying to join each date to a departure date, using a LEFT JOIN. I'm then counting the DISTINCT t1.recid that make the join succeed..

I'm then trying to join each date to a return date, using LEFT JOIN. Total is the sum of both counts.

Fiddle is here .

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