如何在连接表的分组数据中使用子查询对两列进行求和

时间:2017-04-01 13:30:43

标签: sql-server database tsql

我有一个问题:

SELECT COUNT(*) as Avalied
FROM PY_LeaveTransactionMasterTAB as lm
JOIN PY_LeaveTransactionSubsidaryTAB as ls 
ON lm.LV_TransMasterId = ls.LV_TransMasterId
WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by lm.Status

上述查询返回:

Availed
-------
   3

和另一个问题:

SELECT PY_Leave + CY_Leave as Openning 
FROM PY_LeaveOpeningTAB 
WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'

此查询返回:

Openning
--------
   25
   23
   30

我想结合以上两个查询来获得以下结果:

Openning   Availed
--------   --------
   25         3
   23         0
   30         0

如何达到上述效果?谢谢:))

3 个答案:

答案 0 :(得分:0)

对我来说,你想要一行“3”而其他行想要“0”是没有意义的。你可以这样做:

SELECT (PY_Leave + CY_Leave) as Openning,
       (CASE WHEN PY_Leave + CY_Leave = 25 THEN x.Avalied ELSE 0 END) as Avalied
FROM PY_LeaveOpeningTAB lo CROSS JOIN
     (SELECT COUNT(*) as Avalied
      FROM PY_LeaveTransactionMasterTAB lm JOIN
           PY_LeaveTransactionSubsidaryTAB as ls 
           ON lm.LV_TransMasterId = ls.LV_TransMasterId
      WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND
            lm.Status ='Approved'
     ) x
WHERE lo.SystemCode = 'faheem123' and lo.EmployeeCode = '0014';

正如我所说,删除CASE并将“3”放在所有三个“匹配”行上对我来说更有意义。

答案 1 :(得分:0)

您可以尝试使用CTE

 WITH CTE_preselect AS (
 SELECT EmployeeCode,PY_Leave + CY_Leave as Openning 
 FROM PY_LeaveOpeningTAB 
 WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
 )

 SELECT Openning,COUNT(*) as Avalied
 FROM PY_LeaveTransactionMasterTAB as lm
 JOIN PY_LeaveTransactionSubsidaryTAB as ls 
 ON lm.LV_TransMasterId = ls.LV_TransMasterId
 JOIN CTE_preselect ON lm.EmployeeCode = CTE_preselect.EmployeeCode
 WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND 
 lm.Status ='Approved'
 Group by Openning,lm.Status

答案 2 :(得分:0)

假设已失败"属于"到第一行

Select A.Opening
      ,Availed = case when A.RN=1 then B.Availed else 0 end)
 From (
        SELECT PY_Leave + CY_Leave as Openning 
              ,RN = Row_Number() over (Order by (Select NULL))
         FROM PY_LeaveOpeningTAB 
         WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
      ) A
 Cross Join (
                SELECT COUNT(*) as Avalied
                FROM PY_LeaveTransactionMasterTAB as lm
                JOIN PY_LeaveTransactionSubsidaryTAB as ls 
                ON lm.LV_TransMasterId = ls.LV_TransMasterId
                WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
                Group by lm.Status
            ) B