2017-03-31 98 views
0

eg table schema and required outputSQL查询来计算重复使用2个条件

要找出重复的项目时,它满足两个条件,只有当。在此示例中,只有订单大小为“大”并且其相应日期位于其他实例之前时,才会为每个customer_id重复项目类型。这个第一个条件和重复可以通过使用这个代码来实现。

Select Customer_id, Item_Type, COUNT(*) 
from table 
group by Customer_id, Item_Type 
having count(*) > 1 and sum(case when Order_Size = 'Big' then 1 else 0 end) > 0; 

我该如何包含日期方面呢?

+3

而不是你的电子表格的截图,为什么不文本版本中,我们可以操纵? https://senseful.github.io/web-tools/text-table/ – SqlZim

回答

0

我会做这样的:

select t.customer_id, t.item_type, count(*) 
from (select t.*, 
      min(case when OrderSize = 'Big' then date end) over (partition by customer_id, item_type) as min_big 
     from t 
    ) t 
where date > min_big 
group by t.customer_id, t.item_type; 
+0

我想添加一个第二种情况下,当我们说case时(OrderSize ='Big'和item_type IN(从table2中选择item_type)然后结束日期)....它在case语句的When子句中抛出一个错误说非法表达式。我该如何解决这个问题? – viji

+0

我已经把上面的查询请求作为子查询中的新问题写入When Case语句 - 错误:case语句中的When子句中的非法表达式[Link](https://stackoverflow.com/questions/48670005/subquery-within-when-case -statement-errorillegal-expression-in-when-clause-with) – viji

+0

@viji。 。 。如果你有另一个问题,你应该把它当作另一个问题而不是评论。请问为什么你不接受答案? –

0

我相信你可以在子查询中使用一个窗口函数来决定要计算哪些行,然后在你的主查询中对它们进行计数。喜欢的东西:

Select 
    customer_id, item_type, sum(count_pass) as Count 
FROM 
    (
     Select Customer_id, 
      Item_Type, 
      CASE 
       WHEN Order_Size = 'Big' THEN 0 
       WHEN MIN(Order_Size) OVER (PARTITION BY Customer_ID, Item_Type ORDER BY DateField ASC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) = 'BIG' THEN 1 
       ELSE 0 
       END as count_pass 
     FROM table 
    ) subqry 
GROUP BY 1,2 

那大case语句分解,如:

  1. 如果这个纪录'Big'则忽略它
  2. 如果按日期的所有记录各组customer_id/item_type并查看该记录之前的所有记录,并且该组记录中的min(order_size)(按照字典顺序排序)为'Big',那么您有一个大的前一个日期并且可以计算该记录
  3. 否则......你无法数数。这只是order_size = 'small'而没有前面的'big'的记录。
+0

希望在查询时包含第二个条件。一个新的请求写在[链接](https://stackoverflow.com/questions/48670005/subquery-within-when-case-statement-errorillegal-expression-in-when-clause-with) – viji