我正面临一个复杂的情况,我知道可以解决问题的方法,但我的派生表中的order by子句搞乱了自定义排序。以下是我的输入和输出详细信息以及我尝试过的内容。
架构: - 输入: -
CREATE TABLE Test( Rowname VARCHAR(10), Col1 DATETIME, Col2 DATETIME, Col3 DATETIME, Col4 DATETIME );
INSERT INTO Test VALUES( 'Row1', '2016-01-14', '2016-01-08', '2016-01-30', '2016-01-01' );
INSERT INTO Test VALUES( 'Row2', '2016-01-02', '2016-01-01', '2016-01-18', '2016-01-15' );
预期输出: -
RowName Result
Row1 Col4,Col2,Col1,Col3
Row2 Col2,Col1,Col4,Col3
我尝试了什么?
WITH CTE(RowName,Colmn,RN) AS
(
SELECT RowName,Colmn,ROW_NUMBER() OVER( PARTITION BY RowName ORDER BY RowName ) AS RN
FROM
(
( SELECT RowName,Col1 AS Col,'Col1' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col2 AS Col,'Col2' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col3 AS Col,'Col3' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col4 AS Col,'Col4' AS Colmn FROM Test )
) Z
ORDER BY RowName,Col
)
SELECT RowName,
MAX( ( CASE WHEN RN = 1 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 2 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 3 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 4 THEN Colmn END ) ) AS Result
FROM CTE
GROUP BY RowName;
注意: -
内部查询/派生表中的ORDER BY RowName,Col子句失败,因为SQL Server中不允许这样做。如果我不使用此ORDER BY,那么如何在不使用ORDER BY子句的情况下执行自定义排序?
答案 0 :(得分:1)
您的order by
应在over
子句中定义:
WITH CTE(RowName,Colmn,RN) AS
(
SELECT
RowName,Colmn,ROW_NUMBER() OVER(
PARTITION BY RowName
ORDER BY RowName, Col -- add Col here
) AS RN
FROM
(
( SELECT RowName,Col1 AS Col,'Col1' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col2 AS Col,'Col2' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col3 AS Col,'Col3' AS Colmn FROM Test )
UNION ALL
( SELECT RowName,Col4 AS Col,'Col4' AS Colmn FROM Test )
) Z
-- ORDER BY RowName,Col -- remove this line
)
SELECT RowName,
MAX( ( CASE WHEN RN = 1 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 2 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 3 THEN Colmn END ) ) + ',' +
MAX( ( CASE WHEN RN = 4 THEN Colmn END ) ) AS Result
FROM CTE
GROUP BY RowName;
答案 1 :(得分:0)
如果你在row_number中将col添加到订单中,它将按你想要的顺序排序。
ROW_NUMBER() OVER( PARTITION BY RowName ORDER BY RowName, col )
答案 2 :(得分:0)
x[, A := Reduce(function(x,y) paste(x,y,sep=","), .SD), .SDcols = columnsSelected]