我正在尝试创建一个分子(num)和分母(den)列,我稍后会用它来创建一个度量值。在我的分子专栏中,我需要有一个我的分母列没有的标准。当我将where子句添加到我的子查询时,我收到以下错误。我不想将INRInRange添加到我的Group By子句中。
列'dbo.PersonDetailB.INRInRange'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。“
SELECT
dbo.PersonDetailSpecialty.PracticeAbbrevName,
(SELECT COUNT(DISTINCT dbo.Problem.PID) WHERE PersonDetailB.INRInRange='True') AS num,
COUNT(DISTINCT dbo.Problem.PID) AS den
FROM
dbo.PersonDetailB
RIGHT OUTER JOIN
dbo.PersonDetailSpecialty ON dbo.PersonDetailB.PID = dbo.PersonDetailSpecialty.PID
LEFT OUTER JOIN
dbo.Problem ON dbo.PersonDetailSpecialty.PID = dbo.Problem.PID
GROUP BY
practiceabbrevname
答案 0 :(得分:1)
创建一个子查询,该查询计算PersonDetailB.INRInRange
并使用原始查询LEFT OUTER JOIN。
SELECT Main.PracticeAbbrevName, InRange.Num AS num, Main.den
FROM
(SELECT
dbo.PersonDetailSpecialty.PracticeAbbrevName,
COUNT(DISTINCT dbo.Problem.PID) AS den
FROM
dbo.PersonDetailB
RIGHT OUTER JOIN
dbo.PersonDetailSpecialty ON dbo.PersonDetailB.PID = dbo.PersonDetailSpecialty.PID
LEFT OUTER JOIN
dbo.Problem ON dbo.PersonDetailSpecialty.PID = dbo.Problem.PID
GROUP BY
practiceabbrevname) Main
LEFT OUTER JOIN
(SELECT practiceabbrevname, COUNT(DISTINCT dbo.Problem.PID) Num WHERE PersonDetailB.INRInRange='True' GROUP BY practiceabbrevname) InRange ON Main.practiceabbrevname = InRange.practiceabbrevname
答案 1 :(得分:0)
这句话的问题:
SELECT dbo.PersonDetailSpecialty.PracticeAbbrevName,
(SELECT COUNT(DISTINCT dbo.Problem.PID) WHERE PersonDetailB.INRInRange = 'True') AS num,
COUNT(DISTINCT dbo.Problem.PID) AS den
PersonDetailB.INRInRange1
在每个组中都没有唯一值。它有可能。一种方法是将其添加到GROUP BY
:
GROUP BY practiceabbrevname, PersonDetailB.INRInRange
另一种方法是在子查询中使用聚合函数:
SELECT dbo.PersonDetailSpecialty.PracticeAbbrevName,
(SELECT COUNT(DISTINCT dbo.Problem.PID) WHERE MAX(PersonDetailB.INRInRange) = 'True') AS num,
COUNT(DISTINCT dbo.Problem.PID) AS den
答案 2 :(得分:0)
在子查询中的where条件上将单独的表作为不同的名称加入。
SELECT PersonDetailSpecialty.PracticeAbbrevName,
COUNT(PDTRUE.PID) as num,
COUNT(dbo.Problem.PID) AS den
FROM dbo.PersonDetailSpecialty LEFT OUTER JOIN
dbo.PersonDetailB as PDTRUE ON dbo.PersonDetailSpecialty.PID = PDTRUE.PID and PDTRUE.INRInRange='True' LEFT OUTER JOIN
dbo.PersonDetailB ON dbo.PersonDetailSpecialty.PID = PersonDetailB.PID LEFT OUTER JOIN
dbo.Medicate ON dbo.PersonDetailSpecialty.PID = dbo.Medicate.PID LEFT OUTER JOIN
dbo.Problem ON dbo.PersonDetailSpecialty.PID = dbo.Problem.PID
GROUP BY PersonDetailSpecialty.PracticeAbbrevName
这是FROM部分所需的相关代码
dbo.PersonDetailSpecialty LEFT OUTER JOIN dbo.PersonDetailB as PDTRUE
ON dbo.PersonDetailSpecialty.PID = PDTRUE.PID and PDTRUE.INRInRange='True'
这可以让你添加
COUNT(PDTRUE.PID) as num,
作为整体选择查询的简单部分