根据特定标准取最大列

时间:2012-03-22 18:32:41

标签: sql sql-server sql-server-2008

需要你的帮助才能根据sql的select语句中的某些条件获得最大的CAP_PRICE:

IF sid_rnk =0 and prd_id_rnk =1 and cap_price <> 0 
   then Max(cap_price) group by (sid_rnk,prd_rnk) as CAP1

Else if sid_rnk =0 and prd_id_rnk =2 and cap_price <> 0  and cap1 = 0
   then Max(cap_price) group by (sid_rnk,prd_rnk) as cap2

Else if sid_rnk =0 and prd_id_rnk =3 and cap_price <> 0 and cap2 = 0
   then Max(cap_price) group by (sid_rnk,prd_rnk) as cap3

Else if sid_rnk =1 and prd_id_rnk =1 and cap_price <> 0 and cap3 = 0
   then Max(cap_price) group by (sid_rnk,prd_rnk) as cap4

Else if sid_rnk =1 and prd_id_rnk =2 and cap_price <> 0 and cap4 = 0
   then Max(cap_price) group by (sid_rnk,prd_rnk) as cap5

Else if sid_rnk =1 and prd_id_rnk =3 and cap_price <> 0 and cap5 = 0
   then Max(cap_price) group by (sid_rnk,prd_rnk)

示例数据:

CREATE TABLE sap_prod
(
prd_id_rnk int,
sld_to_rnk int,
CAP_geo_1 varchar(20),
F_I_geo_2 varchar(20),
CAP_price int
)


INSERT INTO sap_prod     
       ( prd_id_rnk, sld_to_rnk, CAP_geo_1, F_I_geo_2, CAP_price ) 
SELECT      1,0,'ASMO','ASMO',0   UNION ALL
SELECT      1,0,'ASMO','ASMO',0   UNION ALL 
SELECT      1,0,'ASMO','ASMO',0   UNION ALL 
SELECT      2,0,'WW'  ,'ASMO',0   UNION ALL 
SELECT      2,0,'WW'  ,'ASMO',0   UNION ALL 
SELECT      2,0,'WW'  ,'ASMO',0   UNION ALL 
SELECT      3,0,'EMEA','ASMO',0   UNION ALL 
SELECT      3,0,'EMEA','ASMO',0   UNION ALL 
SELECT      3,0,'IJKK','ASMO',0   UNION ALL 
SELECT      3,0,'IJKK','ASMO',0   UNION ALL
SELECT      1,1,'ASMO','ASMO',0   UNION ALL
SELECT      1,1,'ASMO','ASMO',0   UNION ALL 
SELECT      1,1,'ASMO','ASMO',0   UNION ALL 
SELECT      2,1,'WW'  ,'ASMO',0   UNION ALL 
SELECT      2,1,'WW'  ,'ASMO',0   UNION ALL 
SELECT      2,1,'WW'  ,'ASMO',0   UNION ALL 
SELECT      3,1,'EMEA','ASMO',35  UNION ALL 
SELECT      3,1,'EMEA','ASMO',40  UNION ALL 
SELECT      3,1,'IJKK','ASMO',70  UNION ALL 
SELECT      3,1,'IJKK','ASMO',50   

结果应为:70

1 个答案:

答案 0 :(得分:2)

不确定,但我认为你需要这个:

SELECT TOP 1 cap_price
FROM 
(
    SELECT sld_to_rnk, prd_id_rnk, Max(cap_price) AS cap_price 
    FROM sap_prod
    WHERE cap_price <> 0
    group by sld_to_rnk, prd_id_rnk 
) AS tmp
ORDER BY sld_to_rnk, prd_id_rnk