简体   繁体   中英

Select values from different rows

I have a table (TABLE) which contains rows.

I want a query to pick different value from different rows when the column: LIBELLE is repeated.

EX :

LIBELLE  DEBIT  CREDIT   DATE
LIB1     500     NULL  15/04/2019
LIB1     NULL    NULL  15/04/2019
LIB1     NULL    20    15/04/2019
LIB2     100     NULL  16/04/2019
LIB2     NULL    NULL  16/04/2019
LIB2     NULL    150   16/04/2019

Expected result :

LIBELLE  DEBIT  CREDIT    DATE
LIB1     500      20   15/04/2019
LIB2     100      15   16/04/2019

So from the first row, i want to pick value of debit, & value of CREDIT from the 3rd row.

Try using GROUP BY, note it isn't clear whether you should select the same Libelle across dates or for one date:

For duplicates for each date

   SELECT Libelle, SUM(Debit) As Debit, SUM(Credit) As Credit, Date
    FROM TABLE
    GROUP BY Libelle, Date

For duplicates across dates

   SELECT Libelle, SUM(Debit) As Debit, SUM(Credit) As Credit, MAX(Date) As Date
    FROM TABLE
    GROUP BY Libelle, Date

You may try this...

If you want first debit and last credit, as per your shared case rest of the values are null.

  select distinct Libelle, max(isnull(debit,0)) as Debit, max(isnull(credit,0)) as Credit , Date from table group by Libelle, date

If you want the sum of all debit and credit for each date

 select distinct Libelle, sum(isnull(debit,0)) as Debit, sum(Isnull(credit,0)) as Credit, date from table group by Libelle, date

Not very good code but works for you, for case of taking only debit from first row and credit from last row.

 ; with cte as ( select row_number() over (partition by Libelle order by date,(select 100)) as Slno, Libelle, isnull(debit,0) as debit, isnull(credit,0) as credit, date from table )
 select c.Libelle , c.debit, t.credit, c.date from 
 (select top 1 * from cte order by slno) as c 
 inner join (select top 1 * from cte order by slno desc) as t on c.date=t.date and c.Libelle=t.Libelle

BTW, don't you have an Id column in table to get your first and last value if yes then replace select 100 with that column name.

you can use sub-query as well to get the output:-

 SELECT t.libelle,
         (SELECT t1.debit FROM table t1
           WHERE t1.libelle = t.libelleAND debitIS NOT NULL) debit,
         (SELECT t2.credit FROM table t2
           WHERE t2.libelle = t.libelleAND creditIS NOT NULL) credit,
         t.date
    FROM table t
   GROUP BY t.libelle, t.date;

I would suggest:

select Libelle,
       max(Debit),
       max(Credit),
       max(Date)
from TABLE

I would discourage from using sum as it would return null because of the null in grouped columns.

max will return the only value which is not null (same with min ).

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