简体   繁体   English

TSQL查询通过连接两个表来获取不同WHERE子句的同一列值的差异

[英]TSQL query to get the Difference of values of same column for different WHERE clause by joining two tables

Below is the sample query which gives the rating by employee and manager from two different tables.下面是示例查询,它给出了来自两个不同表的员工和经理的评级。

SELECT pr.[task_id],
       pr.[user_rating],ts.[title]
FROM [dbo].[rpt_task] ts
      INNER JOIN [dbo].[rpt_review] pr ON ts.[task_id] = pr.[task_id]
WHERE ts.[culture_id] = 1

样本输出

Now, I am trying to draft the query where the result be like现在,我正在尝试起草查询,结果如下

Sample Desired Output - [ variance being(user_rating of 'Manager review' - user_rating of 'self_Review')样本期望输出 - [ 方差为('经理审查'的用户等级 -'self_Review' 的用户等级)

task_id   variance
6095      0

I have tried as我试过

SELECT pr.[task_id],
       ((SELECT pr.[user_rating]
         FROM [dbo].[rpt_task] ts
              INNER JOIN [dbo].[rpt_review] pr ON ts.[task_id] = pr.[task_id]
         WHERE ts.[title] = 'Manager Review') -
        (SELECT pr.[user_rating]
         FROM [dbo].[rpt_task] ts
              INNER JOIN [dbo].[rpt_review] pr ON ts.[task_id] = pr.[task_id]
         WHERE ts.[title] = 'Self Review'))
FROM [dbo].[rpt_task] ts
      INNER JOIN [dbo].[rpt_review] pr ON ts.[task_id] = pr.[task_id]  
WHERE ts.[culture_id] = 1
GROUP BY pr.[task_id]

ASSUMPTION : You didn't provide the table structure of the underlying tables, hence I'm assuming that the rpt_review table doesn't need to be joined twice, as there's one record there, and one record for each reviewer in the rpt_task table.假设:您没有提供底层表的表结构,因此我假设rpt_review表不需要连接两次,因为那里有一条记录,并且rpt_task表中的每个审阅者都有一条记录。
Please correct me if this assumption isn't correct.如果这个假设不正确,请纠正我。

You'll need to self-join the table in order to get both the manager and the self reviews.您需要自行加入表格才能获得经理和自我评论。 I've joined both of them to the rpt_review table and did the math as you were trying to do.我已将它们都加入到rpt_review表中,并按照您的要求进行了数学计算。

Sample Code:示例代码:

SELECT 
     pr.[task_id]
    ,ts_manager.[user_rating] - ts_self.[user_rating] AS Variance
FROM [dbo].[rpt_task] ts_self
INNER JOIN [dbo].[rpt_review] pr ON ts.[task_id] = pr.[task_id]
INNER JOIN [dbo].[rpt_task] ts_manager ON ts_self.culture_id = ts_manager.culture_id
WHERE ts_self.[culture_id] = 1
AND ts_self.[title] = 'Self Review'
AND ts_manager.[title] = 'Manager Review';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM