SQL Server查询无法正常工作

时间:2016-09-14 17:25:08

标签: sql-server

我有如下查询,但结果中未显示ShowRoomNameUnitName。我该如何解决?

SELECT A.ShowRoomId
       , Sum(B.BasicAmount) AS TotalBasic
       , Sum(B.HouseAmount) AS TotalHouseAmount
       , Sum(B.MedicaleAmount) AS TotalMedicaleAmount
       , Sum(B.ConvenceAmount) AS TotalConvenceAmount
       , Sum(B.PhoneBillAmount) AS TotalPhoneBillAmount
       , Sum(B.DirectorRemuneration) AS TotalDirectorRemuneration
       , Sum(B.OthersAmount) AS TotalOthersAmount
FROM   Employees A
       OUTER APPLY (SELECT TOP 1 *
                    FROM   EmployeeBasics B
                    WHERE  ( A.EmployeeID = B.EmployeeID )
                    ORDER  BY B.BasicUpdateDate DESC) AS B
       OUTER APPLY (SELECT ShowRoomId
                           , ShowRoomName
                           , UnitId
                    FROM   dbo.ShowRooms C
                    WHERE  A.ShowRoomId = C.ShowRoomId) AS C
       OUTER APPLY (SELECT UnitId
                           , UnitName
                    FROM   dbo.Units D
                    WHERE  C.UnitId = D.UnitId) AS D
GROUP  BY A.SHowRoomId 

2 个答案:

答案 0 :(得分:0)

  • 在提问时使用更具描述性的标题。查询没有 工作基本上描述了99%的问题。
  • 您的单位名称和 showroomname不会出现,因为你不选择它们......

答案 1 :(得分:0)

我猜你想要这样的东西。请注意,我将您的别名更改为有意义的内容。使用A,B,C是别名的坏习惯。维护这样的代码是一项挑战。

SELECT e.ShowRoomId
    , Sum(eb.BasicAmount) AS TotalBasic
    , Sum(eb.HouseAmount) AS TotalHouseAmount
    , Sum(eb.MedicaleAmount) AS TotalMedicaleAmount
    , Sum(eb.ConvenceAmount) AS TotalConvenceAmount
    , Sum(eb.PhoneBillAmount) AS TotalPhoneBillAmount
    , Sum(eb.DirectorRemuneration) AS TotalDirectorRemuneration
    , Sum(eb.OthersAmount) AS TotalOthersAmount
    , sr.ShowRoomName
    , u.UnitName
FROM Employees e
OUTER APPLY 
(
    SELECT TOP 1 *
    FROM EmployeeBasics eb1
    WHERE e.EmployeeID = eb1.EmployeeID
    ORDER BY eb1.BasicUpdateDate DESC
) AS eb
LEFT JOIN ShowRooms sr ON sr.ShowRoomId = e.ShowRoomId
LEFT JOIN Units u ON u.UnitID = sr.UnitID
GROUP BY e.SHowRoomId
    , sr.ShowRoomName
    , u.UnitName