SQL 服务器:输出重复项

SQL Server : outputting duplicates

我使用的是预建程序,所以我无法直接编辑 SQL,我只能编辑它的片段。我遇到的问题是代码正在为客户拥有的许多案例打印出客户代码。例如,如果客户有57个案例,它将打印客户代码57次而不是只显示一次,例如客户代码4个案例57个等

我读到您可能无法将 Unique 或 Distinct 函数与 OVER 命令一起使用,但我不确定没有它如何使总和工作。这是我的代码:

SET NOCOUNT ON; 
DECLARE @ShowZeros nVarChar(4000);

SET @ShowZeros  = 'N';

SELECT 
    SUM ([IC_ProductLots].[Available_Alt]) OVER(PARTITION BY [AR_Customers].    [CustomerCode]) AS [Cases]
    , IC_Products.UnitOfMeasure_Alt
    , SUM([IC_ProductLots].[Available_Stk]) OVER(PARTITION BY [AR_Customers]. [CustomerCode]) AS [Total Stock]
    , IC_Products.UnitOfMeasure_Stk
    , IC_Products.Description1
    , IC_Products.ProductCode
    , AR_Customers.Name
    , AR_Customers.CustomerCode
FROM 
    ((( DC_Transactions 
INNER JOIN  
    AR_Customers ON DC_Transactions.CustomerKey = AR_Customers.CustomerKey)
INNER JOIN  
    IC_ProductLots ON DC_Transactions.LotKey = IC_ProductLots.LotKey)
INNER JOIN  
    IC_Products ON DC_Transactions.ProductKey = IC_Products.ProductKey)
WHERE 
    (IC_Products.ProductCode = '      515070')  AND 
    ((CASE WHEN @ShowZeros = 'Y' or @ShowZeros = 'YES' THEN 1 ELSE
(ISNULL([IC_ProductLots].[Available_Stk],0))
END) > 0)
ORDER BY 
    IC_Products.ProductCode 
    , AR_Customers.CustomerCode 
    , AR_Customers.Name

输出应类似于以下内容:

Cases | U/M  | Total Stock | Description | Cust Name  | Cust Code
-----------------------------------------------------------------
57    | CS   | 1779.45     | Food        | Restaurant | 2
4     | CS   | 120         | Dough       | Bakery     | 44

目前它为客户代码 2 打印出 57 行,为客户代码 44 打印出 4 行,为每个客户代码显示相同的信息。

下面的好像是你想要的。你说你只能部分编辑你的查询,但是你需要 GROUP BY 子句来说明你想要哪些记录(即每个产品和客户一个记录),所以这是主要需要做的。然后你不能使用 OVER 子句,因为聚合组已经由 GROUP BY 给出。为了可读性,我做了更多更改。查看您可以进行哪些编辑。

select 
    sum(l.available_alt) as cases
  , p.unitofmeasure_alt
  , sum(l.available_stk) as [total stock]
  , p.unitofmeasure_stk
  , p.description1
  , p.productcode
  , c.name
  , c.customercode
from dc_transactions t
inner join ar_customers c on t.customerkey = c.customerkey
inner join ic_productlots l on t.lotkey = l.lotkey
inner join ic_products p on t.productkey = p.productkey
where p.productcode = '      515070' 
and (@showzeros in ('Y', 'YES') or l.available_stk > 0)
group by p.productcode, c.customercode
  , p.unitofmeasure_alt, p.unitofmeasure_stk, p.description1, c.name
order by p.productcode, c.customercode;