简体   繁体   中英

Grouping based on current timestamp in sql

Okay So I have a df like this:

MEETING_ID                       sSTART 
       322      2021-05-01 23:45:00.000
       322      2021-05-03 13:45:00.000
       312      2021-05-11 23:45:00.000
       312      2021-05-13 23:45:00.000

And all I want is a table that can tell me how many previous meetings have occurred and how many meetings are coming up...

To do this I use the CURRENT_TIMESTAMP function, unsure if this is wrong but here's my query that isnt working... For the purposes of this post let's say current time is 5/2/2021 10:40PM

WITH s AS (
  SELECT MEETING_ID, 
CASE WHEN sSTART > CURRENT_TIMESTAMP THEN 1
ELSE 0
END PREVIOUS_MEETING,
CASE WHEN sSTART < CURRENT_TIMESTAMP THEN 1
ELSE 0
END UPCOMING_MEETING
FROM df
  ),
  ddd AS (SELECT
  MEETING_ID,
  COUNT(PREVIOUS_MEETING),
  COUNT(UPCOMING_MEETING)
  FROM s
  GROUP BY MEETING_ID
  )
  SELECT *
  FROM ddd

In the end I want this:

MEETING_ID      PREVIOUS_MEETING    UPCOMING_MEETING
       322                     1                   1
       312                     2                   0

I'm unsure why this is the case but some explanation would help.

You just want a basic pivot query here:

SELECT
    MEETING_ID,
    SUM(sSTART > CURRENT_TIMESTAMP)  AS PREVIOUS_MEETING,
    SUM(sSTART <= CURRENT_TIMESTAMP) AS CURRENT_MEETING
FROM df
GROUP BY
    MEETING_ID;

Note that we are summing boolean expressions above, which is valid syntax in MySQL. On other databases, you might have to take conditional counts, something like this:

SELECT
    MEETING_ID,
    COUNT(CASE WHEN sSTART > CURRENT_TIMESTAMP THEN 1 END)  AS PREVIOUS_MEETING,
    COUNT(CASE WHEN sSTART <= CURRENT_TIMESTAMP THEN 1 END) AS CURRENT_MEETING
FROM df
GROUP BY
    MEETING_ID;

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