将三个表组合在一起以显示总计数的查询

时间:2015-11-02 15:23:49

标签: sql sql-server

我似乎无法正确地理解这个问题。我有三张桌子,想要将它们组合起来,以显示每个位置留下多少张票。我正在运行SQL Server 2008 R2。

位置表

_handler.Post(async() => {// do UI changes});

每个位置表的门票

_handler

购买门票表

LocationId | LocationName
1          | Location1 
2          | Location2
3          | Location3

我希望查询显示如下三个表:

TicketId | LocationId | EventId | Amount
1        | 1          | 4       | 25
1        | 2          | 4       | 50
1        | 3          | 4       | 100

这是我一直在玩的查询,但它只显示我已售出门票的位置,我需要它显示所有位置,即使他们没有售票。

AttendeeId | EventId | TicketId | LocationId | Amount | EmployeeId
1          | 4       | 1        | 1          | 5      | 101
2          | 4       | 1        | 1          | 10     | 102
3          | 4       | 1        | 2          | 2      | 103
4          | 4       | 1        | 2          | 4      | 103

3 个答案:

答案 0 :(得分:1)

你需要稍微移动你的桌子..

SELECT  l.LocationName,
        tpl.Amount,
        COALESCE(SUM(pt.Amount),0) Sold,
        tpl.Amount - COALESCE(SUM(pt.Amount),0) Remaining
FROM    Locations l
        INNER JOIN TicketsPerLocation tpl ON l.LocationID = tpl.LocationID
        LEFT JOIN PurchasedTickets pt ON tpl.TicketID = pt.TicketID 
            AND tpl.LocationID = pt.LocationID 
            AND tpl.EventID = pt.EventID
WHERE   tpl.TicketID = 1 AND tpl.EventID = 4
GROUP BY l.LocationName, 
        tpl.Amount

加上你的where语句有P.TicketId = 1,这使得它成为INNER JOIN而不是LEFT JOIN ..所以删除它。

当您加入PurchasedTickets时,请确保它在与TicketsPerLocation相关的所有字段上,而不仅仅是位置

SQL Fiddle

答案 1 :(得分:0)

我可以在您的查询中看到一些问题。看看修复它们是否解决了它:

  1. 由于您需要所有位置,因此您应该在LEFT JOIN之前开始使用该表,而不是在LEFT JOIN之后。

  2. “已购买的票证”表是外部联接,但您可以在where子句中使用它。这总是一个糟糕的组合因为这两件事互相矛盾。我会将该要求移至ON条款。

  3.     SELECT L.LocationName
            ,T.Amount AS Starting
            ,COALESCE(SUM(P.Amount), 0) AS Sold
            ,COALESCE((T.Amount - SUM(P.Amount)), 0) AS Remaining
        FROM Locations L
        LEFT JOIN TicketsPerLocation T ON T.LocationId = L.LocationId
        LEFT JOIN PurchasedTickets P ON T.LocationId = P.LocationId
            AND P.TicketId = 1
        WHERE T.TicketId = 1
            AND T.EventId = 4
        GROUP BY L.NAME
            ,T.Amount
            ,T.TicketId
    

答案 2 :(得分:0)

SELECT L.LocationName, T.Amount as Starting, ISNULL(p.SumAmt,0) As Sold, T.Amount - ISNULL(p.SumAmt,0) AS Remaining
FROM Locations L
LEFT JOIN TicketsPerLocation T
  ON T.LocationId = L.LocationId AND T.TicketId = 1 AND T.EventId = 4 
LEFT JOIN 
   ( SELECT [EventId], [TicketId], [LocationId], SUM(Amount) AS SumAmt 
     FROM PurchasedTickets
     GROUP BY [EventId], [TicketId], [LocationId]
    ) p
    ON T.LocationId = P.LocationId
    AND P.TicketId = T.TicketId AND P.EventId = T.EventId
 ORDER BY L.LocationName

SQL Fiddle