SQL分组问题导致重复行而不是分组

时间:2016-06-01 13:20:31

标签: sql sql-server sql-server-2008

不知怎的,我的SQL没有正确分组。我想每张发票只有一行。我不希望列categoryid,但我认为这导致查询每个发票输出两行(或更多)。

select invoices.InvoiceID, 
    InvoiceDate,
    month(InvoiceDate) as 'month',
    year(InvoiceDate) as 'year',
    CustomerCompanyName,
    countryname,
    case when CATEGORIES.ParentCategoryID in (125,183) and CATEGORIES.CategoryID not in (162, 163, 164, 165) then
        count(SHIPMENTPRODUCTS.ProductID) 
    else
        0
    end as Qnt
--  ,CATEGORIES.CategoryID -- this line showed me that it does not group by categoryid somehow...
from INVOICES
inner join CUSTOMERS on invoices.CustomerID = customers.CustomerID
inner join COUNTRIES on CUSTOMERS.CountryID = COUNTRIES.CountryID
inner join shipments on shipments.invoiceid = invoices.invoiceid and shipments.ShipmentCancelled = 0
inner join SHIPMENTPRODUCTS on shipments.shipmentid = SHIPMENTPRODUCTS.ShipmentID
inner join products on SHIPMENTPRODUCTS.ProductID = products.productid
inner join CATEGORIES on products.CategoryID = CATEGORIES.CategoryID
group by invoices.InvoiceID, 
    invoices.InvoiceDate, 
    customers.customercompanyname, 
    countries.CountryName, 
    CATEGORIES.ParentCategoryID, 
    CATEGORIES.CategoryID

enter image description here

我知道我可以通过在temptable中插入结果并将其分组来解决这个问题。或者使用子选择。但是我想在没有子选择或临时表的情况下修复此问题。它在我的分组或连接中必须是一个小错误,但我没有看到它。

3 个答案:

答案 0 :(得分:2)

您可能想要条件聚合:

select invoices.InvoiceID, InvoiceDate,
       month(InvoiceDate) as [month], year(InvoiceDate) as [year],
       CustomerCompanyName, countryname,
       sum(case when CATEGORIES.ParentCategoryID in (125,183) and CATEGORIES.CategoryID not in (162, 163, 164, 165)
                then 1 else 0
           end) as Qnt

然后将CategoryIdParentCategoryId退出group by条款。

答案 1 :(得分:0)

您需要从CategoryId以及select

中删除group by

答案 2 :(得分:0)

作为我之前发布的评论的示例,我建议用另一个语句包装语句并让列CategoryId离开:

select T.InvoiceId,
       T.InvoiceDate,
       T.Month,
       T.Year,
       T.CustomerCompanyName,
       T.countryname,
       Sum( T.Qnt ) as QNT    // not sure about this at the moment

  from (

     // TODO: insert your query

  ) T

group by T.InvoiceID, 
         T.InvoiceDate,
         T.month,
         T.year,
         T.CustomerCompanyName,
         T.countryname,
         T.Qnt