【发布时间】:2019-08-11 14:20:58
【问题描述】:
我正在尝试为每列计算多个单独的行。下面是我想要完成的一个示例。
select (select top 1 name
from chap
where chap.chp_id = CHS.chp_id) as Chap,
(select count(*)
from CHS,
chap
where O_TYPE = 'PRESIDENT'
and chs.chp_id = chap.chp_id) as Presidents,
(select count(*)
from CHS
where O_TYPE = 'VICEPRESIDENT') as VicePresidents,
(select count(*)
from CHS
where OFFICER_TYPE = 'CORRSECRETARY') as CorrespondinSecretaries,
(select count(*)
from CHS
where O_TYPE = 'RECORDINGSECRETARY') as RecordingSecretaries,
(select count(*)
from CHS
where O_TYPE = 'TREASURER') as Treasurers,
(select count(*)
from CHS
where O_TYPE = 'ADVISOR'
and ADV_CODE = 'B') as ChiefAdvisors,
(select count(*)
from CHS
where O_TYPE = 'ADVISOR'
and ADV_CODE <> 'B') as ChiefAdvisors
from CHS
where O_TYPE in ('PRESIDENT', 'VICEPRESIDENT', 'CORRSECRETARY', 'RECORDINGSECRETARY', 'TREASURER', 'ADVISOR')
and Term_expire >= DateAdd(Day,DateDiff(Day,0,GetDate()),0)
and Term_Begin <= DateAdd(Day,DateDiff(Day,0,GetDate()),0)
and CHS.CHP_ID in (Select chp_id
from chrs
where active = 'Y')
Group by chs.CHP_ID
当我运行它时,它会将每一行的所有记录汇总在一起,而不仅仅是该章的记录。有什么建议吗?
输出示例
AL A 247 264 247 250 246 235 739
AL B 247 264 247 250 246 235 739
AL G 247 264 247 250 246 235 739
AL D 247 264 247 250 246 235 739
AK A 247 264 247 250 246 235 739
AZ A 247 264 247 250 246 235 739
AZ B 247 264 247 250 246 235 739
AZ G 247 264 247 250 246 235 739
我真正想要的是
AL A 1 1 1 4 8 9 16
AL B 1 1 5 7 8 9 21
【问题讨论】:
-
你需要条件聚合,其中
COUNT被SUM(CASE WHEN ... THEN 1 ELSE 0)模拟 -
“为每列计算多个单独的行”不清楚。使用足够多的单词、句子和对部分示例的引用来清楚完整地表达你的意思。说得足够多,有人可以离开并带着解决方案回来。请在代码问题中给出minimal reproducible example--cut & paste & runnable code 加上所需的输出加上清晰的规范和解释。最小意味着将最少的问题代码添加到最少的工作代码中。因此,给出你所展示的最少代码,并在你出错的第一个地方提供最少的代码。 (调试基础。)
标签: sql sql-server join select