2013-03-24 61 views
1

美好的一天。ORDER BY表現不如預期

首先我必須查詢:

; 
    WITH ranked AS (
     SELECT 
     p.id_price as p_id_price, 
     p.id_service as p_id_service, 
     p.name as p_name, 
     p.name_original as p_name_original, 
     p.id_producer_country as p_id_producer_country, 
     p.id_firm as p_id_firm, 
     f.name as f_name, 
     f.address as f_address, 
     f.phone as f_phone, 
     city.name as city_name, 
     pc.name as pc_name, 
     ROW_NUMBER() OVER (
      PARTITION BY p.id_firm 
      ORDER BY 
      CASE -- this criterion puts matching products before non-matching ones 
       WHEN p.name like '%test%' COLLATE SQL_Latin1_General_Cp1251_CI_AS 
       THEN 1 ELSE 2 
      END, 
      p.id_price -- you may use any sorting criteria at this point, 
         -- just ensure it makes the results predictable 
     ) AS rnk 
     FROM Price p 
     left join Firm f 
     on f.id_service=p.id_service 
     AND f.id_city=p.id_city 
     AND f.id_firm=p.id_firm 
     left join City city 
     on city.id_city = p.id_city 
     left join Producer_country pc 
     on pc.id_producer_country = p.id_producer_country 
     WHERE p.id_city='73041' 
     AND p.include='1' 
     AND p.blocked='0' 
     AND f.blocked='0' 
     AND (f.name like '%test%' COLLATE SQL_Latin1_General_Cp1251_CI_AS 
      OR p.name like '%test%' COLLATE SQL_Latin1_General_Cp1251_CI_AS) 
    ) 
    SELECT * 
    FROM ranked 
    WHERE rnk = 1 
ORDER BY CASE WHEN f_name LIKE '%$..' THEN 0 ELSE 1 END, 
       f_name 
     ; 

的ORDER BY沒有工作:

results

Structure tables here

我需要爲什麼沒有ORDER BY像預期的$符號

後按升序排序數字f_name?

+0

你別名'f.name作爲f_name' – Gibron 2013-03-24 06:18:16

+1

@Gibron感謝,但我問的其他問題(混裝) – 2013-03-24 06:21:56

+0

是' '%$ ..''其實你喜歡的查詢?它與您所圈選的字符串不匹配。你的意思是'%$%'? – Gibron 2013-03-24 06:24:43

回答

2

在進一步討論後,意識到我們需要將相同的字符串以兩種方式進行排序。首先如果它有一個$字符,然後是字符串後面的字符,然後是$字符。鑑於ORDER BY將是:

ORDER BY 
    CASE WHEN f_name LIKE '%$%' THEN 0 ELSE 1 END, 
    SUBSTRING (name ,CHARINDEX('$' , name)+1, (LEN(name)) - CHARINDEX('$', name) ASC 
+0

大謝謝我的新知識)) – 2013-03-24 07:19:02

+0

總是樂意幫忙! – Gibron 2013-03-24 07:21:44

4

f.name僅在WITH條款中有效。當你想再次訂購記錄,使用別名提供

CASE WHEN f_name LIKE '%$..' THEN 0 ELSE 1 END 
+0

對不起,即時通訊問其他問題。但是謝謝 – 2013-03-24 06:20:25

+0

嘗試''%$。'',你的預期結果是什麼? – 2013-03-24 06:25:16

+0

現在結果http://i.stack.imgur.com/17BHZ.png 但我需要以與此處公司相同的方式獲得結果http://sqlfiddle.com/#!3/d1514/3 – 2013-03-24 06:28:24