[英]Select values from different rows
我有一个包含行的表(TABLE)。
我希望查询在列:LIBELLE重复时从不同的行中选择不同的值。
例如:
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
预期结果 :
LIBELLE DEBIT CREDIT DATE
LIB1 500 20 15/04/2019
LIB2 100 15 16/04/2019
因此,从第一行开始,我想从第三行中选择借方值和CREDIT的值。
尝试使用GROUP BY,请注意尚不清楚您是应跨日期还是针对同一日期选择相同的Libelle:
对于每个日期重复
SELECT Libelle, SUM(Debit) As Debit, SUM(Credit) As Credit, Date
FROM TABLE
GROUP BY Libelle, Date
跨日期重复
SELECT Libelle, SUM(Debit) As Debit, SUM(Credit) As Credit, MAX(Date) As Date
FROM TABLE
GROUP BY Libelle, Date
你可以试试这个...
如果您要先借方又要最后贷方,则根据您的共同情况,其余值均为空。
select distinct Libelle, max(isnull(debit,0)) as Debit, max(isnull(credit,0)) as Credit , Date from table group by Libelle, date
如果您想要每个日期的所有借方和贷方之和
select distinct Libelle, sum(isnull(debit,0)) as Debit, sum(Isnull(credit,0)) as Credit, date from table group by Libelle, date
不是很好的代码,但是对您有用,例如仅从第一行借记而从最后一行记入贷方的情况。
; 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
顺便说一句,如果表中没有ID列来获取您的第一个值和最后一个值,请用该列名替换select 100
。
您也可以使用子查询来获取输出:
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;
我会建议:
select Libelle,
max(Debit),
max(Credit),
max(Date)
from TABLE
我不鼓励使用sum
,因为分组列中的null
会返回null
。
max
将返回唯一不为null
(与min
相同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.