我有这个问题:
select qos.orgname, qos.org, qos.suborg, qos.Archive, qos.location, count(c.coe) AS DEPT, c.coe AS DEP,
qos.siteid, qos.admin as sitelead,
CASE When qos.Archive = 0 THEN 'Active'
when qos.Archive is null THEN '-'
ELSE 'Archived'
END AS STATUS
from qryOrgsite qos WITH (NOLOCK)
LEFT JOIN ltbcoe c WITH (NOLOCK) on qos.orgname = c.orgname and qos.location= c.location
group by qos.orgname, qos.location, qos.org, qos.suborg, qos.Archive, c.coe,
qos.siteid, qos.ADMIN
这给了我一些记录如下:
所以我想要#34; Dept"活跃的列。我的意思是它应该只返回一行,组织B和部门为7 ....例如,这里的部门列应为7。
这意味着我想要计算c.coe列。
答案 0 :(得分:2)
这里的问题是你的GROUP BY太包容了。查询要求的是计数,但结果必须是GROUP BY中所有列的唯一。如果你只需要每个orgname计数,你需要做
SELECT qos.orgname, COUNT(*)
FROM qryOrgsite qos
GROUP BY qos.orgname
这基本上表示你想要通过orgname统计所有行。您添加到组中的每个列都会为您的COUNT创建唯一的组合。例如,如果按orgname和location分组,它将为这两列的每个组合提供累计计数。根据您在上面显示的数据,这将导致
OrganizationB Demo-Fixe 1
OrganizationB GE CapitalP 3
OrganizationB Hadasa Plant 1
OrganizationB Mostoles Plant 1
答案 1 :(得分:1)
您可以将查询包装在另一个中:
select orgname, count(*)
from (
select qos.orgname, qos.org, qos.suborg, qos.Archive, qos.location, count(c.coe) AS DEPT, c.coe AS DEP,
qos.siteid, qos.admin as sitelead,
CASE When qos.Archive = 0 THEN 'Active'
when qos.Archive is null THEN '-'
ELSE 'Archived'
END AS STATUS
from qryOrgsite qos WITH (NOLOCK)
LEFT JOIN ltbcoe c WITH (NOLOCK) on qos.orgname = c.orgname and qos.location= c.location
group by qos.orgname, qos.location, qos.org, qos.suborg, qos.Archive, c.coe,
qos.siteid, qos.ADMIN) t1
where t1.orgname = 'Organization B' and t1.STATUS = 'Active'
group by t1.orgname
答案 2 :(得分:0)