[英]mysql count (SUM CASE) with join on same table
我有一個查詢,我需要比較同一個表中的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
和e2
是表別名 ,因此該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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.