以不同顺序计算重复项目

时间:2014-11-14 23:25:48

标签: sql-server count having

目标: 要知道我们是否在不同的采购订单上多次购买了重复的StockCodes或Stock Description

因此,如果我们在采购订单1和采购订单2上购买部件ABC,则应返回

的结果

PurchaseOrders,Part#,Qty

采购订单1,采购订单2,ABC,2

我只是不知道如何将整个代码整合在一起,更重要的是,如何在不滚动所有结果的情况下知道它是否发生在超过1个采购订单上,也可能与多个(有计数)语句有关,因为我似乎只是通过StockCode做的

SELECT t1.PurchaseOrder,
       t1.MStockCode,
       Count(t1.MStockCode) AS SCCount,
       t1.MStockDes,
       Count(t1.MStockDes)  AS DescCount
FROM   PorMasterDetail t1
       INNER JOIN PorMasterHdr t2
               ON t1.PurchaseOrder = t2.PurchaseOrder
WHERE  Year(t2.OrderEntryDate) = Year(Getdate())
       AND Month(t2.OrderEntryDate) = Month(Getdate())
GROUP  BY t1.PurchaseOrder,
          t1.MStockCode,
          t1.MStockDes
HAVING Count(t1.MStockCode) > 1 

使用回复我想出了以下

select * from 
(
SELECT COUNT(dbo.InvMaster.StockCode) AS Count, dbo.InvMaster.StockCode AS StockCodes, 
dbo.PorMasterDetail.PurchaseOrder, dbo.PorMasterHdr.OrderEntryDate
FROM  dbo.InvMaster INNER JOIN  dbo.PorMasterDetail ON 
dbo.InvMaster.StockCode =  dbo.PorMasterDetail.MStockCode 
INNER JOIN dbo.PorMasterHdr ON dbo.PorMasterDetail.PurchaseOrder = dbo.PorMasterHdr.PurchaseOrder
WHERE YEAR(dbo.PorMasterHdr.OrderEntryDate) = YEAR(GETDATE())
GROUP BY dbo.InvMaster.StockCode, dbo.InvMaster.StockCode,  
dbo.PorMasterDetail.PurchaseOrder, dbo.PorMasterHdr.OrderEntryDate
) Count
Where Count.Count > 1

这将返回以下内容,这将开始更有帮助 在结果行2,3,4中,我们可以看到相同的股票代码(* 30044)在不同的订单上订购3次 购买订单。

我想问题是,是否可以看一下如果在30天内有多次订购的话。 这可能吗?

Count   StockCodes  PurchaseOrder   OrderEntryDate
2   *12.0301.0021   322959      2014-09-08 
2   *30044          320559      2014-01-21 
8   *30044          321216      2014-03-26 
4   *30044          321648      2014-05-08 
5   *32317          321216      2014-03-26 
4   *4F-130049/TEST 323353      2014-10-22 
5   *650-1157/E     322112      2014-06-24 
2   *650-1757       321226      2014-03-27 

1 个答案:

答案 0 :(得分:0)

SELECT *
FROM
(
  SELECT h.OrderEntryDate, d.*,
  COUNT(*) OVER (PARTITION BY d.MStockCode) DupeCount
  FROM
  PorMasterHdr h
  INNER JOIN PorMasterDetail d ON
  d.PurchaseOrder = h.PurchaseOrder
  WHERE
  -- first day of current month
  -- http://blog.sqlauthority.com/2007/05/13/sql-server-query-to-find-first-and-last-day-of-current-month/
  h.OrderEntryDate >= CONVERT(VARCHAR(25), DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()),101)
) dupes
WHERE
dupes.DupeCount > 1;

如果您只是对股票代码进行重复数据删除,这应该可行。如果你想重复股票代码和股票代码,或者股票代码或股票代码,我有点不清楚。

此外,我还不清楚您的退货栏,因为它几乎看起来像您想要转动列,以便两个采购订单编号出现在同一行。