如何做一个" Order By"按月和年?

时间:2015-08-06 15:33:42

标签: sql sql-server ssms-2014

代码:

SELECT

CONVERT(VARCHAR(10),Due_Date,101) AS Due_Date,
COST_PER_ACRES,
CASE WHEN Due_Amount IS NOT NULL AND Lease_Amount IS NOT NULL THEN '$' + CONVERT(VARCHAR(20),CAST(Due_Amount - Lease_Amount AS MONEY),1)
WHEN Due_Amount IS NULL THEN '$0.00' ELSE '$' + CONVERT(VARCHAR(20),CAST(Due_Amount AS MONEY),1) END AS RENTAL_AMOUNT_DUE,
CONVERT(VARCHAR(10),CHECK_DATE,101) AS Check_Date

FROM tblpayments PH 
LEFT JOIN tblcheck CD
    ON PH.ID = CD.lease_obligation_ID

WHERE PH.PAYMENT_TYPE_ID = 1657 AND PH.LEASE_ID = 76

ORDER BY YEAR(Due_Date)

我想知道如何获得以下输出:

enter image description here

我目前的输出:

enter image description here

1 个答案:

答案 0 :(得分:2)

您只需将month()添加到order by即可。所以我想你想要:

ORDER BY MONTH(ph.Due_Date), YEAR(ph.Due_Date)

(我不知道专栏的来源。我只是在猜ph。)

在您的情况下,您也可以这样做:

ORDER BY Due_Date

Due_Date基于列别名进行解释。它似乎是您想要订购的。

注意:将列重命名为与现有列相同可能会导致ORDER BY混淆。