简体   繁体   中英

How to consolidate all rows that have the same date and participant id (MYSQL)

So I'm trying to write a simple mysql migration like script.
My goal is to select participant_id and date and if they = the same - return a count.
In this example the count would return 4.
I would then take the count and store it in a variable to be placed into another table.
Basically I'm consolidating the data from 4 rows into 1 row in a new table that will have the a count field.

My data currently.

ID   PARTICIPANT_ID  DATE  
---  --------------  ---------------------
"1"  "4"             "2015-05-06 21:35:37"
"2"  "4"             "2015-05-06 21:35:37"
"3"  "4"             "2015-05-06 21:35:37"
"4"  "4"             "2015-05-06 21:35:37"

My goal.

ID    PARTICIPANT_ID  DATE                   COUNT  
----  --------------  ---------------------  -----
"1"   "4"             "2015-05-06 21:35:37"  "4"

I've attempted writing a query like this:

SELECT ID, PARTICIPANT_ID, DATE FROM mytable

What changes do I need to make to my query to return the specified resultset?

Here's one (of several alternatives) that will return the specified result.

SELECT MIN(t.id) AS id
     , t.participant_id
     , t.date
     , COUNT(*) AS `count`
  FROM mytable t
 GROUP BY t.participant_id, t.date

The "trick" is the GROUP BY clause. That "collapses" all rows with common values for the listed expressions into a single row. The COUNT(*) aggregate function returns a count of rows that were "collapsed" into the GROUP . The MIN(t.id) aggregate returns the lowest value of the id column from rows in the group.

INSERT INTO TABLE2
select null, PARTICIPANT_ID, DATE, COUNT(*) from TABLE1
GROUP BY null, PARTICIPANT_ID, DATE

when ID-Field ist AUTOINCREMENT in TABLE2 he should set it correkt.

TIP: Don't name your columns "date" or "count" because these names CAN be keywords and you will get some trouble later.

the problem is only the first column id but you can do MIN(id) or MAX(id) if need.

SELECT participant_id, `date`, CONT(*)
FROM table1
GROUP BY participant_id, `date`
SELECT participant_id,date,count(*)
FROM yourtable
GROUP BY participant_id, date

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