Self-Join with missing rows on both sides

前端 未结 2 905
醉酒成梦
醉酒成梦 2021-01-28 04:22

I have a table containing people joining and leaving an organization.

Sample data: Sql Fiddle

| pId |     pName |  Unit | YearIn | Yea         


        
相关标签:
2条回答
  • 2021-01-28 04:53

    I think you want a subquery and aggregation:

    SELECT Year, Unit, SUM(NumIn) as NumIn, SUM(NumOut) as NumOut
    FROM (SELECT YearIn AS Year, Unit, COUNT(pId) AS NumIn, NULL AS NumOut
          FROM People
          WHERE YearIn >= 2013
          GROUP BY YearIn, Unit
          UNION ALL
          SELECT YearOut AS Year, Unit, NULL AS NumIn, COUNT(pId) AS NumOut
          FROM People
          WHERE YearOut >= 2013
          GROUP BY YearOut, Unit
         ) yu
    GROUP BY Year, Unit;
    
    0 讨论(0)
  • 2021-01-28 05:15

    This should work:

    WITH Years(y) AS
    (
        SELECT * FROM (VALUES('2013'),('2014'),('2015') ) AS tbl(y)
    )
    ,Units AS 
    (
        SELECT DISTINCT Unit FROM People
    )
    SELECT *
    FROM Years CROSS JOIN Units
    CROSS APPLY(SELECT (SELECT COUNT(*) FROM People AS inP WHERE inP.Unit=Units.Unit AND Years.y=inP.YearIn) AS NumIn
                      ,(SELECT COUNT(*) FROM People AS outP WHERE outP.Unit=units.Unit AND Years.y=outP.YearOut ) As NumOut
    ) AS Counts
    ORDER BY Years.y,Unit
    
    0 讨论(0)
提交回复
热议问题