我有一个类似于下表的表(当然有更多的行和字段):
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我想对它进行转换,这样我就可以计算第一步和最后一步之间的时间,并最终找到第一步和最后一步之间的平均时间,等等。基本上,我对如何将上面的表格转换为以下内容感到困惑:
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任何帮助都将不胜感激。
有了OMG小马的帮助,下面是解决方案:
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发布于 2010-07-27 23:34:24
根据问题更新/澄清进行了更新:
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发布于 2010-07-27 23:34:08
一个简单的GROUP BY就可以做到这一点
SELECT category_id
, MIN(first_date)
, MAX(last_date)
FROM TABLE
GROUP BY category_ID发布于 2010-07-27 23:34:57
答案很简单:
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'您还可以在查询中进行计算,而不只是返回两个日期值。
https://stackoverflow.com/questions/3345252
复制相似问题