declare @Temp table
(CaseID int,
PrimaryClientID int,
Category int
)
INSERT INTO @Temp
SELECT
[casCaseID],
[casPrimaryClientID],
CASE
WHEN (SELECT COUNT(evecaseid) FROM MPS3.dbo.Events where evecaseid=cascaseid and eveworkflowid=960)>0 THEN 1
WHEN (SELECT COUNT(CTC2.ctcCaseID)FROM MPS3.dbo.ClientToCase CTC1 INNER JOIN MPS3.dbo.ClientToCase CTC2 ON CTC1.ctcClientID=CTC2.ctcClientID INNER JOIN MPS3.dbo.Events E2 ON CTC2.ctcCaseID=E2.eveCaseID AND E2.eveWorkflowID=960 WHERE CTC1.ctcCaseID=casCaseID AND CTC2.ctcCaseID < CTC1.ctcCaseID)>0 THEN 2
ELSE 3
END AS [FPCategory]
FROM [MPS3].[dbo].[Cases]
WHERE
casRecontactDate BETWEEN '2012-01-01' AND '2012-01-01'
AND
casCaseType = 'm'
ORDER BY FPCategory
SELECT
Category AS [CategoryType],
COUNT(Category) AS [CategoryTotal]
CASE
WHEN [Category] = 0 or [Category] = 0 THEN 0
else ([Category]+0.0)/COUNT[Category])
END AS [Percentage],
FROM
@Temp
GROUP BY
Category
为了简化我的工作,我创建了一个临时表,列出了数据库中的案例。我已经应用了一个案例陈述,然后将这些案例分为3种类型,1,2或3。
在下面的选择声明中,我希望有另一列显示总数中每个类别的百分比。 我的问题是我不能使用早期case语句中的别名“FPCategory”,因为尚未发生在后面的语句中使用的有效列名。
谢谢!
答案 0 :(得分:0)
首先,让我们废除那些讨厌的子查询&amp;将您的查询转换为CTE(未经测试,因为我无法看到您的架构):
WITH EventCounts ( casCaseID, EventCount )
AS ( SELECT evecaseid ,
COUNT(evecaseid)
FROM MPS3.dbo.Events
WHERE eveworkflowid = 960
),
ClientToCaseCounts ( casCaseID, ClientToCaseCount )
AS ( SELECT CTC1.ctcCaseID ,
COUNT(CTC2.ctcCaseID)
FROM MPS3.dbo.ClientToCase CTC1
INNER JOIN MPS3.dbo.ClientToCase CTC2 ON CTC1.ctcClientID = CTC2.ctcClientID
INNER JOIN MPS3.dbo.Events E2 ON CTC2.ctcCaseID = E2.eveCaseID
AND E2.eveWorkflowID = 960
WHERE CTC2.ctcCaseID < CTC1.ctcCaseID
),
BaseData ( [casCaseID], [casPrimaryClientID], [FPCategory] )
AS ( SELECT [casCaseID] ,
[casPrimaryClientID] ,
CASE WHEN EventCounts.EventCount > 0 THEN 1
WHEN ClientToCaseCounts.ClientToCaseCount > 0 THEN 2
ELSE 3
END AS [FPCategory]
FROM [MPS3].[dbo].[Cases] C
LEFT OUTER JOIN EventCounts ON C.[casCaseID] = EventCounts.casCaseID
LEFT OUTER JOIN ClientToCaseCounts ON C.[casCaseID] = ClientToCaseCounts.casCaseID
WHERE casRecontactDate BETWEEN '2012-01-01'
AND '2012-01-01'
AND casCaseType = 'm'
)
SELECT [FPCategory] ,
COUNT([casCaseID]) AS TotalCases
FROM BaseData
GROUP BY [FPCategory]
现在,我注意到你在上一次查询中对FPCategory进行分组的方式,这意味着你的结果会有多个每个FPCategory的casCaseID?我不是100%肯定你想要的平均值?但现在它是一个CTE,你可以重新加入EventCounts&amp; ClientToCaseCounts到最终查询(递归)。希望这能指出你正确的方向,如果没有,请提供一些示例架构&amp;数据示例&amp;我会相应地调整我的答案。