在SQL Server中对3个表进行分组的日期之间进行过滤

时间:2017-09-10 06:17:40

标签: sql sql-server

我在SQL Server中有这个SQL:

SELECT 
    Itens.Mercadoria, Mercadoria.Nome, Cabecalho.Data, 
    SUM(ValorUnitario) AS Total, 
    SUM(Quantidade) AS Quantidade
FROM 
    Itens 
INNER JOIN 
    Mercadoria ON Itens.Mercadoria = Mercadoria.Codigo 
INNER JOIN 
    Cabecalho ON Cabecalho.Codigo = Itens.Cabecalho 
WHERE 
    Cabecalho.Data >= '2016-01-01' 
    AND Cabecalho.Data <= '2018-12-31'
GROUP BY 
    Itens.Mercadoria, Mercadoria.Nome, Cabecalho.Data 
ORDER BY 
    4 DESC

返回以下结果。

enter image description here

突出显示的值正在重复,我不想重复,我想只显示每个项目一次,并且QuantidadeTotal字段是SUM。

例如:

`Camisa Polo` -> **Quantidade = 23**
`Calça Jeans` -> **Quantidade = 15** 
`Camiseta Estampada` -> **Quantidade = 21**

1 个答案:

答案 0 :(得分:1)

假设销售和SaleItems之间的关系基于SalesId 您可以在分配给your_start_date和your_end_date之间使用正确的值

  select  Products.ProductName 
        , sum(SaleItems.Price)
        , sum(SaleItems.Quantity)
  from  Products
  inner join SaleItems on SaleItems.IdProduct = Products.IdProduct
  inner join Sales on Sales.IdSale = SaleItems.IdSale
  where SaleDate between your_start_date and your_end_date
  group by  Products.ProductName 

在您的情况下,删除或汇总Cabecalho.Data列,例如:

  SELECT Itens.Mercadoria
      ,  Mercadoria.Nome
      , SUM(ValorUnitario) AS Total
      , SUM(Quantidade) AS Quantidade
  FROM Itens INNER JOIN Mercadoria ON Itens.Mercadoria = Mercadoria.Codigo 
  INNER JOIN Cabecalho ON Cabecalho.Codigo = Itens.Cabecalho 
  WHERE Cabecalho.Data between   '2016-01-01' AND  '2018-12-31'
  GROUP BY Itens.Mercadoria, Mercadoria.Nome
  ORDER BY 4 DESC

  SELECT Itens.Mercadoria
      ,  Mercadoria.Nome
      ,  max(Cabecalho.Data)
      , SUM(ValorUnitario) AS Total
      , SUM(Quantidade) AS Quantidade
  FROM Itens INNER JOIN Mercadoria ON Itens.Mercadoria = Mercadoria.Codigo 
  INNER JOIN Cabecalho ON Cabecalho.Codigo = Itens.Cabecalho 
  WHERE Cabecalho.Data between   '2016-01-01' AND  '2018-12-31'
  GROUP BY Itens.Mercadoria, Mercadoria.Nome 
  ORDER BY 4 DESC