[英]MySQL Combine multiple rows
I have a table similar to the following (of course with more rows and fields): 我有一个类似于以下的表格(当然有更多的行和字段):
category_id | client_id | date | step
1 1 2009-12-15 first_step
1 1 2010-02-03 last_step
1 2 2009-04-05 first_step
1 2 2009-08-07 last_step
2 3 2009-11-22 first_step
3 4 2009-11-14 first_step
3 4 2010-05-09 last_step
I would like to transform this so that I can calculate the time between the first and last steps and eventually find the average time between first and last steps, etc. Basically, I'm stumped at how to transform the above table into something like: 我想对此进行转换,以便我可以计算出第一步和最后一步之间的时间,并最终找到第一步和最后一步之间的平均时间,等等。基本上,我很困惑于如何将上表转换为类似以下内容的方法:
category_id | first_date | last_date
1 2009-12-15 2010-02-03
1 2009-04-05 2009-08-07
2 2009-11-22 NULL
3 2009-11-14 2010-05-09
Any help would be appreciated. 任何帮助,将不胜感激。
With OMG Ponies help, here's the solution: 在OMG Ponies的帮助下,以下是解决方案:
SELECT t.category_id,
MIN(t.date) AS first_date,
CASE
WHEN COUNT(*) >= 2 THEN MAX(t.date)
ELSE NULL
END AS last_date
FROM TABLE t
GROUP BY t.category_id, t.client_id
Updated based on question update/clarification: 根据问题更新/说明进行了更新:
SELECT t.category_id,
MIN(t.date) AS first_date,
CASE
WHEN MAX(t.date) = MIN(t.date) THEN NULL
ELSE MAX(t.date)
END AS last_date
FROM TABLE t
GROUP BY t.category_id, t.client_id
a simple GROUP BY
should do the trick 一个简单的GROUP BY
应该可以解决问题
SELECT category_id
, MIN(first_date)
, MAX(last_date)
FROM TABLE
GROUP BY category_ID
Try: 尝试:
select category_id , min(date) as first_date , max(date) as last_date from table_name group by category_id , client_id
simple answer: 简单的答案:
SELECT fist.category_id, first.date, last.date
FROM tableName first
LEFT JOIN tableName last
ON first.category_id = last.category_id
AND first.step = 'first_step'
AND last.step ='last_step'
You could also do the calculations in the query instead of just returning the two date values. 您也可以在查询中进行计算,而不仅仅是返回两个日期值。
You need to do two sub queries and then join them together - something like the following 您需要执行两个子查询,然后将它们连接在一起-类似于以下内容
select * from (select *, date as first_date from table where step = "first_step") a left join ( select * date as last_date from table where step = "lastt_step") b on (a.category_id = b.category_id) 从(a.category_id = b.category_id)上的一个左联接(从step =“ first_step”的表中,选择*日期作为from last_date的表)中的select * from
Enjoy! 请享用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.