如何在CTE中聚合并建立两个字段之间的比率

时间:2017-06-26 11:24:01

标签: sql sql-server

我有一个查询返回一个标志,而今年与我公司签订合同的客户是新的还是返回:

    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')

现在,我需要聚合所有新客户端和现有客户端,并在它们之间建立比率。 有任何想法吗?提前谢谢。

2 个答案:

答案 0 :(得分: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 :(得分:0)

您的查询可以简化为

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