简体   繁体   English

如何在T-sql中使用逗号分隔的1列值或sql语句中生成多行

[英]how to produce multiple rows into 1 column value or sql statement with comma seperated in T-sql

ColumnName  IsOrdered    Seq_ID
ABC          2              2
DEF          1              1
GHI          0             NULL
JKL          1              4
MNO          1              3
PQR          0              5

I have a table (table1) in the database with above values stored in it. 我在数据库中有一个表(table1),其中存储了以上值。

Note: - 注意: -

I. Is_Ordered column : 2 --> Desc; I. Is_Ordered专栏 :2 - > Desc; 1 --> Asc; 1 - > Asc; 0 --> Default. 0 - >默认。

II. II。 Seq_ID column : Column names 'order by' sequence Seq_ID列 :列名称'顺序'序列

These values are stored in the above table by user.(ie on User interface). 这些值由用户存储在上表中(即在用户界面上)。 I want to produce a 'order by' clause from the multiple rows to a single statement with comma ',' seperated (one single column). 我想从多行生成一个'order by'子句到一个带逗号','分隔(单个列)的语句。

eg: select * from Table1 order by DEF asc, ABC desc, MNO asc, JKL asc 例如:从表1中选择*由DEF asc,ABC desc,MNO asc,JKL asc

Here I want to write a sql statement to produce just the order by statement as above shown ie (order by DEF asc, ABC desc, MNO asc, JKL asc) 这里我想编写一个sql语句来生成如上所示的order by语句, ie (order by DEF asc, ABC desc, MNO asc, JKL asc)

Here you will notice that GHI column and PQR columns are not included since these two are not selected in the order by selections in the user interface. 在这里,您将注意到GHI列和PQR列未包括在内,因为这两个列未按用户界面中的选择顺序选择。

I thank you in advance who tried to understand my question and given an appropriate solution for this. 我事先感谢你试图理解我的问题并给出了适当的解决方案。

Hope this helps 希望这可以帮助

DECLARE @OrderBySetting VARCHAR(max) = ''
DECLARE @OrderByString VARCHAR(max) = ''

DECLARE MY_CURSOR CURSOR
FOR  SELECT  ColumnName + ' ' + 
case IsOrdered  
    WHEN 1 THEN 'ASC'
    WHEN 2 THEN 'DESC'
    END
    + ','
FROM         Table1
WHERE     (IsOrdered <> 0)
ORDER BY Seq_ID DESC

OPEN My_Cursor 

Fetch NEXT FROM MY_Cursor INTO @OrderBySetting

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @OrderByString = @OrderBySetting + @OrderByString


FETCH NEXT FROM MY_Cursor INTO @OrderBySetting
END
CLOSE MY_Cursor
DEALLOCATE MY_Cursor

SET @OrderByString = 'SELECT * FROM TABLE1 ORDER BY ' + SUBSTRING(@OrderByString, 1, LEN(@OrderByString)-1)

Here you go (may need to add a CAST) 你去(可能需要添加一个CAST)

SELECT
    'ORDER BY ' +
      SUBSTRING(
      (
      SELECT
          ',' + ColumnName + 
               CASE IsOrdered  
                 WHEN 1 THEN 'ASC'
                 WHEN 2 THEN 'DESC'
               END
      FROM
          MyTable
      WHERE
          IsOrdered > 0 -- why have "IsIncluded" column ?
      ORDER BY
          Seq_ID
      FOR XML PATH ('')
      )
      , 2, 7999)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM