不确定如果没有某种类型的Dynamic SQL或Pivot(我想远离)是否可能...我有一个报告,其中显示了各种类型/各种状态组合的总数...这些类型和状态始终保持不变并显示在报表上,因此对于特定组合不返回任何数据将产生零。截至目前,只有三种caseType(植被,BOA和分区)和8 statusType(见下文)。
我首先使用临时表设置报告的框架。我一直小心地将临时表的列命名为与第二个表“ #ReportData”中的“ statusType”列相同。有没有一种方法可以根据我第二张表中“ statusType”列的值来更新“ #FormattedData”中的不同列?
创建格式表(用于报告):
CREATE TABLE #FormattedReport (
caseType VARCHAR(50)
, underInvestigation INT NOT NULL DEFAULT 0
, closed INT NOT NULL DEFAULT 0
, closedDPW INT NOT NULL DEFAULT 0
, unsubtantiated INT NOT NULL DEFAULT 0
, currentlyMonitored INT NOT NULL DEFAULT 0
, judicialProceedings INT NOT NULL DEFAULT 0
, pendingCourtAction INT NOT NULL DEFAULT 0
, other INT NOT NULL DEFAULT 0
)
INSERT INTO #FormattedReport (caseType) VALUES ('Vegetation')
INSERT INTO #FormattedReport (caseType) VALUES ('BOA')
INSERT INTO #FormattedReport (caseType) VALUES ('Zoning')
创建数据表(以填充#FormattedReport):
SELECT B.Name AS caseType, C.Name AS StatusType, COUNT(*) AS Amount
INTO #ReportData
FROM table1 A
INNER JOIN table2 B ...
INNER JOIN table3 C ...
WHERE ...
GROUP BY B.Name, C.Name
当前更新语句(当前在#FormattedReport中每列将更新1次):
UPDATE A SET underInvestigation = Amount FROM #ReportData B
INNER JOIN #FormattedReport A ON B.CaseType LIKE CONCAT('%', A.caseType, '%')
WHERE B.StatusType = 'Under Investigation'
UPDATE A SET closed = Amount FROM #ReportData B
INNER JOIN #FormattedReport A ON B.CaseType LIKE CONCAT('%', A.caseType, '%')
WHERE B.StatusType = 'Closed'
...
请求的更新语句:当“#ReportData.statusType”与“ #FormattedData”列的名称相同时,希望有一条更新语句知道要更新的列。对于我的“其他”列,我将使用NOT IN手动进行。
答案 0 :(得分:3)
假设我理解这个问题,我认为您可以为此使用条件聚合:
;WITH CTE AS
(
SELECT CaseType
,SUM(CASE WHEN StatusType = 'Under Investigation' THEN Amount ELSE 0 END) As underInvestigation
,SUM(CASE WHEN StatusType = 'Closed' THEN Amount ELSE 0 END) As closed
-- ... More of the same
FROM #ReportData
GROUP BY CaseType
)
UPDATE A
SET underInvestigation = B.underInvestigation
,closed = b.closed
-- more of the same
FROM #FormattedReport A
INNER JOIN CTE B
ON B.CaseType LIKE CONCAT('%', A.caseType, '%')