如何根据两个表中的两个不同属性计算排名?

时间:2018-01-14 07:16:34

标签: sql sql-server sql-server-2012

我有两张表tbl_Generatetbl_Statustbl_Generate有两列,一列是TGenerate(只有布尔值1或0),而Emp_Id表是这样的: -

 T_ID |Tgenerate |Emp_ID
 -----|----------|-------
   1  | 0        |101
   2  | 1        |101
   3  | 1        |101
   4  | 0        |102
   5  | 1        |102
   6  | 1        |102
   7  | 1        |102
   8  | 0        |102

我有另一个表tbl_Status它还有两个imp列状态(状态有四个固定值'Delivered','Pending','Didn't Call','Refused')和Emp_Id

 status_Id | Status      |Emp_ID
 ----------|-------------|------
    1      | Delivered   |  101
    2      | Didn't Call |  102
    3      | Pending     |  101
    4      | Refused     |  101
    5      | Delivered   |  101
    6      | Refused     |  102
    7      | Delivered   |  102
    8      | Pending     |  102
    9      | Didn't Call |  101
    10     | Pending     |  102

我想根据生成Emp_Id的更多内容的人来计算每个TGenerate的排名(对于tbl_Generate中的ex,已生成总数2和102生成总数3 {{1 }}和Tgenerate具有最高状态的delieverd(对于ex 101,总计2个已交付计数)。

那么如何编写sql查询以根据这两个属性(Emp_IdTGenerate)获得排名。如何获得状态未交付的总计数。 P.S .:我正在使用SQL Server 2012。

2 个答案:

答案 0 :(得分:2)

我想你需要这样的东西

SELECT T.Emp_Id,
       [Rank] = Dense_rank() OVER (ORDER BY Tgenerate_Cnt DESC, Delivered_Cnt DESC)
FROM   (SELECT Emp_ID,
               Tgenerate_Cnt = Count(*)
        FROM   tbl_Generate
        WHERE  Tgenerate = 1
        GROUP  BY Emp_ID) T
       LEFT JOIN (SELECT Emp_ID,
                         Delivered_Cnt = Count(*)
                  FROM   tbl_Status
                  WHERE  Status = 'Delivered'
                  GROUP  BY Emp_ID) S
              ON T.Emp_ID = S.Emp_ID 

答案 1 :(得分:1)

尝试以下查询。

注意 - 由于正在使用INNER JOIN,因此只需要表中存在的Emp_IDSELECT TG.EMP_ID, DENSE_RANK() OVER (ORDER BY TS.COUNT_DEL, TG.COUNT_TG) AS YOUR_RANK FROM (SELECT EMP_ID, SUM(CASE WHEN TGENERATE = 1 THEN 1 ELSE 0 END) AS COUNT_TG FROM TBL_GENERATE GROUP BY EMP_ID) TG INNER JOIN (SELECT EMP_ID, SUM(CASE WHEN STATUS = 'DELIVERED' THEN 1 ELSE 0 END) AS COUNT_DEL FROM TBL_STATUS GROUP BY EMP_ID) TS ON TG.EMP_ID = TS.EMP_ID;

{{1}}