GROUP BY月份编号和年份

时间:2013-06-07 17:11:09

标签: tsql sql-server-2012-express

我有一个产生月号和年份的查询。我想按月号和年份对结果进行排序。因此,月份1,2012年是第一个,然后是2012年,所以依此类推。我怎么能这样做?

SELECT
    a.Vendor,
    vn.ACNAME,
    a.FiscalMonthNum,
    a.FiscalYear,
    a.ModDate,
    a.QtySold,
    a.ExtCost
FROM
    dbo.S2K_VEND vn
    INNER JOIN
(SELECT
    sd.IFPRVN AS Vendor,
    fc.FiscalMonthNum,
    fc.FiscalYear,
    sd.Mod_Date As ModDate,
    SUM(sd.SBQSHP) AS QtySold,
    SUM(sd.SBEPRC) AS ExtCost
FROM
    dbo.SalesData sd
    LEFT OUTER JOIN dbo.FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
GROUP BY
    sd.IFPRVN,
    fc.FiscalMonthNum,
    fc.FiscalYear,
    sd.Mod_Date
)a
ON vn.ACVEND = a.Vendor
ORDER BY
    a.FiscalMonthNum

2 个答案:

答案 0 :(得分:3)

你说的是:

order by FiscalMonthNum asc , -- Major order. Use 'asc' if you want it in ascending sequence (or simply omit it as that is the default)
         FiscalYear desc -- Minor order. Use 'desc' if you want it in descending sequence

答案 1 :(得分:2)

尝试

SELECT
    a.Vendor,
    vn.ACNAME,
    a.FiscalMonthNum,
    a.FiscalYear,
    a.ModDate,
    a.QtySold,
    a.ExtCost
FROM
    dbo.S2K_VEND vn
    INNER JOIN
(SELECT
    sd.IFPRVN AS Vendor,
    fc.FiscalMonthNum,
    fc.FiscalYear,
    sd.Mod_Date As ModDate,
    SUM(sd.SBQSHP) AS QtySold,
    SUM(sd.SBEPRC) AS ExtCost
FROM
    dbo.SalesData sd
    LEFT OUTER JOIN dbo.FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
GROUP BY
    sd.IFPRVN,
    fc.FiscalMonthNum,
    fc.FiscalYear,
    sd.Mod_Date
)a
ON vn.ACVEND = a.Vendor
ORDER BY
    a.FiscalMonthNum, a.FiscalYear