這裏是論壇新手。我的問題是,如何獲得一列的數量並根據案例陳述呈現?我已經搜索了論壇並找到了與獲得計數,金額和總計有關的答案,但沒有發現任何與案例陳述的附加條件有關的問題。以下是我目前的代碼。該代碼可以正常工作,但不會根據需要返回信息。SQL計數或聚合錯誤
例如可以說在一個特定的程序中有5個不同的站點有10次訪問。我怎樣才能得到的輸出顯示爲這樣:
visits e4pv.site_providing_service_name, State location program_name
2 a b c d
2 b b c d
2 c b c d
2 d b c d
2 e b c d
和查詢是:
select distinct
count (e4pv.people_id) as visits,--field is not numeric
e4pv.site_providing_service_name,
e4pv.actual_date,
CASE
when --case_out_locations_based_on_states
end as State,
CASE
when rcis.program_name in ('')
then rcis.managing_office_name
when rcis.program_name not in ('')
then rcis.profile_name
end as location,rcis.program_name, e4pv.event_name
from dbo.rpt_events_4people_view as e4pv
join dbo.rpt_critical_info_script as rcis with (nolock) on
e4pv.people_id = rcis.people_id and
e4pv.site_providing_service = rcis.managing_office_id
left outer join dbo.program_modifier_enrollment_view as pmev with(nolock) on
rcis.people_id = pmev.people_id
where
rcis.program_name not in ('')
and e4pv.event_name in ('')
and date between '07/01/2015' and '06/30/2016'
GROUP BY
e4pv.people_id,
e4pv.site_providing_service_name,
e4pv.actual_date,
rcis.managing_office_name,
rcis.profile_name,
rcis.program_name
感謝您的幫助
更新過的語法
我已經更新的語法建議使用子查詢並將小組聲明添加到小組中,但仍然無法獲得結果。該代碼導致錯誤,如組附近的語法錯誤等。
select visits, State, location, rcis.program_name, e4pv.event_name
from (
select distinct
count(e4pv.people_id) as visits,
e4pv.actual_date,
CASE
--cities mapped to states
end as State,
CASE
when rcis.program_name in ('')
then rcis.managing_office_name
when rcis.program_name not in ('')
then rcis.profile_name
end as location,
rcis.program_name,
e4pv.event_name
from dbo.rpt_events_4people_view as e4pv
join dbo.rpt_critical_info_script as rcis with (nolock) on
e4pv.people_id = rcis.people_id and
e4pv.site_providing_service = rcis.managing_office_id
where
rcis.program_name not in ('')
and e4pv.event_name in ('A')
)
GROUP BY
count(e4pv.people_id),
rcis.profile_name,
rcis.program_name,
e4pv.event_name
您需要逐字逐句地將select語句中的所有非聚合表達式重複一遍。一些RBBMS允許在第 – cha
條款中使用別名(例如,在你的情況下是'location')我不知道其他的,但如果有一些CREATE TABLE語句,它會幫助我回答很多問題,在這個問題中有一些例子'INSERT'語句。然後,我可以把它扔到本地安裝或小提琴中,並嘗試一些我的想法來查詢。例如,我不知道「rpt_critical_info_script」的模式是什麼樣的。我可以嘗試猜測創建所有這些表,但我可以犯錯誤和不正確的假設,以使其全部工作。我認爲這在回答者中問得很多。如果你能簡化示例模式,那更好。 –
在sql-fiddle中構建模式的任何機會? – maSTAShuFu