SQL中按条件进行数据分区

时间:2018-07-05 14:25:22

标签: sql sql-server sql-server-2012

如何按条件划分数据?

SELECT [Dt]
      , [CustomerName]

      , [ItemRelation]

      , [SaleCount]
      , [DocumentNum]
      , [DocumentYear]
      , [IsPromo]
      , [CustomerType]
  FROM [Action]. [Dbo]. [FC]

[IsPromo]的值为0和1。 对于零类别ispromo,我需要将数据除以[SaleCount]的销售数量!

例如,我通过ispromo = 0获得20个观察值,其中[SaleCount]仅15个而不是零值。 计算系数,将总天数除以没有零销售的天数除以salecount。 15/20 = 0.75。 必须分别对每个阶层(组)[CustomerName] + [ItemRelation] + [DocumentYear]执行此操作。 因此,如果该组内的系数大于0.71,则应将这些组写入表中 mytab1 如果更少,则在mytab2

如何做到?

数据样本

Dt  CustomerName    ItemRelation    SaleCount   DocumentNum DocumentYear    IsPromo
2018-02-19 00:00:00.000 1   11683   0   999 2018    0
2018-02-20 00:00:00.000 1   11683   0   999 2018    0
2018-02-21 00:00:00.000 1   11683   0   999 2018    0
2018-02-22 00:00:00.000 1   11683   0   999 2018    0
2018-02-23 00:00:00.000 1   11683   0   999 2018    0
2018-02-24 00:00:00.000 1   11683   1339    999 2018    0
2018-02-25 00:00:00.000 1   11683   81  999 2018    0
2018-02-26 00:00:00.000 1   11683   487 999 2018    0
2018-02-27 00:00:00.000 1   11683   861 999 2018    0
2018-02-28 00:00:00.000 1   11683   546 999 2018    0
2018-03-01 00:00:00.000 1   11683   722 999 2018    0
2018-03-02 00:00:00.000 1   11683   890 999 2018    0
2018-03-03 00:00:00.000 1   11683   1128    999 2018    0
2018-03-04 00:00:00.000 1   11683   81  999 2018    0
2018-03-05 00:00:00.000 1   11683   884 999 2018    0
2018-03-06 00:00:00.000 1   11683   3675    999 2018    0
2018-03-07 00:00:00.000 1   11683   3780    999 2018    0
2018-03-08 00:00:00.000 1   11683   3178    999 2018    0
2018-03-09 00:00:00.000 1   11683   1749    999 2018    0
2018-03-10 00:00:00.000 1   11683   1243    999 2018    0

该阶层的系数为0.75 转到mytab1

和这个阶层

Dt  CustomerName    ItemRelation    SaleCount   DocumentNum DocumentYear    IsPromo
2018-02-19 00:00:00.000 2   11684   0   999 2018    0
2018-02-20 00:00:00.000 2   11684   0   999 2018    0
2018-02-21 00:00:00.000 2   11684   0   999 2018    0
2018-02-22 00:00:00.000 2   11684   0   999 2018    0
2018-02-23 00:00:00.000 2   11684   0   999 2018    0
2018-02-24 00:00:00.000 2   11684   1339    999 2018    0
2018-02-25 00:00:00.000 2   11684   81  999 2018    0
2018-02-26 00:00:00.000 2   11684   487 999 2018    0
2018-02-27 00:00:00.000 2   11684   861 999 2018    0
2018-02-28 00:00:00.000 2   11684   546 999 2018    0
2018-03-01 00:00:00.000 2   11684   722 999 2018    0

具有系数0,545454545 11天,按ispromo的零类别分类 而6天的销售量则非零。

1 个答案:

答案 0 :(得分:2)

一种简单的方法将avg()group by结合使用:

select CustomerName, ItemRelation, DocumentYear,
       avg( case when IsPromo > 0 then 1.0 end) as promo_ratio
from action.dbo.fc
group by CustomerName, ItemRelation, DocumentYear;

然后您可以使用having avg( case when IsPromo > 0 then 1.0 end) > 0.71进行过滤。