按UNION查询中的特定值排序表

时间:2016-04-20 13:17:32

标签: sql

我有一个需要按特定值排序列的查询。目前,对于act_code,费用具有“+”值,付款具有“ - ”值,奖励具有“=”值。我需要订单是费用,付款,奖励,但我得到付款,费用,奖励。运行查询时,我收到“无效的列名tcodes.act_code”。这是我的疑问:

    SELECT tmptract.soc_sec, 
           name.last_name, 
           name.first_name, 
           name.mi, 
           address.st_addr, 
           address.add_addr, 
           address.add_add2, 
           address.city, 
           address.state, 
           address.zip, 
           tcodes.act_code, 
           '' as employee_soc_sec, 
           2 as bill_type
      FROM tmptract, 
           name, 
           address, 
           tcodes, 
           transact
     WHERE tmptract.soc_sec = name.soc_sec
       AND address.soc_sec = name.soc_sec
       AND tcodes.tcodes = transact.tcodes
       AND tmptract.token = '#session.token#'
  ORDER BY name.last_name, 
           name.first_name, 
           name.mi, 
           tmptract.soc_sec, 
           bill_type,
           (CASE 
              WHEN tcodes.act_code = '+' THEN '1'
              WHEN tcodes.act_code = '-' THEN '2'
              WHEN tcodes.act_code = '=' THEN '3' 
              ELSE tcodes.act_code 
            END)

1 个答案:

答案 0 :(得分:0)

选择代码时,你必须这样做..

SELECT tmptract.soc_sec, 
           name.last_name, 
           name.first_name, 
           name.mi, 
           address.st_addr, 
           address.add_addr, 
           address.add_add2, 
           address.city, 
           address.state, 
           address.zip, 
           tcodes.act_code,
            (CASE 
              WHEN tcodes.act_code = '+' THEN '1'
              WHEN tcodes.act_code = '-' THEN '2'
              WHEN tcodes.act_code = '=' THEN '3' 
              ELSE tcodes.act_code 
            END) as TCode, 
           '' as employee_soc_sec, 
           2 as bill_type
      FROM tmptract, 
           name, 
           address, 
           tcodes, 
           transact
     WHERE tmptract.soc_sec = name.soc_sec
       AND address.soc_sec = name.soc_sec
       AND tcodes.tcodes = transact.tcodes
       AND tmptract.token = '#session.token#'
  ORDER BY name.last_name, 
           name.first_name, 
           name.mi, 
           tmptract.soc_sec, 
           bill_type,
           TCode