返回每个 ID 的最少行数 SQL

Returning Minimum Rows For Each ID SQL

我有一个很长的列表,大致如下所示(列名和数据匿名)

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

而我所追求的是每列生成 1 行的能力 "ID",它具有最低 ID2 的值的总和。

举个例子,上面的table会变成:

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

如果你的 table 被称为 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