我有一张表格,上面有客户编号,订单编号和等级字段。每个客户编号可以包含具有不同等级值的多个订单。实施例
cust# order# rank
1 12 1
1 13 3
1 14 2
2 15 2
2 16 1
3 17 3
3 18 4
3 19 1
3 20 2
我正在使用此表来填充另一个看起来像这样的表。
cust order1 order2 order3 order4
1 12 14 13
2 16 15
3 19 20 17 18
那么,如何选择填充order2, order3, order4
字段的第二个,第三个最低排名?
答案 0 :(得分:0)
SELECT R1.cust#, R1.order#, R2.order#, r3.order#, r4.order#
FROM MyTable AS R1
LEFT JOIN MyTable AS R2 ON R1.cust# = R2.cust# AND R2.rank = 2
LEFT JOIN MyTable AS R3 ON R1.cust# = R3.cust# AND R3.rank = 3
LEFT JOIN MyTable AS R4 ON R1.cust# = R4.cust# AND R4.rank = 4
WHERE R1.rank = 1
答案 1 :(得分:0)
也许这会有所帮助:
SELECT cust#,
MAX(CASE WHEN rank = 1 THEN order# END) AS order1,
MAX(CASE WHEN rank = 2 THEN order# END) AS order2,
MAX(CASE WHEN rank = 3 THEN order# END) AS order3,
MAX(CASE WHEN rank = 4 THEN order# END) AS order4
FROM(SELECT cust#,
order#,
ROW_NUMBER() OVER (PARTITION BY cust# ORDER BY order#) rank
FROM your_table
)
GROUP
by cust#
答案 2 :(得分:0)
使用ROW_NUMBER()
和PIVOT
的组合,如下所示:
DECLARE @tmp TABLE (Customer INT, OrderNumber INT, Ranking INT)
INSERT INTO @tmp (Customer, OrderNumber, Ranking)
SELECT 1, 12, 1 UNION
SELECT 1, 13, 3 UNION
--SELECT 1, 14, 2 UNION
SELECT 2, 15, 2 UNION
SELECT 2, 16, 1 UNION
SELECT 3, 17, 3 UNION
SELECT 3, 18, 4 UNION
SELECT 3, 19, 1 UNION
SELECT 3, 20, 2
SELECT
Customer,
MAX(Order1) AS Order1,
MAX(Order2) AS Order2,
MAX(Order3) AS Order3,
MAX(Order4) AS Order4
FROM
(
SELECT
*,
'Order' + CAST(ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY Ranking) AS VARCHAR(4)) AS rn
FROM @tmp
) d
PIVOT
(
MAX(OrderNumber) FOR rn IN ([Order1], [Order2], [Order3], [Order4])
) p
GROUP BY Customer