涉及四向连接的SQL查询

时间:2011-05-30 23:35:35

标签: sql sql-server sql-server-2005

尝试为MSSQL练习创建4路查询。让我简要描述一下表格:

4个主要表,供应商(供应商详细信息,pk vendorId),发票(发票明细pk InvoiceId,fk VendorID),InvoiceLineItems(I)和GlAccounts(accountNo pk)。

查询:编写一个返回四列的SELECT语句:VendorName,AccountDescription,LineItemCount和LineItemSum。 LineItemCount是行计数,LineItemSum是InvoiceLineItemAmount列的总和

我的解决方案:

SELECT Vendors.VendorName, GLAccounts.AccountDescription, 
  SUM(InvoiceLineItems.InvoiceLineItemAmount) as LineItemSum, 
  Count (InvoiceLineItems.InvoiceID) as LineItemCount
FROM Vendors  INNER JOIN Invoices
ON Vendors.VendorID = Invoices.VendorID 
INNER JOIN InvoiceLineItems
  ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID
INNER JOIN GLAccounts
  ON InvoiceLineItems.AccountNo = GLAccounts.AccountNo
ORDER BY  Vendors.VendorName

问题:

Msg 8120,Level 16,State 1,Line 1 列'Vendors.VendorName'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

THE DILEMMA:

不确定为什么会出现这个问题,因为很明显我在Group By子句中提到了Vendors.VendorName。我怀疑它与我正在执行的内连接有关,因为它们是多个,我一定有错。

有人能发现这里有什么不对吗?

4 个答案:

答案 0 :(得分:2)

添加GROUP BY Vendors.VendorName,GLAccounts.AccountDescription

答案 1 :(得分:2)

由于您要为每个InvoiceLineItemAmount汇总(聚合)InvoiceIDVendorName一个结果,因此您还需要对VendorName和{{ 1}}列。只需添加一个

AccountDescription

在查询结束时。

答案 2 :(得分:0)

尝试

SELECT Vendors.VendorName, GLAccounts.AccountDescription, SUM(InvoiceLineItems.InvoiceLineItemAmount) as LineItemSum, Count (InvoiceLineItems.InvoiceID) as LineItemCount FROM Vendors INNER JOIN Invoices ON Vendors.VendorID = Invoices.VendorID INNER JOIN InvoiceLineItems ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID INNER JOIN GLAccounts ON InvoiceLineItems.AccountNo = GLAccounts.AccountNo Group By Vendors.VendorName, GLAccounts.AccountDescription ORDER BY Vendors.VendorName.

Sum, Count, Avg etc是聚合函数,因此记录必须按特定条件分组才能执行这些操作。

答案 3 :(得分:0)

我们必须考虑您在同一张发票上有多个gl帐户值的可能性。为此,我们需要使用子查询,该子查询将为我们提供这些帐号的分隔列表。另外,建议您为单张发票执行此操作?如果是这样,结果可能如下所示:

Select V.VendorName
    , Stuff(
        (
        Select ', ' + GA1.AccountDescription
        From InvoiceLineItems As LI1
            Join GLAccounts As GA1
                On GA1.AccountNo = LI1.AccountNo
        Where LI1.InvoiceId = I.InvoiceId
        Group By GA1.AccountDescription
        Order By GA1.AccountDescription
        ).value('.', 'nvarchar(max)'), 1, 2, '') As AccountDescriptions
    , Coalesce( LineItemInfo.ItemCount, 0 ) As LineItemCount
    , Coalesce( LineItemInfo.AmountTotal, 0 ) As LineItemSum
From Vendors As V
    Join Invoices As I
        On I.vendorid = V.vendorid
    Left Join   (
                Select LI2.InvoiceId
                    , Count(*) As ItemCount
                    , Sum(LI2.Amount) As AmountTotal
                From InvoiceLineItems As LI2
                Group By LI2.InvoiceId
                ) As LineItemInfo
        On LineItemInfo.InvoiceId = I.InvoiceId
Where I.InvoiceId = @SomeInvoiceId