额外的SQL查询列

时间:2018-12-26 09:22:53

标签: sql sql-server

我需要从我的SQL查询中的另一个表中选择额外的列。

SELECT      
    d.UnitID,
    b.BookingID,
    d.ProjectID,
    b.ClientName,
    (SELECT LetterTypeID 
     FROM Letters 
     WHERE ProjectID = 27 AND BookingID = b.BookingID)                  
FROM        
    ScheduledDues AS d 
INNER JOIN
    Booking AS b ON d.BookingID = b.BookingID 
INNER JOIN
    Units AS u ON d.UnitID = u.UnitID               
WHERE
    d.ProjectID = 27 
    AND DueFrom <= GETDATE()
GROUP BY    
    d.BookingID, d.UnitID, d.ProjectID,
    u.UnitNo, b.ClientName
HAVING      
    SUM(DueTill) = 0

我该怎么做?并分组。是否可以选择LetterTypeID

2 个答案:

答案 0 :(得分:0)

需要在group by中使用LetterTypeID,如下所示,或者您可以将不带字母表的结果提取到temp中,然后将其与字母结合起来以获得LetterTypeID

SELECT       d.UnitID,
            b.BookingID,
            d.ProjectID,
            b.ClientName,
            l.LetterTypeID                   
FROM        ScheduledDues AS d INNER JOIN
            Booking AS b ON d.BookingID = b.BookingID INNER JOIN
            Units AS u ON d.UnitID = u.UnitID INNER JOIN
            Letters AS l ON b.BookingID=l.BookingID AND l.ProjectID=27          
WHERE       d.ProjectID = 27 AND
            DueFrom <= GETDATE()

GROUP BY    d.BookingID,
            d.UnitID,
            d.ProjectID,
            u.UnitNo,
            b.ClientName,
            l.LetterTypeID
HAVING      SUM(DueTill) = 0

答案 1 :(得分:0)

您可以尝试查询

SELECT  BookingID, UnitID, ProjectID
    UnitNo, ClientName ,LetterTypeID FROM (SELECT      
    d.UnitID,
    b.BookingID,
    d.ProjectID,
    b.ClientName,
    DueTill,
    (SELECT LetterTypeID 
     FROM Letters 
     WHERE ProjectID = 27 AND BookingID = b.BookingID)   LetterTypeID               
FROM        
    ScheduledDues AS d 
INNER JOIN
    Booking AS b ON d.BookingID = b.BookingID 
INNER JOIN
    Units AS u ON d.UnitID = u.UnitID               
WHERE
    d.ProjectID = 27 
    AND DueFrom <= GETDATE()) x
GROUP BY    
    BookingID, UnitID, ProjectID,
    UnitNo, ClientName ,LetterTypeID
HAVING      
    SUM(DueTill) = 0