【发布时间】:2018-02-22 12:26:53
【问题描述】:
我有一个查询,其中我需要 3 列以及一个额外的“时间”列,我需要做的是运行每个计数查询并将它们与相关的时间相匹配,但是发生的事情是查询是返回计数的总和并将它们添加到每次。见下文。
应该发生的事情是我得到一个这样的列表:
我知道这是我最后分组的方式,但我似乎无法在计数范围内分组,有人有什么想法吗?
SELECT
case
when ( extract( HOUR FROM e.started) = 0 ) then '12am'
when ( extract( HOUR FROM e.started) < 12) then concat(extract(HOUR FROM e.started), 'am')
when ( extract( HOUR FROM e.started) = 12) then '12pm'
when ( extract( HOUR FROM e.started) > 12) then concat( ( extract(HOUR FROM e.started) -12 ), 'pm')
end AS "Time",
(
SELECT COUNT(*)
FROM eventinfo e
join tickets o on e.ticket_id = o.id
where e.created > '2018-02-20 00:00:00' and e.created < '2018-02-21 00:00:00'
and o.stagename = ’Stage3'
) AS 'Column1',
(
SELECT COUNT(*)
FROM eventinfo e
join tickets o on e.ticket_id = o.id
where e.created > '2018-02-20 00:00:00' and e.created < '2018-02-21 00:00:00'
and o.stagename = ’Stage2'
) AS 'Column2',
(
SELECT COUNT(*)
FROM eventinfo e
join tickets o on e.ticket_id = o.id
where e.created > '2018-02-20 00:00:00' and e.created < '2018-02-21 00:00:00'
and o.stagename = ’Stage1'
) AS 'Column3'
FROM eventinfo e
group by extract(hour from e.started)
编辑: 如果我从每个计数查询中查询时间,我会收到错误:“操作数应包含 1 列”
SELECT
(
SELECT
case
when ( extract( HOUR FROM e.started_at) = 0 ) then '12am'
when ( extract( HOUR FROM e.started_at) < 12) then concat(extract(HOUR FROM e.started_at), 'am')
when ( extract( HOUR FROM e.started_at) = 12) then '12pm'
when ( extract( HOUR FROM e.started_at) > 12) then concat( ( extract(HOUR FROM e.started_at) -12 ), 'pm')
end AS "Time",
COUNT(*)
FROM events e
join operations o on e.operation_id = o.id
where e.created_at > '2018-02-20 00:00:00' and e.created_at < '2018-02-21 00:00:00'
and o.stagename = ’Stage1'
) AS 'Column1',
(
SELECT
case
when ( extract( HOUR FROM e.started_at) = 0 ) then '12am'
when ( extract( HOUR FROM e.started_at) < 12) then concat(extract(HOUR FROM e.started_at), 'am')
when ( extract( HOUR FROM e.started_at) = 12) then '12pm'
when ( extract( HOUR FROM e.started_at) > 12) then concat( ( extract(HOUR FROM e.started_at) -12 ), 'pm')
end AS "Time",
COUNT(*)
FROM events e
join operations o on e.operation_id = o.id
where e.created_at > '2018-02-20 00:00:00' and e.created_at < '2018-02-21 00:00:00'
and o.stagename = ’Stage2'
) AS 'Column2',
(
SELECT
case
when ( extract( HOUR FROM e.started_at) = 0 ) then '12am'
when ( extract( HOUR FROM e.started_at) < 12) then concat(extract(HOUR FROM e.started_at), 'am')
when ( extract( HOUR FROM e.started_at) = 12) then '12pm'
when ( extract( HOUR FROM e.started_at) > 12) then concat( ( extract(HOUR FROM e.started_at) -12 ), 'pm')
end AS "Time",
COUNT(*)
FROM events e
join operations o on e.operation_id = o.id
where e.created_at > '2018-02-20 00:00:00' and e.created_at < '2018-02-21 00:00:00'
and o.stagename = ’Stage3'
) AS 'Column3'
【问题讨论】:
-
请标记您的 DBMS 以获得正确答案
-
对不起@iSR5,它的mysql
-
我认为你应该修改你的架构。
标签: mysql sql time group-by count