2012-03-22 109 views
-1

以列的最大需要你的幫助來獲得CAP_PRICE的基礎上在SQL中的select語句一定的標準最大:基於特定標準

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

+0

你的標準是什麼sid_rnk? – 2012-03-22 18:40:36

+0

剛剛考慮CAP_price的最大值有什麼區別? – Lamak 2012-03-22 18:42:07

+0

@Lamak:如果任何標準滿足上面,它應該停在那裏。例如,如果第二行的CAP_PRICE爲5 ..它應該給出結果5 – satyajit 2012-03-22 18:44:48

回答

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 
+0

我認爲這可能只會在可能出現負價時破裂,我懷疑是這種情況。至少,這是正確的道路,因此是有用的。 – 2012-03-22 19:23:51