CREATE TABLE `cc_comment_master` (
`ID` int(11) DEFAULT NULL,
`DRAFT_SALESDOC_HEADER_ID` int(11) DEFAULT NULL,
`PRODUCT_ID` int(11) DEFAULT NULL,
`PRODUCT_NUMBER` varchar(50) DEFAULT NULL,
`COMMENT_DESC` varchar(100) DEFAULT NULL,
`COMMENT_BY` varchar(50) DEFAULT NULL,
`COMMENT_ON` datetime DEFAULT NULL,
`MODIFIED_BY` varchar(100) DEFAULT NULL,
`MODIFIED_ON` datetime DEFAULT NULL,
`CREATED_BY` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `cc_comment_master`(`ID`,`DRAFT_SALESDOC_HEADER_ID`,`PRODUCT_ID`,`PRODUCT_NUMBER`,`COMMENT_DESC`,`COMMENT_BY`,`COMMENT_ON`,`MODIFIED_BY`,`MODIFIED_ON`,`CREATED_BY`)
values (1,1,1,'abc','first','test','2016-01-12 10:43:48','test',NULL,'test'),(2,2,2,'def','second','test','2016-01-12 10:43:53','test',NULL,'test'),(3,3,3,'xyz','third','test','2016-01-12 10:43:56','test',NULL,'test'),(4,4,4,'pqr','four','test','2016-01-12 10:44:33','test',NULL,'test');
查询:
declare @comments varchar(max)
set @comments = ''
Select
@comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-'
from
CC_COMMENT_MASTER c
where
c.DRAFT_SALESDOC_HEADER_ID = 1
and PRODUCT_NUMBER = 'abc'
order by
c.COMMENT_ON desc --order by not working
select @comments;
我想选择一个字符串中附加的所有 COMMENT_DESC,按 COMMENT_ON 降序排列。
如果没有 order by 子句,我将在一个字符串中按 asc 顺序获取所有 COMMENT_DESC。当我尝试通过 COMMENT_ON desc 订购时,它不起作用。
输出:
first-COMMENT_SEPERATOR-
预期输出:
first-COMMENT_SEPERATOR-second-COMMENT_SEPERATOR-third--COMMENT_SEPERATOR-
错误:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
最佳答案
试试这个
declare @comments varchar(max)
set @comments = ''
Select
@comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-'
from
(select top 100 percent * from CC_COMMENT_MASTER c order by COMMENT_ON desc) as t
select @comments;
关于mysql - Order by 子句不适用于此查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736224/