【发布时间】:2017-03-08 23:19:46
【问题描述】:
这里是论坛的新手。我的问题是如何计算一列的数量并根据案例陈述呈现它?我搜索了论坛并找到了与获取计数、总和和聚合相关的答案,但没有找到与案例陈述的附加条件相关的任何问题。以下是我当前的代码。该代码可以正常工作,但无法按需要返回信息。
例如,假设在特定程序中的 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
感谢您的帮助
更新的语法
我已经更新了语法,建议使用子查询并将 case 语句按部分添加到分组中,但仍然没有得到结果。该代码导致错误,例如组附近的语法不正确等。
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 语句到 group 的所有非聚合表达式。一些 RBBMS 允许在 group by 子句中使用别名(如您的情况下的
location) -
我不知道其他人,但如果这个问题中有一些
CREATE TABLE语句和一些示例INSERT语句,这将有助于我回答这个问题。然后我可以将它放入本地安装或小提琴中,并实际尝试我的一些查询想法。例如,我不知道rpt_critical_info_script的架构是什么样的。我可以尝试猜测创建所有这些表,但我可能会犯错误和不正确的假设以使其全部正常工作。在我看来,这对回答者提出了很多要求。如果您可以简化示例架构,那就更好了。 -
是否有机会在 sql-fiddle 中构建您的架构?
-
@cha 谢谢,我早上试试;
-
@JeremyPridemore 因为这是我的第一篇文章,我会确保下次提供示例数据。然而,出于这个问题的目的,表格本身并不重要。为简化起见,我想计算对办公室的总访问次数。每次访问都在访问表中连续捕获。这些行有idno office state(case statement) dateofvisit。如何获得按办公室和州显示的总访问次数?
标签: sql count group-by aggregate-functions