Ordering by a field not in the select statement in SQL

时光怂恿深爱的人放手 提交于 2020-03-16 05:49:41

问题


I need to create a query that pulls only the customer_no column (because the software restrictions are as such, and I can't code it externally). But I need to be able to sort the data by create_dt (in reverse) column. The code/SQL is restricting me in using the following because in order to sort by something that data has to appear int the select statement.

I can't have it appear there – is there any way around this?

 Select Distinct top 3500 a.customer_no 
  From T_CUSTOMER a  WITH (NOLOCK)
  JOIN (Select a1.customer_no From VXS_CUST_TKW a1 WITH (NOLOCK) Where a1.tkw in (141)) as e ON      e.customer_no = a.customer_no
  Where 1 = 1
 order by a.create_dt desc

回答1:


Of course you can. Your query looks like SQL Server, where this will likely do what you want:

  Select top 3500 a.customer_no 
  From T_CUSTOMER a  WITH (NOLOCK) JOIN
       (Select a1.customer_no
        From VXS_CUST_TKW a1 WITH (NOLOCK)
        Where a1.tkw in (141)
       ) e
       ON e.customer_no = a.customer_no
  Where 1 = 1
  group by a.customer_no
  order by max(a.create_dt) desc;

The equivalent query in MySQL would look like:

  Select a.customer_no 
  From T_CUSTOMER a JOIN
       (Select a1.customer_no
        From VXS_CUST_TKW a1 
        Where a1.tkw in (141)
       ) e
       ON e.customer_no = a.customer_no
  Where 1 = 1
  order by a.create_dt desc
  limit 3500;

I removed the distinct because it may not be necessary. If it is, add it back in.




回答2:


This does not look like mysql.

Anyway... you could try an ordered sub-select IE

From (select * from T_CUSTOMER order by create_dt) a WITH (NOLOCK)

I hope this helps.




回答3:


Use a subquery that includes the column you're ordering by. Then the main query can just return the column you care about:

SELECT customer_no
FROM (
    Select top 3500 a.customer_no, a.create_dt
      From T_CUSTOMER a  WITH (NOLOCK) JOIN
           (Select a1.customer_no
            From VXS_CUST_TKW a1 WITH (NOLOCK)
            Where a1.tkw in (141)
           ) e
           ON e.customer_no = a.customer_no
      Where 1 = 1
      order by a.create_dt desc
)


来源:https://stackoverflow.com/questions/25789703/ordering-by-a-field-not-in-the-select-statement-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!