[英]Cannot group by shared field - Oracle SQL
我有一個聲明:
SELECT adherence_date,
CASE scheduled_time
WHEN 'morning' THEN CASE acknowledged_at WHEN null THEN 0 ELSE 1 END
ELSE null END AS morning,
CASE scheduled_time
WHEN 'afternoon' THEN CASE acknowledged_at WHEN null THEN 0 ELSE 1 END
ELSE null END AS afternoon,
CASE scheduled_time
WHEN 'evening' THEN CASE acknowledged_at WHEN null THEN 0 ELSE 1 END
ELSE null END AS evening,
CASE scheduled_time
WHEN 'night' THEN CASE acknowledged_at WHEN null THEN 0 ELSE 1 END
ELSE null END AS night
FROM MEDICATION_ADHERENCES
WHERE PATIENT_ID = 10049;
輸出:
[
#<MedicationAdherence:0x007f8425947860> {
"id" => nil,
"adherence_date" => Thu, 27 Oct 2016,
"morning" => 1,
"afternoon" => nil,
"evening" => nil,
"night" => nil
},
#<MedicationAdherence:0x007f8425947360> {
"id" => nil,
"adherence_date" => Thu, 27 Oct 2016,
"morning" => nil,
"afternoon" => 1,
"evening" => nil,
"night" => nil
},
#<MedicationAdherence:0x007f8425946d98> {
"id" => nil,
"adherence_date" => Thu, 27 Oct 2016,
"morning" => nil,
"afternoon" => nil,
"evening" => 1,
"night" => nil
},
#<MedicationAdherence:0x007f8425946aa0> {
"id" => nil,
"adherence_date" => Thu, 27 Oct 2016,
"morning" => nil,
"afternoon" => nil,
"evening" => nil,
"night" => 1
}
]
我希望將結果按adherence_date
分組,以便返回
#<MedicationAdherence:0x007f8425946aa0> {
"id" => nil,
"adherence_date" => Thu, 27 Oct 2016,
"morning" => 1,
"afternoon" => 1,
"evening" => 1,
"night" => 1
}
但是,當我添加GROUP BY ADHERENCE_DATE
它返回錯誤OCIError: ORA-00979: not a GROUP BY expression
我在這里不明白什么? 我正在運行oracle-12c
編輯
MedicationAdherence記錄如下:
MedicationAdherence {
:id => :integer,
:adherence_date => :date,
:scheduled_time => :string,
:acknowledged_at => :datetime,
:patient_id => :integer,
:created_at => :datetime,
:updated_at => :datetime
}
您需要對其余列使用聚合函數。 我猜你想要:
SELECT adherence_date,
SUM(CASE WHEN scheduled_time = 'morning' AND acknowledged_at is not null THEN 1 ELSE 0
END) AS morning,
SUM(CASE WHEN scheduled_time = 'afternoon' AND acknowledged_at is not null THEN 1 ELSE 0
END) AS afternoon,
SUM(CASE WHEN scheduled_time = 'evening' AND acknowledged_at is not null THEN 1 ELSE 0
END) AS evening,
SUM(CASE WHEN scheduled_time = 'night' AND acknowledged_at is not null THEN 1 ELSE 0
END) AS night
FROM MEDICATION_ADHERENCES
WHERE PATIENT_ID = 10049
GROUP BY adherence_date;
嵌套case
不僅更加復雜,而且沒有按照您的意願進行。 when null
永不匹配時,因為null
不等於null
。
我能夠解決這個問題
SELECT
adherence_date,
patient_id,
sum(case when scheduled_time = 'morning' then nvl2(acknowledged_at,1,0) end) as morning,
sum(case when scheduled_time = 'afternoon' then nvl2(acknowledged_at,1,0) end) as afternoon,
sum(case when scheduled_time = 'evening' then nvl2(acknowledged_at,1,0) end) as evening,
sum(case when scheduled_time = 'night' then nvl2(acknowledged_at,1,0) end) as night
FROM medication_adherences
GROUP BY adherence_date, patient_id
回答這個問題: 按日期匯總多個記錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.