排名显示所有用户罚款。但是如何显示一个用户的排名?

时间:2018-04-17 18:18:36

标签: sql sql-server

我有这个SQL查询:

SELECT 
    DENSE_RANK() OVER (ORDER BY s.rows DESC) AS Ranks,
    Territory, TM_Name,
    COALESCE(g.rows, 0) AS RXCount, 
    COALESCE(s.rows, 0) AS DelCounts,
    COALESCE(nd.rows, 0) AS NotDeliveredCount,
    COALESCE(trgt.rows, 0) AS Target,
    e.TM_Emp_Id
FROM 
    tblEmployee e
LEFT JOIN
    (SELECT EmpCode, SUM(RxGenerate) AS rows 
     FROM tbl_RX 
     GROUP BY EmpCode) g ON g.EmpCode = e.TM_Emp_Id
LEFT JOIN
    (SELECT EmpCode, SUM(MedToPCount) AS rows 
     FROM tbl_MedicinToPatient 
     WHERE Status = 'Delivered' 
     GROUP BY EmpCode) s ON s.EmpCode = e.TM_Emp_Id
LEFT JOIN
    (SELECT EmpCode, COUNT(*) AS rows 
     FROM tbl_MedicinToPatient 
     WHERE Status != 'Delivered' 
     GROUP BY EmpCode) nd ON nd.EmpCode = e.TM_Emp_Id
LEFT JOIN
    (SELECT 
         EmpCode, CurrentTarget AS rows,   
         CreatedDate, RankOrder, T.PreviousTarget 
     FROM
         (SELECT
              EmpCode, CurrentTarget, CreatedDate,PreviousTarget,
              RANK() OVER (PARTITION BY EmpCode ORDER BY CreatedDate DESC) RankOrder
          FROM
              tbl_Target) T 
     WHERE 
         RankOrder = 1) trgt ON trgt.EmpCode = e.TM_Emp_Id

返回所需的输出。这是为每个用户计算完美排名。但是当我在查询结尾添加where条件时,例如:

e.TM_Emp_Id = 101

它显示等级1.对于每个用户,我得到相同的结果(即等级1)。 但我想显示原始排名。我该如何实现这一目标?提前谢谢!

2 个答案:

答案 0 :(得分:4)

您至少有3个简单的选择。

  1. 将整个查询封装到子查询中,使其看起来像

    select * 
    from (current code) 
    where TM_Emp_ID = 101
    
  2. 与上述相同,只是将其作为CTE:

    WITH MY_QUERY AS 
    (current code) 
    SELECT * 
    FROM MY_QUERY 
    WHERE TM_EMP_ID = 101
    
  3. 与上述2相同,但使用临时表

答案 1 :(得分:1)

您必须对所有用户进行排名才能了解特定用户的排名。因此,请从您的查询中选择:

select *
from ( your query here ) q
where tm_emp_id = 101;