我有一张桌子
id | event_id | stat_count | month | year
1 | 1 | 12 | 01 | 2070
2 | 1 | 11 | 02 | 2070
3 | 2 | 14 | 01 | 2070
4 | 2 | 15 | 04 | 2070
等等。
我需要通过event_id分组来获取数据。月份将是从01到12,但不一定是所有月份,并且stat_count可能已插入表格中。提供的日期不是英文日期格式。 我需要得到如下结果
event data
Fevent 12,21,0,3,0,9,0,0,12,23,34,0
Fevent2 12,0,3,4,3,0,3,2,3,4,0,0
等等。
以下是我尝试使用group_concat
的查询:
select
(select event_name from vital_events where id=VEC.vital_event_id) name,
group_concat(
CASE when VEC.month='01' then VEC.stat_count
when VEC.month='02' then VEC.stat_count
when VEC.month='03' then VEC.stat_count
when VEC.month='04' then VEC.stat_count
when VEC.month='05' then VEC.stat_count
when VEC.month='06' then VEC.stat_count
when VEC.month='07' then VEC.stat_count
when VEC.month='08' then VEC.stat_count
when VEC.month='09' then VEC.stat_count
when VEC.month='10' then VEC.stat_count
when VEC.month_nepali='11' then VEC.stat_count
when VEC.month='12' then VEC.stat_count
else 0 end order by VEC.month
)as data
from vital_event_counts as VEC
group by VEC.vital_event_id
答案 0 :(得分:1)
使用CROSS JOIN
的另一个版本查找应包含的所有月份,然后对具有现有值的表使用LEFT JOIN
;
SELECT x.event_id,
GROUP_CONCAT(COALESCE(stat_count,0) ORDER BY x.month) stat_count
FROM
(SELECT DISTINCT event_id, m.month FROM Table1 CROSS JOIN
(SELECT 1 month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL
SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) m
) x
LEFT JOIN Table1
ON table1.month = x.month AND table1.event_id = x.event_id
AND year = 2070
GROUP BY x.event_id
答案 1 :(得分:0)
不漂亮,但是......
SELECT
event_id,
CONCAT(
(SELECT COALESCE(SUM(stat_count), 0) FROM tbl WHERE id = t.id AND month = 1), ',',
(SELECT COALESCE(SUM(stat_count), 0) FROM tbl WHERE id = t.id AND month = 2), ',',
(SELECT COALESCE(SUM(stat_count), 0) FROM tbl WHERE id = t.id AND month = 3), ',',
⋮
(SELECT COALESCE(SUM(stat_count), 0) FROM tbl WHERE id = t.id AND month = 12)
) AS data
FROM
tbl AS t