我创建了一个表,将Product信息与Master ID表连接起来。主ID是产品信息通用的外键。因此,购买了多个产品的每个人都将拥有一个通用的Master ID。我想要得到最早卖给客户的产品——所以我使用ROW_NUMBER() PARTITION BY。
SELECT PRODUCT_NUM, CO_Cd, PROD_CD, Date,
MASTER_ID,
ROW_NUMBER() OVER (PARTITION BY MASTER_ID ORDER BY Date) ROW_NUM
FROM MyTable
ORDER BY MASTER_ID
但是,我面临的情况是在同一天购买了两个产品。所以SQL我想是随机分配ROW_NUM = 1到任何产品。我想默认ROW_NUM = 1文具而不是PRINTER。我尝试了一个Case语句,当PROD_CD = 'STATIONERY'然后'PA' ORDER BY Date时,该PARTITION BY MASTER_ID Case。需要更多的指导。
你刚才把CASE
放在了PARTITION BY
里,它应该在ORDER BY
里
SELECT
PRODUCT_NUM,
CO_Cd,
PROD_CD,
Date,
MASTER_ID,
ROW_NUMBER() OVER (PARTITION BY MASTER_ID
ORDER BY Date, CASE WHEN PROD_CD = 'STATIONERY' THEN 1 ELSE 2 END) ROW_NUM
FROM MyTable
ORDER BY MASTER_ID
可以在order by
中包含prod_cd
。出于这个目的,'STATIONERY' > 'PRINTER'
和你想要它首先,所以需要降序排序:
SELECT PRODUCT_NUM, CO_Cd, PROD_CD, Date, MASTER_ID,
ROW_NUMBER() OVER (PARTITION BY MASTER_ID ORDER BY Date, PROD_CD DESC) AS ROW_NUM
FROM MyTable
ORDER BY MASTER_ID;