我有一个很长的列表,看起来很粗糙,如下(列名和数据匿名化(
ID | ID2 | Value
1 | 5 | 900
1 | 7 | 400
2 | 2 | 100
2 | 8 | 800
2 | 2 | 200
3 | 4 | 100
3 | 5 | 300
4 | 8 | 750
4 | 5 | 900
我所追求的是每列" ID" 1行的能力,该列具有最低ID2的值的总和。
作为一个例子,上表将变成:
ID | ID2 | Value
1 | 5 | 900
2 | 2 | 300
3 | 4 | 100
4 | 5 | 900
我尝试了几种脚本变体,但没有成功。这是我当前的清理代码:
SELECT res.id
, min(id2) as rdk
,sum(value)
FROM x as res
left join y as clai
on res.id = clai.id
left join z as cal
on clai.col99 = cal.col99
group by
res.id
但是,总和是" ID"的所有价值,而不仅仅是最低的" ID2"?
任何帮助!
尝试以下操作: -
select a.ID,a.ID2, sum(Value) as Value
from
your_table_name a
inner join
(
SElect ID, min(ID2) as ID2
from your_table_name
group by ID
) b
on a.ID=b.ID and a.ID2=b.ID2
group by a.ID,a.ID2;
希望这会有所帮助: - (
尝试一下:
select a.*,b.value from
(select id,min(id2) as id2
from have
group by id) a
left join
(select id,id2,sum(value) as value
from have
group by id,id2) b
on a.id=b.id and a.id2=b.id2;
我的输出:
id |id2 |value
1 |5 |900
2 |2 |300
3 |4 |100
4 |5 |900
请在任何查询时让我知道。
我将在这里放置解决方案:(
with ExampleData as (
select 1 ID1, 5 ID2, 900 Value union all
select 1 ID1, 7 ID2, 400 Value union all
select 2 ID1, 2 ID2, 100 Value union all
select 2 ID1, 8 ID2, 800 Value union all
select 2 ID1, 2 ID2, 200 Value union all
select 3 ID1, 4 ID2, 100 Value union all
select 3 ID1, 5 ID2, 300 Value union all
select 4 ID1, 8 ID2, 750 Value union all
select 4 ID1, 5 ID2, 900 Value)
select ID1,
ID2,
Value
from (
select ID1,
ID2,
SUM(VALUE) VALUE,
ROW_NUMBER() OVER (partition by ID1 order by ID2) R
from ExampleData
group by ID1,ID2
) T where T.R=1
如果您的表被称为t1:
SELECT t1.id, t1.id2, SUM(t1.value)
FROM t1 INNER JOIN
(
SELECT id, min(id2) minId
FROM t1
GROUP BY id
) A
ON A.id = t1.id AND A.minId = t1.id2
GROUP BY t1.id, t1.id2