MSSQL-组合两个SELECTS,包括JOIN和COUNT

时间:2017-03-16 15:10:03

标签: sql-server select join count

我是Stackoverflow的新手。希望我的问题不是愚蠢的!

我有两个SELECTS,我必须结合起来。我已经尝试了UNION和另一个JOIN,但它没有成功。

SELECT 
Person.Name, Saldo1.Duration AS Holiday, Saldo2.Duraten AS Hours
FROM Person_Saldo AS Saldo1 
JOIN Person_Saldo AS Saldo2 ON Saldo1.Person_ID = Saldo2.Person_ID
JOIN Person ON Saldo1.Person_ID = Person.ID
WHERE Person.Group_ID= '1' AND Person.Active = 'true' AND Saldo1.Year = '2017' AND Saldo1.Timekonto = '4' AND Saldo2.Timekonto='52'  

和第二个SELECT:

SELECT
Person_ID, Count([Date]) AS Amount 
FROM Booking Where Timekonto = 54 AND Booking_OK = 1 Group by Person_ID

第一个SELECT显示如下:

Name Holiday Hours A 20 50 B 12 -30

第二件事是这样的:

ID Amount A 4 B 3

我尝试的是什么:
 Name Holiday Hours Amount A 20 50 4 B 12 -30 3

谢谢,希望你能帮助我。

2 个答案:

答案 0 :(得分:1)

一种方法是将聚合查询加入主查询,如下所示:

3

如果您仍希望在结果中返回的人SELECT Person.Name , Saldo1.Duration AS Holiday , Saldo2.Duraten AS Hours , b.Amount FROM Person_Saldo AS Saldo1 JOIN Person_Saldo AS Saldo2 ON Saldo1.Person_ID = Saldo2.Person_ID JOIN Person ON Saldo1.Person_ID = Person.ID left join ( SELECT Person_ID, Count([Date]) AS Amount FROM Booking Where Timekonto = 54 AND Booking_OK = 1 Group by Person_ID ) b on b.Person_ID = Saldo1 WHERE Person.Group_ID= '1' AND Person.Active = 'true' AND Saldo1.Year = '2017' AND Saldo1.Timekonto = '4' AND Saldo2.Timekonto='52' 可能left join,则可能需要使用inner join而不是count ()。< / p>

您还可以使用outer apply()cross apply()来获得相同的结果。

null

答案 1 :(得分:0)

您可以使用“With”以使其更清晰。您可以在两个表之间使用左外连接。

   WITH Table2 as (
   SELECT
   Person_ID, Count([Date]) AS Amount 
   FROM Booking Where Timekonto = 54 AND Booking_OK = 1 Group by Person_ID)


Select Name, Holiday, Hours, Amount
from (SELECT 
    Person.Name, Saldo1.Duration AS Holiday, Saldo2.Duraten AS Hours
    FROM Person_Saldo AS Saldo1 
    JOIN Person_Saldo AS Saldo2 ON Saldo1.Person_ID = Saldo2.Person_ID
    JOIN Person ON Saldo1.Person_ID = Person.ID
    WHERE Person.Group_ID= '1' AND Person.Active = 'true' 
    AND Saldo1.Year = '2017' AND Saldo1.Timekonto = '4'
    AND Saldo2.Timekonto='52') Table1 LEFT OUTER JOIN
    Table2 on Table2.Person_ID=Table1.Name