SQL:计数以及表中的行值

时间:2017-05-15 14:17:35

标签: sql sql-server tsql

简而言之,我有一个有5列的表,而Col2的值有x1,x2,x3 ......

我想要一个类似于下面的输出:

第1行=第1列|伯爵(第2栏)| Col3 | Col4 | Col5 | (X1,X2,X3,X4,..)

第2行=第1列|伯爵(第2栏)| Col3 | Col4 | Col5 | (X4,X8,X23,X44,..) 等等

实现它的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

使用for xml:

select  col1, 
        col2 = count(col2), 
        col3, col4, col5, 
        col6 = replace(replace( REPLACE( (select c = col2 from mytable _t where _t.col1 = t.col1 and _t.col3 = t.col3 and _t.col4 = t.col4 and _t.col5 = t.col5
                                    for xml auto),'<_t c="',''),'"/>',', '),'<_t/>','')
from mytable t
group by col1, col3, col4, col5

或创建一个连接函数:

CREATE FUNCTION fn_str_agg 
(
    @col1 int, @col3 int, @col4 int, @col5 int
)
RETURNS varchar(max)
AS
BEGIN
    declare @result varchar(max)=''

    SELECT @result = @result+',' + col2
    FROM myTable
    where col1 = @col1 and col3 = @col3 and col4 = @col4 and col5 = @col5
    return @result
END

select  col1, 
        col2 = count(col2), 
        col3, col4, col5, 
        col6 = dbo.fn_str_agg(col1, col3, col4, col5)
from mytable t
group by col1, col3, col4, col5