简体   繁体   中英

Get record ids from groups where the sum of one of the field of their records is greater than

I have records as such:

    Id  ForeignKey  Level   ValueA  ValueB
    1   1001        1       2       10
    2   1001        1       10      10
    3   1001        1       20      20
    4   1001        2       20      30
    5   1002        1       1       100
    6   1003        1       1       100
    7   1004        1       1       100

I want to get the Ids of each record of the groups grouped by ForeignKey and Level where the sum of the group's records' ValueA values divided by the sum of ValueB values is greater than 0.5

In this case, I'd like to retrieve the Id of the three first records as (2 + 10 + 20) / (10 + 10 + 20) = 0.8

Here is what I've got so far:

    select 
    ForeignKey,
    SUM(ValueA) as ValueASum,
    SUM(ValueB) as ValueBSum,
    from tableA 
    group by ForeignKey
    having (SUM(ValueA) / SUM(ValueB) > 0.5)

The result is

    ForeignKey  ValueASum   ValueBSum
    1001        32          40

How do I get the ids of the records from this point? If I add the Id in the select, I must group on it and then have a group for each record.

Thanks for your time

Hm, how about

select id from your_table where foreignkey = 1001

Is something wrong with working with multiple queries?

If you want you can do a subquery:

select id from your_table where foreignkey in ( select foreignkey from ( <yourQuery> ) sq);

UPDATE:

select t.id from Table1 t
inner join 
( 
    select 
    ForeignKey, level,
    SUM(ValueA) as ValueASum,
    SUM(ValueB) as ValueBSum
    from Table1 
where level = 1
    group by ForeignKey, Level
    having (SUM(ValueA) / SUM(ValueB) > 0.5) ) sq
ON t.foreignkey = sq.foreignkey AND t.level = sq.level

I added where level = 1 just because your given resultset not what I get when I execute your query.

See it working live in an sqlfiddle .

You were on the right track, but if you wanted it from each "Level", you would need to add that into your group by also.

select
      tA2.ID,
      tA2.ForeignKey,
      tA2.Level,
      tA2.ValueA,
      tA2.ValueB
   from
      ( select 
              tA.ForeignKey,
              tA.Level,
              SUM(tA.ValueA) as ValueASum,
              SUM(tA.ValueB) as ValueBSum,
           from 
              tableA tA
           group by 
              tA.ForeignKey,
              tA.Level
           having 
              (SUM(tA.ValueA) / SUM(tA.ValueB) > 0.5) ) PreQualified
      JOIN tableA tA2
         on PreQualified.ForeignKey = tA2.ForeignKey
        AND PreQualified.Level = tA2.Level

This would give all values that matched the qualifying condition.

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