我正在使用樞軸將年齡段的年齡範圍分組,並且所有列都沒有按照他們應該填充的方式填充。我將LOS(停留時間)的總和計算在內,並且年齡範圍總計應等於TotalLOS,但目前情況並非如此。請幫忙!!使用樞軸用於年齡範圍問題
這是T-SQL查詢:
SELECT *
FROM
(
SELECT [Hosp Name],
Cnty,
Max([Hosp County]) as [FirstOfHosp_County],
Max(Hosp) as UID,
LOS,
Age,
Sum(LOS) as TotalLOS,
CASE
WHEN Age <=17 THEN '0-17'
WHEN Age Between 18 and 64 THEN '18-64'
WHEN Age >=65 THEN '65 Up'
ELSE NULL
END AS AGERANGE
FROM [S1: Basic Source Query]
GROUP BY [Hosp Name], Cnty, Age, [Hosp County], Hosp, LOS
) AS S
PIVOT
(
Sum(S.LOS)
for S.AGERANGE
in ([0-17], [18-64],[65 Up])
) as pvt
我從Access轉換此查詢。這是訪問查詢:
TRANSFORM Sum([S1: Basic Source Query].LOS) AS Days
SELECT [S1: Basic Source Query].[Hosp Name],
[S1: Basic Source Query].Cnty,
FirstOfHosp County: First([S1: Basic Source Query].[Hosp County])
UID: First([S1: Basic Source Query].Hosp)
Total: Sum([S1: Basic Source Query].LOS)
FROM [S1: Basic Source Query]
GROUP BY [S1: Basic Source Query].[Hosp Name],
[S1: Basic Source Query].Cnty
PIVOT Switch([Age] Between 0 And 17,"0-17",[Age] Between 18 And 64,"18-64",[Age]>=65,"65 Up");
這是一個示例訪問數據之前的數據透視。它沒有所有的列。
Hosp Hosp Name LOS Age
HOSP301 Apple Hospital 16 92
HOSP301 Apple Hospital 5 34
HOSP301 Apple Hospital 14 85
HOSP301 Apple Hospital 7 21
HOSP301 Apple Hospital 4 79
HOSP301 Apple Hospital 2 26
HOSP301 Apple Hospital 2 19
而且一旦進入查詢運行時,它把它變成這樣:
UID Hosp Name TotalLOS 0-17 18-64 65 Up
HOSP301 Apple Hospital 130 117 13
HOSP301 Apple Hospital 5 5
HOSP301 Apple Hospital 722 60 455 207
HOSP301 Apple Hospital 23 17 6
HOSP301 Apple Hospital 15 15
HOSP301 Apple Hospital 6 6
HOSP301 Apple Hospital 3 3
HOSP301 Apple Hospital 32 1 31
這是不正確的SQL結果我得到。正如你看到的範圍內的數字並不總是匹配什麼在TotalLOS列
UID Hosp Name Cnty FirstOfHosp_County Age TotalLOS 0-17 18-64 65 Up
HOSP301 Apple Hospital Apple Apple 57 24 4
HOSP301 Apple Hospital Apple Apple 68 13 13
HOSP301 Apple Hospital Apple Apple 69 12 4
HOSP301 Apple Hospital Apple Apple 71 10 10
HOSP301 Apple Hospital Apple Apple 73 8 2
HOSP301 Apple Hospital Apple Apple 74 7 7
HOSP301 Apple Hospital Apple Apple 75 6 6
HOSP301 Apple Hospital Apple Apple 79 34 17
HOSP301 Apple Hospital Bacon Apple 63 2 2
HOSP301 Apple Hospital Bagwin Apple 68 16 16
所以:根據年齡範圍的數字應該匹配TotalLOS列。我相信我沒有從Access正確轉換它到T-SQL。
當[聚合](https://msdn.microsoft.com/en-GB/library/ms173454.aspx)在[Hosp County],Hosp,LOS'組中包含這些字段沒有意義在select子句中。你能否提供返回不正確結果的樣本數據?沒有它很難處理你的查詢。 –