简体   繁体   English

如何合并具有相同日期和参与者ID(MYSQL)的所有行

[英]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. 所以我试图写一个简单的像脚本一样的mysql迁移。
My goal is to select participant_id and date and if they = the same - return a count. 我的目标是选择参与者ID和日期,如果它们=相同,则返回一个计数。
In this example the count would return 4. 在此示例中,计数将返回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. 基本上,我将数据从4行合并到新表中的1行中,该表将具有一个count字段。

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. “技巧”是GROUP BY子句。 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 . COUNT(*)聚合函数返回“折叠”到GROUP的行数。 The MIN(t.id) aggregate returns the lowest value of the id column from rows in the group. MIN(t.id)聚合返回组中各行中id列的MIN(t.id)

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. 当表2中的ID字段为AUTOINCREMENT时,应将其设置为correkt。

TIP: Don't name your columns "date" or "count" because these names CAN be keywords and you will get some trouble later. 提示:不要将列的名称命名为“ date”或“ count”,因为这些名称可能是关键字,以后您会遇到麻烦。

the problem is only the first column id but you can do MIN(id) or MAX(id) if need. 问题仅在于第一列id但如果需要,您可以执行MIN(id)MAX(id)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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