联接表上未选择的列上的SQL查询ORDER BY

时间:2018-10-04 12:19:50

标签: sql sql-server sql-order-by

我面临的问题如下,我连接了2个表,我想拉2列(每列1个),但是我想按其中一个表的第三列进行排序,到目前为止,我一直在不成功,这是我尝试过的查询,但无法正常工作。

SELECT
    [Months].[Month] AS 'Name',
    SUM(ISNULL([Documents].[Balance],0)) AS 'Value'
FROM (
    SELECT 
        [Months].[Month],
        SUM(ISNULL([Documents].[Balance],0)),
        MONTH([Documents].[Date])
    FROM
        [Documents]
    LEFT JOIN [Months] ON
        [Months].[MonthNumber] = MONTH([Documents].[Date])
    GROUP BY
        [Months].[Month], MONTH([Documents].[Date])
    ORDER BY
        MONTH([Documents].[Date]) ASC
)

对这个问题有帮助吗?

3 个答案:

答案 0 :(得分:0)

您不需要派生表/子查询。

    SELECT 
        [Months].[Month] AS 'Name',
        SUM(ISNULL([Documents].[Balance],0)) AS 'Value',
        MONTH([Documents].[Date]) AS 'Mth'
    FROM
        [Documents]
    LEFT JOIN [Months] ON
        [Months].[MonthNumber] = MONTH([Documents].[Date])
    GROUP BY
        [Months].[Month], MONTH([Documents].[Date])
    ORDER BY
        Mth ASC

如果仅需要“名称和值”列,则从MONTH([Documents].[Date])中删除SELECT并将ORDER BY更改为ORDER BY MONTH([Documents].[Date])

答案 1 :(得分:0)

为什么在这里需要子查询?您可以JOIN并使用ORDER BY子句:

SELECT m.[Month], SUM(ISNULL(d.[Balance], 0))
FROM [Documents] d LEFT JOIN 
     [Months] m 
     ON m.[MonthNumber] = MONTH(d.[Date])
GROUP BY m.[Month], MONTH(d.[Date])
ORDER BY MONTH(d.[Date]);

但是,order by子句中没有与SELECT语句一起显示的列没有任何意义。

答案 2 :(得分:0)

您必须在选择列表中使用按列排序

SELECT 
        [Months].[Month] AS 'Name',
        SUM(ISNULL([Documents].[Balance],0)) AS 'Value',
        MONTH([Documents].[Date]) AS  dcosdate
    FROM
        [Documents]
    LEFT JOIN [Months] ON
        [Months].[MonthNumber] = MONTH([Documents].[Date])
    GROUP BY
        [Months].[Month], MONTH([Documents].[Date])
    ORDER BY
        MONTH([Documents].[Date])