2017-06-26 67 views
0

我有一個查詢它返回一個標誌wheter今年誰,我和公司的合同客戶是新的或返回:如何聚合,使兩個領域之間的比率從CTE

WITH Resultset AS( 
    SELECT 
     Cnt = COUNT(*) 
     ,KliRC --personal identification number 
    FROM dbo.Smlouvy 
    WHERE VyplacenaCastka > 0 
    GROUP BY KliRC 
) 
    SELECT 
     s.KliRC 
     ,CASE WHEN Cnt > 1 THEN 1 ELSE 0 END AS Novy --new client 
     ,CASE WHEN Cnt = 1 THEN 1 ELSE 0 END AS Stavajici --existing client 
    FROM Resultset JOIN dbo.Smlouvy s ON s.KliRC = resultset.KliRC 
    WHERE (YEAR(DatumZadosti) = YEAR(GETDATE())) AND (s.KliRC NOT LIKE '%x') 

現在,我需要彙總所有新客戶和現有客戶,並在他們之間進行比較。 任何想法?提前致謝。

+0

讓你的主查詢另一個CTE。 –

回答

0

我想這你想要做什麼:

WITH Resultset AS ( 
     SELECT COUNT(*) as cnt, 
      KliRC --personal identification number, 
      (CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END) AS Novy --new client 
      (CASE WHEN COUNT(*) = 1 THEN 1 ELSE 0 END) AS Stavajici 
     FROM dbo.Smlouvy 
     WHERE VyplacenaCastka > 0 
     GROUP BY KliRC 
) 
SELECT SUM(Novy)/SUM(Stavajici) 
FROM Resultset r JOIN 
    dbo.Smlouvy s 
    ON s.KliRC = r.KliRC 
WHERE YEAR(DatumZadosti) = YEAR(GETDATE()) AND 
     s.KliRC NOT LIKE '%x'; 
1

您的查詢可以簡化爲

SELECT SUM(Novy)*1.0/SUM(Stavajici) 
FROM (
SELECT KliRC 
,CASE WHEN COUNT(*) OVER(PARTITION BY KliRC) > 1 THEN 1 ELSE 0 END AS Novy --new client 
,CASE WHEN COUNT(*) OVER(PARTITION BY KliRC) = 1 THEN 1 ELSE 0 END AS Stavajici --existing client 
FROM dbo.Smlouvy 
WHERE YEAR(DatumZadosti) = YEAR(GETDATE()) AND KliRC NOT LIKE '%x' 
) T 
+0

不是PARTITION BY需要太多計算資源嗎? –

+0

根據執行計劃,它的成本是其他解決方案的4倍。然而,那麼50%的新客戶數量是不正確的。 –