如何创建对字段进行分组的案例陈述?

How to create a case statement which groups fields?

我正在尝试了解如何将值组合在一起以添加指标。我想 'fix' 值并基于此,为指标添加属性。

我试图对日期、客户名称和产品类型的值进行分组,以创建一个指标来捕获所下订单的类型(仅水果、水果和蔬菜、仅蔬菜)。目标是计算每种订单的总交易量。数据是这样设置的,我要创建的列是'Order Type.

到目前为止我做了什么:

案例陈述

    CASE WHEN Product_Type = 'Fruit' THEN 1 ELSE 0 END AS Fruit_Indicator
, CASE WHEN Product_Type = 'Vegetable' THEN 1 ELSE 0 END AS Veg_Indicator

带分区依据和排序依据的案例语句

, CASE WHEN ROW_NUMBER() OVER (PARTITION BY Order_Date, Customer  ORDER BY Order_Date ASC) = 1  AND Product_Type =  'Fruit' THEN 1 ELSE NULL END AS Fruit_Ind
, CASE WHEN ROW_NUMBER() OVER (PARTITION BY Order_Date, Customer  ORDER BY Order_Date ASC) = 1 AND Product_Type =  'Vegetable' THEN 1 ELSE NULL END AS Veg_Ind

我将不胜感激任何关于正确方向的指导。

谢谢!

您似乎正在尝试获取按日期分组的数据,例如 3 月 21 日、3 月 22 日等...因此,您可能希望使用辅助查询来加入主要数据。第二个查询将按客户和日期汇总。如果日期字段是面向 date/time 的,则必须调整分组依据以获得正确格式化的上下文,例如 date-format 使用 month/day/year 并忽略任何时间组件。这也可能由一个函数来处理,以获取 date-part 并忽略时间。然后,您对聚合的原始数据应该可以满足您的需求。也许是这样的。

select
      yt.date,
      yt.customer,
      yt.product,
      yt.productType,
      case when PreQuery.IsFruit > 0 and PreQuery.IsVegetable > 0
           then 'Fruit & Vegetable'
           when PreQuery.IsFruit > 0 and PreQuery.IsVegetable = 0
           then 'Fruit Only'
           when PreQuery.IsFruit = 0 and PreQuery.IsVegetable > 0
           then 'Vegetable Only' end OrderType
   from
      YourTable yt
         JOIN
         ( select
                 yt2.customer,
                 yt2.date,
                 max( case when yt2.ProductType = 'Fruit'
                           then 1 else 0 end ) IsFruit,
                 max( case when yt2.ProductType = 'Vegetable'
                           then 1 else 0 end ) IsVegetable
              from
                 YourTable yt2
              -- if you want to restrict time period, add a where
              -- clause here on the date range as to not query entire table
              group by
                 yt2.customer,
                 yt2.date ) PreQuery
            ON yt.customer = PreQuery.customer
           AND yt.date = PreQuery.date
   -- same here for your outer query to limit just date range in question.
   -- if you want to restrict time period, add a where
   -- clause here on the date range as to not query entire table
   order by
      yt.date,
      yt.customer,
      yt.product