SELECT UNION ALL ORDER BY查询中的GROUP BY子句错误

时间:2017-09-27 11:42:50

标签: sql-server select group-by union-all

我正在尝试在SQL SERVER中的union all之后对表进行排序

我已经阅读了几个地方(例如:How to use order by with union all in sql?),我需要写一下:

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

但是,我一直收到错误说:

Column 'dum.var' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

虽然我没有任何GROUP BY查询...

有人可以向我解释一下吗?

3 个答案:

答案 0 :(得分:1)

感谢上面评论中的Tyron78,我发现了这个错误。

实际查询是:

SELECT * 
FROM
(
SELECT
        *
FROM
#TABLE1
UNION ALL
SELECT
        *
FROM
#TABLE2
) AS Z
ORDER BY sum([Units]) DESC, [Distance], [ID], [Product]

问题在于sum(),因为我之前已经在table1和table2中进行了总结。 所以好的查询如下:

SELECT * 
FROM
(
SELECT
        *
FROM
#TABLE1
UNION ALL
SELECT
        *
FROM
#TABLE2
) AS Z
ORDER BY [Units] DESC, [Distance], [ID], [Product]

全部谢谢!

答案 1 :(得分:0)

您需要提供要对结果集进行排序的列名。

SELECT  * 
FROM 
    (
        SELECT * FROM TABLE_A 
        UNION ALL 
        SELECT * FROM TABLE_B
    ) dum
order by <column_name> [asc|desc]

两个表中必须相同。

答案 2 :(得分:0)

// B2CPopup.js
import $ from 'jquery'

export default class B2CPopup {
  constructor ({ _id, options }, html) {
    this._id = _id
    this.options = options
    this.html = html
  }

  start = () => {}
  createOptions = () => {}
  prependHTMLToDOM = () => $(this.html).prependTo('body')

  show = () => {}
}