【问题标题】:mysql count (SUM CASE) with join on same tablemysql 计数(SUM CASE)与同一张表上的连接
【发布时间】:2018-02-27 12:54:17
【问题描述】:

我有一个查询,我需要比较同一个表中的 2 行(不是连续的),其中一个的 id 必须小于另一个,并且字段的名称必须等于特定值。 如果我不包括连接,我可以提取数据,但是当我尝试连接数据时,我得到“列 e1 未知”。我假设它与计数有关,但我似乎无法修复它。有什么想法吗?

SELECT 
case 
when ( extract( HOUR FROM e1.created_at) = 0 ) then '12am'
when ( extract( HOUR FROM e1.created_at) < 12) then concat(extract(HOUR FROM e1.created_at), 'am') 
when ( extract( HOUR FROM e1.created_at) = 12) then '12pm'
when ( extract( HOUR FROM e1.created_at) > 12) then concat( ( extract(HOUR FROM e1.created_at) -12 ), 'pm') 
end  AS "Time", 
sum(case when e1.result = “result1" and e2.result =“result2" and e1 < e2 then 1 else 0 end) AS ‘My Result'
from event e1 
join event e2 on e2.secondary_id = e1.secondary_id
where e1.started_at > '2018-02-19 00:00:00' and e1.started_at < '2018-02-20 00:00:00'
group by extract(hour from e1.created_at)

【问题讨论】:

  • 编辑您的问题并提供示例数据和所需的结果。但是,这可能是e1 &lt; e2的条件。

标签: mysql sql join count


【解决方案1】:

由于e1e2表别名,这个CASE 表达式不正确:

e1 < e2

您需要指定要比较的event 表中的哪些字段。假设您正在比较时间戳,sum 表达式应如下所示:

sum(case when e1.result = “result1" and e2.result =“result2" and e1.started_at < e2.started_at then 1 else 0 end) AS ‘My Result'

【讨论】: