组合3个SQL查询

时间:2017-02-06 15:18:21

标签: sql sql-server

我有3个SQL查询。我需要的输出是角色,开斋节,目标,coacheename,总豁免和总教练。但是我很难将3个查询组合在一起。

我的第一个问题:

SELECT
    coachEID, role, coacheeEID, 
    IIF(COUNT(status) > IIF(a.role = 'SME', 1, 2), IIF(a.role = 'SME', 1, 2), COUNT(status)) AS total 
FROM 
    coaching z
JOIN
    tbl_calendar v ON z.starttime BETWEEN v.datestart AND v.dateend
JOIN
    roster a ON z.coachEID = a.EID
WHERE 
    z.status = 'completed'
    AND v.month = '1' AND v.year = '2017'
    AND a.location = 'manila'
GROUP BY
    coacheid, coacheeeid, status, role

第二个查询是:

SELECT 
    y.role, y.eid, IIF(y.sme = y.eid, 1, 2) AS target
FROM 
    roster y
JOIN 
    roster x ON (x.supervisor = y.eid OR x.sme = y.eid OR x.teamlead = y.eid) 
             AND x.eid <> y.eid 
             AND x.employstatus = 'Active'
WHERE 
    y.employstatus = 'active' 
    AND y.Role IN ('SME', 'Junior Team Lead','Team Lead', 'Shift Lead', 
                   'Operations Lead', 'Quality Lead', 'Policy Lead') 
    AND y.location = 'manila'

第三个查询是:

SELECT 
    x.coachEID, x.CoacheeEID, SUM(x.NoOfApproved) AS exempt, 
    x.month, x.year 
FROM
    exemptitems x
LEFT JOIN
    roster y ON y.eid = x.Coacheid
WHERE
    x.month = '1' AND x.year = '2017'
    AND y.eid = x.coacheid 
    AND x.NoOfApproved IS NOT NULL
GROUP BY 
    x.CoachEID, x.CoacheeEID, x.Month, x.year

Result of queries

2 个答案:

答案 0 :(得分:1)

我应该有以下几点:

with CTE1 as (
    select coachEID,role,coacheeEID, IIF(count(status)>IIF(a.role='SME',1,2),IIF(a.role='SME',1,2),count(status))
        as total from coaching z
        join tbl_calendar v
        ON z.starttime BETWEEN v.datestart and v.dateend
        join roster a on z.coachEID=a.EID
        where z.status='completed'
        and v.month='1' and v.year='2017'
        and a.location='manila'
        group by coacheid, coacheeeid, status, role
), CTE2 as (
    SELECT y.role, y.eid, IIF(y.sme=y.eid,1,2) AS target
        FROM roster y
        JOIN roster x ON (x.supervisor = y.eid OR x.sme = y.eid OR x.teamlead = y.eid) AND x.eid <> y.eid 
        AND x.employstatus = 'Active'
        WHERE y.employstatus = 'active' 
        AND y.Role IN ('SME', 'Junior Team Lead','Team Lead', 'Shift Lead', 'Operations Lead', 'Quality Lead', 'Policy Lead') 
        AND y.location = 'manila'
), CTE3 as (
        SELECT x.coachEID,x.CoacheeEID,  sum (x.NoOfApproved) as exempt, x.month, x.year from exemptitems x
        left join roster y on y.eid=x.Coacheid
        where x.month='1' and x.year='2017'
        and y.eid=x.coacheid and x.NoOfApproved is not NULL
        group by x.CoachEID, x.CoacheeEID, x.Month, x.year
)
select c1.role, c2.eid, c2.target, c1.total -- insert the rest of the fields you want to be included
from CTE1 c1
join CTE2 c2 on c1.coachEID = c2.eid
join CTE3 c3 on c1.coachEID = c3.coachEID

请在脚本底部添加必要的列,因为我无法清楚地理解您的请求。

答案 1 :(得分:0)

如果列数相同,则可以合并每个查询。如果需要,可以使用文字填充其他查询以在每个语句上提供相同的结构,然后在每个语句之间放置一个UNION。