在select语句生成的列上排序BY

时间:2014-10-23 15:44:37

标签: sql

我正在运行此查询:

SELECT
     claims.rID
    ,claims.client
    ,clients.cName
    ,cur.currency
    ,carriers.scac
    ,carriers.cName
    ,claims.client+claims.counter
    ,claims.dateOn
    ,(SELECT top 1 errorCode FROM entries WHERE entries.rID=claims.rID) as errorCode
    ,(SELECT SUM(refundDue) FROM entries WHERE entries.rID=claims.rID) as amount
    ,auditors.initials

FROM claims
    INNER JOIN clients ON clients.code = claims.client 
    INNER JOIN currency cur ON claims.currency = cur.currencyID 
    INNER JOIN entries ON claims.rID = entries.rid
    INNER JOIN carriers ON carriers.carrierID = claims.carrierID
    INNER JOIN auditors ON claims.auditorID=auditors.auditorID

GROUP BY 
     claims.rID
    ,claims.client
    ,claims.counter
    ,claims.dateOn
    ,carriers.scac
    ,carriers.cName
    ,clients.cName
    ,cur.currency
    ,auditors.initials
    ,errorCode

ORDER BY errorCode ASC

重点应放在orderBy errorCode上。出于某种原因,它实际上并不是由errorCode按字母顺序排序。关于为什么的任何想法?

1 个答案:

答案 0 :(得分:1)

大多数数据库不允许您在GROUP BY,ORDER BY和WHERE子句中使用SELECT列表中创建的别名。相反,您必须重复SELECT列表中使用的表达式:

SELECT
    claims.rID,
    ...,
    (SELECT top 1 errorCode FROM entries WHERE entries.rID=claims.rID) AS errorCode,
    ...
FROM
   claims INNER JOIN ...
GROUP BY
    claims.rID,
    ...,
    (SELECT top 1 errorCode FROM entries WHERE entries.rID=claims.rID)
ORDER BY
    (SELECT top 1 errorCode FROM entries WHERE entries.rID=claims.rID) ASC

但我认为最好在FROM子句中使用子选择作为数据源:

SELECT
    claims.rID,
    ...,
    E.errCode, E.amount,
    ...
FROM claims
    INNER JOIN clients ON clients.code = claims.client 
    INNER JOIN currency cur ON claims.currency = cur.currencyID 
    INNER JOIN (SELECT rID, MIN(errorCode) AS errCode, SUM(refundDue) AS amount
                FROM entries
                GROUP BY rID) AS E
        ON claims.rID = E.rid
    INNER JOIN carriers ON carriers.carrierID = claims.carrierID
    INNER JOIN auditors ON claims.auditorID=auditors.auditorID
GROUP BY
    claims.rID,
    ...,
    E.errCode
ORDER BY
    E.errCode ASC

请注意,我也包含了SUM(refundDue) AS amount。如果entries中的错误代码为空,请使用MAX(errorCode)代替MIN(errorCode)