【问题标题】:SQL Retain or Running totalSQL 保留或运行总计
【发布时间】:2020-12-23 01:59:50
【问题描述】:

我有一张表,其中有一个商店列表,我想按分配量对它们进行排序,然后对于每个商店,我想首先获得最高的分配量并继续总计,直到达到一定数量,例如 60% 和然后为所有这些记录触发一个字段 (ETA60) 为真。

所以我的桌子看起来像这样。

【问题讨论】:

  • 请阅读this,了解一些改进问题的技巧。
  • 我想先按 Store(DIVLOC 未显示我知道)然后按 Distri(分销)订购。单张订单无关紧要,只是碰巧我这样做了。对不起

标签: sql tsql ssms


【解决方案1】:

你想要一个运行总和和一些 case 逻辑:

select t.*,
       (case when sum(distr1) over (partition by store order by tract) - distr1 >= 0.6
             then 'X'
        end) as eta60
from t;

【讨论】:

  • -- 'order' 附近的语法不正确。选择 DIVLOC, TRACTID, Distribution Into [aTemp].[TRACTS_WITH_CD_ETA_Testing] from [GEO].[TRACTS_WITH_CREDITDATA__ETA_True_D2019_V2020] ALTER TABLE [aTemp].[TRACTS_WITH_CD_ETA_Testing] ADD ETA60 Bit DEFAULT 0 WITH VALUES select (CDTemp].[TRACTS_ETATH_Testing]当 sum(Distribution) over (divloc order by DIVLOC, Distribution) - Distribution >= 0.6 then 1 end) as eta60 from [aTemp].[TRACTS_WITH_CD_ETA_Testing] 的情况; Select * From [aTemp].[TRACTS_WITH_CD_ETA_Testing] 按 divloc 排序,分布
  • @Bearcatrunner 。 . .此语法适用于所有受支持的 SQL Server 版本。
【解决方案2】:

您可以使用窗口函数来过滤记录:

SELECT x.store, x.tract, x.distri, x.eta as eta60 from 
(SELECT a.*, coalesce(SUM(distri) OVER(PARTITION BY store 
ORDER BY tract rows between unbounded preceding and 1 preceding ), distri) as eta60,
coalesce(SUM(distri) OVER(PARTITION BY store 
ORDER BY tract rows unbounded preceding ), distri) as eta
FROM
table_dist a) x WHERE coalesce(eta60, distri) <= 60;

如果您不想过滤并仅使用标记“X”标记此类记录,则可以使用以下查询:

SELECT a.*, case when coalesce(SUM(distri) OVER(PARTITION BY store 
ORDER BY tract rows between unbounded preceding and 1 preceding ), distri) <= 60 THEN 'X' END as eta60 FROM
table_dist a;

【讨论】:

  • -- 'order' 附近的语法不正确。选择 DIVLOC, TRACTID, Distribution Into [aTemp].[TRACTS_WITH_CD_ETA_Testing] from [GEO].[TRACTS_WITH_CREDITDATA__ETA_True_D2019_V2020] ALTER TABLE [aTemp].[TRACTS_WITH_CD_ETA_Testing] ADD ETA60 Bit DEFAULT 0 WITH VALUES select (CDTemp].[TRACTS_ETATH_Testing]当 sum(Distribution) over (divloc order by DIVLOC, Distribution) - Distribution >= 0.6 then 1 end) as eta60 from [aTemp].[TRACTS_WITH_CD_ETA_Testing] 的情况; Select * From [aTemp].[TRACTS_WITH_CD_ETA_Testing] 按 divloc 排序,分布
猜你喜欢
  • 2016-07-18
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2013-01-17
  • 2011-12-02
  • 1970-01-01
相关资源
最近更新 更多