1

再会。

首先我有查询:

   ;
    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 不起作用:

结果

结构表在这里

我需要 f_name 在 $ 符号后按升序排序

为什么ORDER BY行为不符合预期?

4

2 回答 2

4

f.name仅对WITH子句有效。当您想再次订购记录时,请使用提供的别名

CASE WHEN f_name LIKE '%$..' THEN 0 ELSE 1 END
于 2013-03-24T06:17:40.187 回答
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
于 2013-03-24T07:18:09.897 回答