简体   繁体   中英

How can i consolidate this SQL rows?

Let's say I have a simple table:

CREATE TABLE [dbo].[Lease]
(
    [unitcode] [NVARCHAR](50) NOT NULL,
    [chargecode] [NVARCHAR](50) NOT NULL,
    [Jan] [INT] NULL,
    [feb] [INT] NULL,
    [mar] [INT] NULL
) ON [PRIMARY]
GO

INSERT INTO Lease (UNITCODE, CHARGECODE, JAN, FEB, MAR)
VALUES (001, 'RENT', 100, null, null),
       (001, 'RENT', null, 200, null),
       (001, 'RENT', null, null, 300),
       (001, 'PARKING', 50, 50, 50);

I am trying to consolidate the 'rent' columns into one row - this row would show all the non null values for jan, feb and mar. Any thoughts on how I can do this?

Here is the current output:

在此处输入图片说明

Here is what I am trying to achieve:

在此处输入图片说明

Thank you, Asif

I think your looking for a simple aggregation and Group By

Assuming you want RENT as the top line, I added the conditional sort.

Example

Select unitcode
      ,chargecode
      ,Jan = sum(Jan)
      ,Feb = sum(Feb)
      ,Mar = sum(Mar)
 From lease
 Group By unitcode
         ,chargecode
 Order By unitcode
         ,case when chargecode='Rent' then 0 else 1 end
         ,chargecode

Returns

unitcode    chargecode  Jan Feb Mar
1           RENT        100 200 300
1           PARKING     50  50  50

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