【发布时间】:2017-11-17 16:37:42
【问题描述】:
为了举例,我有以下数据集: ToyReferenceNumber、Company、CompositeCalculatedField、PermanentRecallDate、ReturnToStoreDate
基本上,每个项目可能有 3-4 个条目(虚构的公司 TheToyCompany,或 TTC):
TTC-011-0934, TTC, calculation, NULL, 2017-03-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2014-05-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2011-08-27 12:01:01.00
TTC-994-0132, TTC, calculation, 2017-06-12 12:01:01.00, NULL
TTC-994-0132, TTC, calculation, NULL, 2017-02-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, 2015-03-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, NULL
从业务逻辑的角度来看,对于第一个产品 (0934),它进行了多次召回(我们不在乎哪个印刷或生产批次),但每次都被修复并返回商店。
对于 0132,它试图修复缺陷,但随后公司决定报废该产品,因为它无论如何都没有销售。
对于 0122,产品批次于 2015 年 3 月 1 日被召回、修复,然后发送到商店,但当前批次目前正在修复(因此,NULL,NULL)。
管理层需要一份报告,说明当前修复工厂计费(例如修理玩具的人的时间表)。
伪查询:
For a given product, return only the record with NULL, NULL dates (actively being fixed)
IF not null, null, return only the record with the PermanentRecallDate
IF no PermanentRecallDate, return only the record with the latest ReturnToStoreDate
oracle查询与下面的伪代码基本一致:
SELECT <normal columns>
,MAX(ts.PermanentRecallDate) KEEP (dense_rank last order by ts.PermanentRecallDate NULLS LAST) PERANENTRECALLDATE
,MAX(ts.ReturnToStoreDate) KEEP (dense_rank last order by ts.ReturnToStoreDate NULLS LAST) RETURNTOSTOREDATE
oracle 查询非常简单,但我在 T-SQL 中需要它:
WITH CTE_ToyReferenceExport
AS
(
SELECT ts.ToyReferenceNumber AS TOYNUM
,tsh.Company AS COMPANY
,MAX(largeSetofCalculations) AS CompositeCalculatedField
,MAX(ts.PermanentRecallDate) AS PERMANETRECALL
,MAX(ts.ReturnToStoreDate) AS RETURNTOSTORE
,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.PermanentRecallDate) as PRDRank
,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.(ReturnToStoreDate) AS RTSDRank
FROM origin.ToyStaging ts
JOIN origin.ToyOrders to ON ts.ordernumer = to.ordno
JOIN origin.ToyShipment tsh ON to.packno = tsh.crateno
LEFT JOIN origin.Shippers sh ON to.packno = sh.cratenum AND 'calcField' = sh.originfield
GROUP BY ts.ToyReferenceNumber, tsh.Company, ts.permanentrecalldate, ts.returntostoredate
)
它还有很多内容,但让我大吃一惊的主要是获取由“MAX..Keep Dense_rank last order by.. NULLS LAST”逻辑返回的结果集。
任何帮助将不胜感激。 SQL Server 2012 是版本。
【问题讨论】:
标签: sql sql-server tsql window-functions