您能否帮助我如何获得预期的输出,如下面的屏幕截图所示?
DECLARE @TT TABLE ( CUSTOMERID INT, TYPE VARCHAR(100) , D1 DATE)
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/1/2017')
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/2/2017')
INSERT INTO @TT VALUES ( 15001,'TYPE1', '4/3/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/4/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/5/2017')
INSERT INTO @TT VALUES ( 15001,'NON TYPE1', '4/6/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/1/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/2/2017')
INSERT INTO @TT VALUES ( 245,'Non TYPE1', '4/3/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/4/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/5/2017')
INSERT INTO @TT VALUES ( 245,'TYPE1', '4/6/2017')
查询是:
SELECT * ,
DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY CUSTOMERID,TYPE) DR
FROM @TT
WHERE CUSTOMERID = 15001
ORDER BY CUSTOMERID,D1
SELECT *,
DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY CUSTOMERID,TYPE) DR
FROM @TT
WHERE CUSTOMERID = 245
ORDER BY CUSTOMERID,D1
感谢您的帮助。
答案 0 :(得分:1)
您希望按最短日期订购群组。我认为它是这样的:
SELECT t.*,
DENSE_RANK() OVER ( PARTITION BY CUSTOMERID ORDER BY mind1, TYPE) DR
FROM (SELECT t.*, MIN(d1) OVER (PARTITION BY CUSTOMERID, TYPE) as mind1
FROM @TT t
) t
WHERE CUSTOMERID = 15001
ORDER BY CUSTOMERID, D1;
这种假设类型不是交错的(如示例中所示)。如果是这种情况,那么请问另一个问题。这显着改变了这个问题。该问题还应提供更好的样本数据和预期结果。