基于列中值的分类SQL

时间:2016-10-28 16:28:38

标签: sql sql-server sql-server-2008

对你们中的一些人来说可能很简单,但我很难过。谢谢你的帮助!

我没有任何接近工作的SQL。

以下是我正在尝试的结果:

我想根据C列中的值创建下面的D列,按B列分组并汇总A列:

Column a||  Column b  ||Column c  ||Column d
$20         john        1           1&2
$30         john        2           1&2 
$20         sally       1           1
$20         suzie       2           2
$20         mary        3           3
$20         bob         1           1&2
$10         bob         2           1&2
$20         karen       1           1&3
$10         karen       3           1&3

2 个答案:

答案 0 :(得分:1)

由于您有两个SQL-Server标记,我假设SQL Server

Declare @YourTable table (colA int,colB varchar(50),colC int)
Insert Into @YourTable values
(20,'john',1),
(30,'john',2),
(20,'sally',1),
(20,'suzie',2),
(20,'mary',3),
(20,'bob',1),
(10,'bob',2),
(20,'karen',1),
(10,'karen',3)

Select *
      ,ColD = Replace((Select String=Stuff((Select ',' +cast(colC as varchar(25)) From  @YourTable Where ColB=A.ColB For XML Path ('')),1,1,'') ) ,',','&')
 From @YourTable A

返回

enter image description here

答案 1 :(得分:0)

对于SQL Server,您可以使用公用表表达式和FOR XML。以下示例查询将按B分组,组合C列并提供A的总和。

WITH MyTable (A,B,C)
AS
(
    SELECT A,B,C
    FROM TestT
)

SELECT t1.B, SUM(a) AS SumOfA,
    STUFF((
        SELECT DISTINCT ', ' + CAST(C AS VARCHAR(MAX))
        FROM MyTable t2
        WHERE t1.B = t2.B
        FOR XML PATH('')), 1, 1, '') AS D

FROM MyTable t1

GROUP BY t1.B

这将产生以下结果:

B       SumOfA  D
bob     30      1, 2
john    50      1, 2
karen   30      1, 3
mary    20      3
sally   20      1
suzie   20      2