MYSQL
COUNTY OUTAGE TIME
BOONE 1 2/17/2014 16:03
BOONE 1 2/17/2014 15:36
BOONE 1 2/17/2014 15:18
BOONE 1 2/17/2014 14:14
BOONE 1 2/17/2014 14:13
BROWN 1 2/17/2014 16:03
BROWN 1 2/17/2014 15:36
BROWN 1 2/17/2014 15:18
BROWN 0 2/17/2014 14:14
BROWN 0 2/17/2014 14:13
BUTLER 2 2/17/2014 16:03
BUTLER 2 2/17/2014 15:36
BUTLER 2 2/17/2014 15:18
BUTLER 3 2/17/2014 14:14
BUTLER 3 2/17/2014 14:13
CAMPBELL 0 2/17/2014 16:03
CAMPBELL 0 2/17/2014 15:36
CAMPBELL 0 2/17/2014 15:18
CAMPBELL 0 2/17/2014 14:14
CAMPBELL 0 2/17/2014 14:13
CLERMONT 1 2/17/2014 16:03
CLERMONT 1 2/17/2014 15:36
CLERMONT 1 2/17/2014 15:18
CLERMONT 0 2/17/2014 14:14
CLERMONT 0 2/17/2014 14:13
如何让我的数据看起来更像
COUNTY TIME_1 TIME_2 TIME_3 TIME_4 TIME_5
BOONE 1 1 1 1 1
BROWN 0 1 1 1 0
BUTLER 2 2 2 3 3
每个县总会有五个不同的重复时间。我在这里不知所措。
答案 0 :(得分:2)
你试过吗
SELECT COUNTY,
GROUP_CONCAT(OUTAGE ORDER BY `TIME` DESC SEPARATOR ' ') AS outstr
FROM tbl
GROUP BY COUNTY
这是一个小提琴。 http://sqlfiddle.com/#!2/3a13c/1/0这将为您提供连接成单个字段的五个整数值。它将根据最新的时间列排序。这不完全是你指定的,但它可以为你完成这项工作。
如果您需要五列,可以像这样包装该查询。
SELECT COUNTY,
SUBSTR(outstr, 1, 1) as TIME_1,
SUBSTR(outstr, 3, 1) as TIME_2,
SUBSTR(outstr, 5, 1) as TIME_3,
SUBSTR(outstr, 7, 1) as TIME_4,
SUBSTR(outstr, 9, 1) as TIME_5
FROM (
SELECT COUNTY,
GROUP_CONCAT(OUTAGE ORDER BY `TIME` DESC SEPARATOR ' ') AS outstr
FROM tbl
GROUP BY COUNTY
) AS a
这是一个小提琴。 http://sqlfiddle.com/#!2/3a13c/5/0这有点令人作呕。但是,传统的数据透视技术由于你想要转移到列中的行上缺少明确的标记而变得困难。
答案 1 :(得分:0)
假设您想按最近发生的次数排序;您需要自行加入并使用LIMIT
运算符选择所需的日期:
select
c.county,
t1.outage as outage_1, t1.time as time_1,
t2.outage as outage_2, t2.time as time_2,
t4.outage as outage_3, t3.time as time_3,
t4.outage as outage_4, t4.time as time_4,
t5.outage as outage_5, t5.time as time_5
from counties c
join (
select *
from counties
order by time desc
limit 0,1
) t1 on t1.county = c.county
join (
select *
from counties
order by time desc
limit 1,1
) t2 on t1.county = c.county
join (
select *
from counties
order by time desc
limit 2,1
) t3 on t1.county = c.county
join (
select *
from counties
order by time desc
limit 3,1
) t4 on t1.county = c.county
join (
select *
from counties
order by time desc
limit 4,1
) t5 on t1.county = c.county
警告:与许多支点一样,这不会有效。不要将其用于实时查询,仅用于编译报告数据。