SQL query with return columns based on grouping

前端 未结 2 874
无人共我
无人共我 2021-01-15 12:51

I have this select as follows:

SELECT SUBSTRING(Col1, 1, 3)          AS \'Series\',
       b.Col2,
       CAST(c.Price * c.Qty AS MONEY) AS Total
FROM   tabl         


        
相关标签:
2条回答
  • 2021-01-15 13:11

    Please try the following codes. You have to use PIVOT query.

    create table TableName (Series varchar(20),col2 varchar(10), price decimal(8,2))
    
    insert into TableName values ('105','C50',30)
    insert into TableName values ('105','C50',10)
    
    insert into TableName values ('105','C53',20)
    insert into TableName values ('105','C53',30)
    
    
    SELECT Series,
           [C50],
           [C53]
    FROM   (SELECT Series,
                   col2,
                   price
            FROM   TableName) AS SourceTable 
                       PIVOT ( SUM(price) FOR col2 IN ([C50],
                                                       [C53])
           ) AS PivotTable;  
    
    0 讨论(0)
  • 2021-01-15 13:11

    For potential null value for col2, please try the following code.

    Note: you may need to adjust @PIV_COL size depend on how many distinct records of col2. I used 'NO_VAL' for potential NULL value of col2.

    insert into TableName  values ('105',NULL,100)
    
    
    DECLARE @PIV_COL VARCHAR(100)
    
    SELECT @PIV_COL = STUFF(
    (
        SELECT DISTINCT ',[' + ISNULL(COL2,'NO_VAL') + ']'
        FROM TableName  C   
        FOR XML PATH('')
    ), 1, 1, '') 
    
    
    EXEC
    ('
        SELECT Series,' + @PIV_COL + '
        FROM   (
                    SELECT Series,
                       ISNULL(COL2,''NO_VAL'') col2,
                       price
                FROM   TableName ) AS SourceTable 
                           PIVOT ( SUM(price) FOR col2 IN ('+ @PIV_COL + ')
        ) AS PivotTable
    ')
    
    0 讨论(0)
提交回复
热议问题