目前我有一张由价格组成的表格。
列PriceList,ItemCode,DiscountLine,Amount,Price。
E.G。
*1 , ITEM1 , 0 , 100 , 0.50
*1 , ITEM1 , 1 , 200 , 0.45
1234 , ITEM1 , 0 , 100 , 0.45
1234 , ITEM1 , 1 , 100 , 0.40
问题是,PriceList可以是价格表(以*开头)或客户编号。
我需要一行结果;
所以
CUSTOMER ITEM AMOUNT0 PRICE0 AMOUNT1 PRICE1
1234 ITEM1 100 0.45 200 0.40
为此我使用以下代码:
select Customer.CardCode ,Customer.CardName,SP.* from Customer inner join (
select ItemCode,CardCode,
max(case when DPNum=0 then Amount end) Amount1,
max(case when DPNum=0 then Price end) Price1,
max(case when DPNum=1 then Amount end) Amount2,
max(case when DPNum=1 then Price end) Price2,
max(case when DPNum=2 then Amount end) Amount3,
max(case when DPNum=2 then Price end) Price3,
max(case when DPNum=3 then Amount end) Amount4,
max(case when DPNum=3 then Price end) Price4,
max(case when DPNum=4 then Amount end) Amount5,
max(case when DPNum=4 then Price end) Price5,
max(case when DPNum=5 then Amount end) Amount6,
max(case when DPNum=5 then Price end) Price6,
max(case when DPNum=6 then Amount end) Amount7,
max(case when DPNum=6 then Price end) Price7,
max(case when DPNum=7 then Amount end) Amount8,
max(case when DPNum=7 then Price end) Price8,
max(case when DPNum=8 then Amount end) Amount9,
max(case when DPNum=8 then Price end) Price9,
max(case when DPNum=9 then Amount end) Amount10,
max(case when DPNum=9 then Price end) Price10
from SPP2 group by ItemCode,CardCode
) sp
on sp.CardCode = Customer.CardCode or sp.CardCode = '*'+cast(ListNum as varchar(1))
where Customer.Cardcode='1234'
order by Customer.CardCode,ItemCode,sp.CardCode DESC
这对于一个小细节来说是分开的; 如果客户有价格表(并且所有客户都有)并且他们有“特殊”价格;我得到每件2行。
所以我的结果是:
CUSTOMER NAME ITEM PLCODE AMOUNT0 PRICE0 AMOUNT1 PRICE1
1234 DUMMY ITEM1 1234 100 0.45 200 0.40
1234 DUMMY ITEM1 *1 100 0.50 200 0.45
如果客户有特价,则只返回此价格。 有没有办法在一个查询中完成此操作? (或者可能有更有效的方式来做我想要完成的事情)?
答案 0 :(得分:3)
您可以使用row_number()
为每位客户获取一行。这是一个想法:
select csp.*
from (select c.*, sp.*,
row_number() over (partition by customer
order by (case when plcode like '*_' then 1 else 2 end)
) as seqnum
from customer c join
(select ItemCode, CardCode,
max(case when DPNum=0 then Amount end) Amount1,
max(case when DPNum=0 then Price end) Price1,
. . .
from SPP2
group by ItemCode, CardCode
) sp
on sp.CardCode = Customer.CardCode or sp.CardCode = '*'+cast(ListNum as varchar(1))
where c.Cardcode = '1234'
) csp
where seqnum = 1;