2017-08-01 33 views
-1

第一個Stackoverflow問題 - 所以容易對我:)。Summing自定義列

你好,我試圖用下面的查詢標記項目作爲「歸因」。實質上,如果患者ID具有PERSON_PROVIDER_RELATIONSHIP標誌,則針對該實例給予1。如果他們有另一種類型的標誌(還有其他兩種可能的標誌可以接收)。一切都很順利(將「1」分配給PERSON_PROVIDER_RELATIONSHIP的實例),但是當我嘗試總結創建的自定義列(「Attribution」)時,出現此錯誤:(Column「Attribution」不存在)。我得到這個錯誤,無論我是否嘗試創建另一個列來進行求和,或者當我添加一個「having」子句到最後我聲明我只想查看總和> 0的記錄時。任何幫助,將不勝感激!我正在使用MySQL編寫此代碼,並很樂意提供任何澄清信息。

select distinct c.empi_id as "Patient", 
c.incurred_from_date as "Service Date", 
(case when c.billing_organization_source_id IN ('xxxx','yyyy') then 1 else 0 
end) as "In-Network Indicator", 
(case when t.ref_record_type = 'PERSON_PROVIDER_RELATIONSHIP' then 1 else 0 
end) as "Attribution", 
(sum("Attribution") over (partition by c.empi_id)) as "Attribution Flag", 
p.cleanprovidername as "Provider", t.ref_record_type 
from ph_f_annotated_claim c 
left outer join PH_F_Attribution_Component_Data_Point t 
on t.empi_id = c.empi_id and t.population_id = c.population_id 
inner join ph_d_personnel_alias a 
on a.prsnl_id = t.prsnl_id 
inner join xxxx_xxxx_xxxx_xxxx p 
on a.prsnl_alias_id = p.NPI 
where (c.bill_type_code like '33%' 
or c.bill_type_code like '32%' 
or c.bill_type_code like '033%' 
or c.bill_type_code like '032%') 
and c.source_description = 'MSSP Claims' 
and c.incurred_from_date >= '2015-12-01' 
and c.incurred_from_date <= '2017-01-31' 
and c.population_id = '2feb2cb1-be55-4827-a21f-4e2ef1a40340' 
and p.DegreeName IN ('MD','DO') 
and a.prsnl_alias_type = 'NPI' 
and p.PrimaryPHO = 'Yes' 
group by c.empi_id, c.incurred_from_date, c.billing_organization_source_id, 
p.cleanprovidername, t.ref_record_type 
+0

見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me -to-be-a-very-simple-sql-query – Strawberry

+0

你能否澄清一下你正在使用的RDBMS – Strawberry

回答

1

在同一個SELECT子句中,不能使用別名列作爲表達式。你必須做這樣的事情:

sum(case when t.ref_record_type = 'PERSON_PROVIDER_RELATIONSHIP' then 1 else 0 end) over (partition by c.empi_id) as "Attribution Flag" 
+0

謝謝!有沒有什麼方法根據別名列的總和使用「having」子句排除記錄?你所說的工作就像一個魅力,但拋出一個「有(總和(」Attribution旗幟「)> 0」返回相同的「列」歸因「不存在」的錯誤 –

+0

你必須做同樣的事情'HAVING '子句:使用整個表達式而不是別名。在某個時候,將這個表達式放在子查詢或CTE中會更簡單,然後* then *可以通過列名稱在主查詢中引用它。 –