简体   繁体   中英

SQL Server select all rows into single column with repeating column names

I have this code and its temporary tables so you can run it.

    create table #hourly_sales(
    id int identity(1,1),
    tenant_code varchar(13),
    hour_code int,
    net_sale_per_hour decimal(18,2)
    )


    insert into #hourly_sales(tenant_code,hour_code,net_sale_per_hour)
    values('1234567890000',1,200),('1234567890000',2,500),('1234567890000',3,400)


    select * from #hourly_sales

    drop table #hourly_sales    

This will give you this output

  id          tenant_code   hour_code   net_sale_per_hour
  ----------- ------------- ----------- -------------------
  1           1234567890000 1           200.00
  2           1234567890000 2           500.00
  3           1234567890000 3           400.00

I wanted them all to select in a single column with the tenant code grouped and net sale is summed up

My goal:

  id          tenant_code   hour_code   net_sale_per_hour hour_code net_sale_per_hour
  -----------------------------------------------------------------------
  1           1234567890000 1           200.00            2         500     

  hour_code net_sale_per_hour   total_net_sale
  -----------------------------------------------------------------------
  3         400                 

and so on

My attempt:

    declare @sum decimal(18,2);
    set @sum = (select sum(net_sale_per_hour) from #hourly_sales);

    select TOP 1
        id,
        tenant_code,
        hour_code,
        net_sale_per_hour,
        @sum
    from #hourly_sales

This is all I got for you I need your help.

Sometimes if you have limited columns, only 24, it is easier just to spell it out.

select tenant_code, 
    sum(case when hour_code = 1 then net_sale_per_hour else null end) as '01',
    sum(case when hour_code = 2 then net_sale_per_hour else null end) as '02',
    sum(case when hour_code = 3 then net_sale_per_hour else null end) as '03'
    from #hourly_sales
    group by tenant_code

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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