SQL:按2列重新排序

时间:2016-12-15 02:31:09

标签: sql sql-server

我有一个问题要重新排序。我想在UsernameUserType之前订购此订单而不会违反NumRow订单。它应该是1,2,3等。下面是我当前结果的图像:

enter image description here

这是当前的sql:

WITH ReceiverList AS
(
  SELECT
    ROW_NUMBER() OVER (ORDER BY receiver.username asc) NumRow,
    receiver.username AS Username,
    user_lookup.user_login_id AS UserID,
    CASE
        WHEN user_lookup.username = user_lookup.user_login_id THEN 'RECEIVER' 
        ELSE 'SUB-RECEIVER' 
    END AS UserType
  FROM receiver
  JOIN user_lookup
    ON receiver.username = user_lookup.username
)

SELECT TOP 4 *
FROM ReceiverList

这是我想要的结果,但顺序(NumRow)应该是1,2,3,4。这个sql我在数据表中使用ajax来订购和搜索。请帮帮我们。

enter image description here

1 个答案:

答案 0 :(得分:0)

根据您的结果,您还想按UserId订购:

WITH ReceiverList AS (
      SELECT r.username AS Username,
             ul.user_login_id AS UserID,
             (CASE WHEN ul.username = ul.user_login_id THEN 'RECEIVER' 
                   ELSE 'SUB-RECEIVER' 
              END) AS UserType
      FROM receiver r JOIN
           user_lookup ul
           ON r.username = ul.username
     )
SELECT TOP 4
       row_number() over (username, usertype, userid) as rownum
       rl.*
FROM ReceiverList
ORDER BY rownum;

您无法在定义它的同一usertype中使用SELECT