如何使用一列过滤查询在另一列中有多个匹配?

时间:2017-02-14 14:07:38

标签: sql sql-server

很难思考如何过滤我的查询。我有一个查询结果,结果我只想显示按照" EACH"作为" CASE"或" INNER"一个星期。

目前的输出示例:

values = np.random.pareto(1.5, 10000) + 1

因此,使用此示例输出,我只想显示结果:

loc=0

以下是我目前对如何获得这些结果的疑问:

Weekno     Itemno     UnitofMeasure     ConvQty     #Orders
1           31111      EACH               1           5
1           31111      CASE               144         10
1           31112      EACH               1           10 
1           31113      CASE               144         2
2           31111      EACH               1           10
2           31112      EACH               1           20
2           31112      CASE               144         15  
2           31113      EACH               1           5
2           31113      INNER              12         20

3 个答案:

答案 0 :(得分:1)

你会计算每一个'和' INNER' /' CASE'每周和项目,仅显示两者中匹配的周/项目对。

select weekno, itemno, unitofmeasure, convqty, #orders
from
(
  select weekno, itemno, unitofmeasure, convqty, #orders
    , count(case when unitofmeasure = 'EACH' then 1 end) 
            over (partition by weekno, itemno) as cnt_each
    , count(case when unitofmeasure in ('INNER','CASE') then 1 end) 
            over (partition by weekno, itemno) as cnt_inner_or_case
  from mytable
) counted
where cnt_each > 0 and cnt_inner_or_case > 0;

答案 1 :(得分:1)

declare @T TABLE(
    Weekno     INT,
    Itemno     INT,
    UnitofMeasure  VARCHAR(32),
    ConvQty     INT,
    Orders  INT)

INSERT @T
VALUES
(1, 31111, 'EACH', 1, 5),
(1, 31111, 'CASE', 144, 10),
(1, 31111, 'CASE', 144, 11),
(1, 31112, 'EACH', 1 , 10),
(1, 31113, 'CASE', 144 , 2),
(2, 31111, 'EACH', 1 , 10),
(2, 31112, 'EACH', 1 , 20),
(2, 31112, 'CASE', 144, 15), 
(2, 31113, 'CASE', 144, 5)

SELECT a.* 
FROM @T a
    JOIN (
        SELECT DISTINCT t.Weekno, t.Itemno
        FROM @T t
            CROSS APPLY (SELECT Itemno FROM @T WHERE UnitofMeasure IN ('CASE', 'INNER') AND Weekno = t.Weekno AND Itemno = t.Itemno) c
        WHERE t.UnitofMeasure = 'EACH' 
    ) q ON q.Itemno = a.Itemno AND q.Weekno = a.Weekno

答案 2 :(得分:0)

如果我理解正确,以下查询应该可以解决问题。它将所有UnitMeasures INNER视为有效,并将所有EACH和CASE对视为有效。 :

DECLARE @t TABLE (Weekno int, Itemno int, UnitofMeasure varchar(10), ConvQty int, NumOrders int);

INSERT INTO @t VALUES
 (1, 31111, 'EACH', 1   , 5  )
,(1, 31111, 'CASE', 144 , 10 )
,(1, 31112, 'EACH', 1   , 10 )     
,(1, 31113, 'CASE', 144 , 2  )
,(2, 31111, 'EACH', 1   , 10 )
,(2, 31112, 'EACH', 1   , 20 )
,(2, 31112, 'CASE', 144 , 15 )     
,(2, 31113, 'CASE', 144 , 5  );


WITH cte AS(
  SELECT Weekno, Itemno, UnitofMeasure, ConvQty, NumOrders, CASE WHEN UnitofMeasure IN ('CASE', 'EACH') THEN 0.5 WHEN UnitofMeasure = 'INNER' THEN 1 END AS x
    FROM @t
),
cteFilter AS(
  SELECT Weekno, Itemno, sum(x) x
     FROM cte
     GROUP BY Weekno, Itemno
     HAVING sum(x) = 1
)
SELECT t.*
  FROM @t AS t
  JOIN cteFilter AS f ON f.Weekno = t.Weekno AND f.Itemno = t.Itemno