0

How can I Count the Lending comments for each lending (the comments is on another table called "LendingComments" with a reference Column called "LendingId" ?

SELECT LendingStatus.Status, Products.Productname, Products.Serial_number,    Deposits.Amount, Lendings.DeliveryDate, Lendings.Id AS LendingId, Products.Id AS ProductId  FROM Lendings
LEFT JOIN Products ON Lendings.ProductId = Products.Id
LEFT JOIN LendingStatus ON Lendings.StatusId = LendingStatus.Id
LEFT JOIN Deposits ON Lendings.DepositId = Deposits.Id
WHERE PersonId = 561 ORDER BY DeliveryDate DESC
4

3 回答 3

1

像这样的马比(如果我对这个问题理解得足够好)

SELECT
LendingStatus.Status, Products.Productname, Products.Serial_number,Deposits.Amount, Lendings.DeliveryDate, Lendings.Id AS LendingId, Products.Id AS ProductId, LendingComments.NumLendingComments
FROM Lendings
LEFT JOIN Products ON Lendings.ProductId = Products.Id
LEFT JOIN LendingStatus ON Lendings.StatusId = LendingStatus.Id
LEFT JOIN Deposits ON Lendings.DepositId = Deposits.Id
OUTER APPLY
(
SELECT
    COUNT(*) AS NumLendingComments
    FROM
        LendingComments PL
    WHERE
        PL.LendingID = Lendings.LendingID
) AS LendingComments WHERE Personid = 561 ORDER BY DeliveryDate desc
于 2013-04-22T11:07:49.273 回答
0

也许这有帮助:

SELECT CommentCount = Sum(lc.comments) 
                      OVER ( 
                        partition BY lc.id), 
       lendingstatus.status, 
       products.productname, 
       products.serial_number, 
       deposits.amount, 
       lendings.deliverydate, 
       lendings.id AS LendingId, 
       products.id AS ProductId 
FROM   lendings 
       LEFT JOIN products 
              ON lendings.productid = products.id 
       LEFT JOIN lendingstatus 
              ON lendings.statusid = lendingstatus.id 
       LEFT JOIN deposits 
              ON lendings.depositid = deposits.id 
       LEFT JOIN LendingComments lc
              ON lc.LendingId = lendings.Lendings.Id
WHERE  personid = 561 
ORDER  BY deliverydate DESC 

但是,您还没有显示PersonLendings表格,是吗?

于 2013-04-22T11:00:56.230 回答
0

试试这个——

SELECT  ls.status
    ,   p.Productname
    ,   p.Serial_number
    ,   d.AMOUNT
    ,   l.DeliveryDate
    ,   l.Id AS LendingId
    ,   p.Id AS ProductId
    ,   pl.cnt
FROM dbo.Lendings l
LEFT JOIN (
    SELECT pl.LendingId, cnt = COUNT(pl.LendingComments)
    FROM dbo.PersonLendings pl
    GROUP BY pl.LendingId
) pl ON pl.LendingId = l.LendingId
LEFT JOIN dbo.Products p ON l.ProductId = p.Id
LEFT JOIN dbo.LendingStatus ls ON l.StatusId = ls.Id
LEFT JOIN dbo.Deposits d ON l.DepositId = d.Id
WHERE PersonID = 561
ORDER BY l.DeliveryDate DESC
于 2013-04-22T11:07:28.593 回答