简体   繁体   中英

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

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.
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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