我有一个包含行的表(TABLE)。
我希望查询在列LIBELLE重复时从不同的行中选择不同的值。
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
预期结果:
LIBELLE DEBIT CREDIT DATE
LIB1 500 20 15/04/2019
LIB2 100 15 16/04/2019
所以从第一行开始,我想从第三行中选择借方值和CREDIT的值。
答案 0 :(得分:0)
尝试使用GROUP BY,请注意尚不清楚您是跨日期还是同一日期选择相同的Libelle:
对于每个日期重复
SELECT Libelle, SUM(Debit) As Debit, SUM(Credit) As Credit, MAX(Date) As Date
FROM TABLE
GROUP BY Libelle, Date
对于跨日期的重复
kind: ConfigMap
apiVersion: v1
metadata:
name: udp-services
namespace: ingress-nginx
labels:
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/part-of: ingress-nginx
data:
5684: "dev/dip-dc:5684"
答案 1 :(得分:0)
您可以尝试...
如果您要先借方又要最后贷方,则根据您的共同情况,其余值均为空。
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
。
答案 2 :(得分:0)
您也可以使用子查询来获取输出:-
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;
答案 3 :(得分:0)
我建议:
select Libelle,
max(Debit),
max(Credit),
max(Date)
from TABLE
由于分组列中的sum
,我不鼓励使用null
,因为它会返回null
。
max
将返回唯一的值,而不是null
(与min
相同)。