我有以下表,我需要總結T-SQL計數問題
ID A B C D E F G
----------------------------------
1-100 1 2 1 1 1 1 1
1-201 1 2 1 2 2 2 2
1-322 1 1 1 1 2 2 1
2-155 1 1 2 1 1 2 2
2-167 2 1 2 1 2 1 2
2-389 2 2 1 2 1 1 2
2-423 1 2 2 2 1 1 1
3-10 2 1 1 1 2 2 2
3-222 1 1 1 1 2 2 1
3-397 2 1 1 2 2 1 1
在上表中,值1被編碼爲S 2時編碼爲R.另外,ID是代碼爲XX,YY或XX,其中 - 之前的數字代表XX,YY或XX。
我想有總結是這樣的
XX YY ZZ
------------------------------------------
A S 3 100% 2 50% 1 33%
R 0 0% 2 50% 2 66%
B S 2 66% 2 50% 3 100%
R 1 33% 2 50% 0 0%
C S 3 100% 3 75% 3 100%
R 0 0% 1 25% 0 0%
D S 2 66% 2 50% 2 66%
R 1 33% 2 50% 1 33%
E S 1 33% 3 75% 0 0%
R 2 66% 1 25% 3 100%
F S 1 33% 3 75% 2 66%
R 2 66% 1 25% 1 33%
G S 2 66% 1 25% 1 33%
R 1 33% 3 75% 2 66%
所以我需要旋轉表,算上1/2和創建百分比。
這已經讓我很困惑,我已經下降了如何做到這一點的幾個死角(更不用說如何做到這一點優雅)
提前感謝!
隨着馬丁的幫助,我永遠如此接近。我的數據當然比我給出的例子稍微低一點,所以我仍然有困難。我譴責的數據,以及把我想要的正確的編碼 - 是的編碼是真正愚蠢的,我無法控制他們:)
我已經擴展馬丁SQL鏈接到我的數據,但有兩個剩下的問題。 Thing Column中的行順序不是我想要的。
當我嘗試下面的代碼時,我得到一個「必須聲明標量變量@order」 - 它不喜歡加入我的臨時表myOrder。
DECLARE @myOrder TABLE (rug varchar(3), rugOrder int)
INSERT @myOrder
SELECT 'INH', 1 UNION ALL
SELECT 'RIF', 2 UNION ALL
SELECT 'KM', 3 UNION ALL
SELECT 'AK', 4 UNION ALL
SELECT 'CM', 5 UNION ALL
SELECT 'MOX', 6 UNION ALL
SELECT 'OFX', 7;
WITH YourData(ID, INH, RIF, KM, AK, CM, MOX, OFX) As
(SELECT Sample_ID, INH, RIF, KM, AK, CM, MOX, OFX
FROM dbo.[GCT_Rug] WHERE Sample_ID NOT LIKE '99%')
, Unpivoted AS
(
SELECT S_R_Flag,
Thing,
Site =
CASE
WHEN LEFT(ID,1) = 1 THEN 1
WHEN LEFT(ID,1) = 6 THEN 1
WHEN LEFT(ID,1) = 8 THEN 2
WHEN LEFT(ID,1) = 9 THEN 3 END
FROM YourData
UNPIVOT
(S_R_Flag FOR Thing IN (INH, RIF, KM, AK, CM, MOX, OFX)
)AS unpvt)
SELECT Thing
,SRFLAG =
CASE
WHEN S_R_Flag = 1 THEN 'S'
WHEN S_R_Flag = 2 THEN 'R'
END
,[1] AS IND
,round(CAST([1] AS FLOAT)/NULLIF(SUM([1]) OVER (PARTITION BY Thing),0)*100,1) AS 'Ind Percent'
,[2] AS MD
,round(CAST([2] AS FLOAT)/NULLIF(SUM([2]) OVER (PARTITION BY Thing),0)*100,1) AS 'MD Percent'
,[3] AS 'SA'
,round(CAST([3] AS FLOAT)/NULLIF(SUM([3]) OVER (PARTITION BY Thing),0)*100,1) AS 'SA Percent'
FROM Unpivoted
INNER JOIN @myOrder
ON Unpivoted.Thing= @myOrder.rug
PIVOT (COUNT (Site) FOR Site IN ([1], [2], [3])) AS pvt
ORDER BY rugOrder,
SRFLAG;
錯誤「必須聲明標量變量@myOrder」意味着什麼,爲什麼我不能加入它?
再次感謝你們(尤其是馬丁)真棒!
你可以添加你有什麼到目前爲止您的查詢的結果? –
到目前爲止,我一直在沿着這條路線SUM(CASE當A = 1則1 ELSE 0 END)作爲,SUM(CASE當A = 2則1 ELSE 0 END)作爲AB – user918967
發佈完整的查詢將會有幫助。 – Sorpigal