[英]Get all records having count from one table is greater than sum of other table
[英]Get record ids from groups where the sum of one of the field of their records is greater than
我有這樣的記錄:
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
我想獲取由ForeignKey和Level分組的組的每個記錄的ID,其中組記錄的ValueA值的總和除以ValueB值的總和大於0.5
在這種情況下,我想檢索(3 + 2 + 10 + 20)/(10 + 10 + 20)= 0.8的前三個記錄的ID
這是到目前為止我得到的:
select
ForeignKey,
SUM(ValueA) as ValueASum,
SUM(ValueB) as ValueBSum,
from tableA
group by ForeignKey
having (SUM(ValueA) / SUM(ValueB) > 0.5)
結果是
ForeignKey ValueASum ValueBSum
1001 32 40
從這一點上如何獲取記錄的ID? 如果我在選擇中添加ID,則必須對其進行分組,然后為每個記錄分組。
謝謝你的時間
嗯,怎么樣
select id from your_table where foreignkey = 1001
處理多個查詢有問題嗎?
如果需要,可以執行子查詢:
select id from your_table where foreignkey in ( select foreignkey from ( <yourQuery> ) sq);
更新:
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
我添加where level = 1
只是因為您給定的結果集不是執行查詢時得到的結果。
看到它在sqlfiddle中實時工作。
您的方向是正確的,但是如果您希望每個“級別”都需要它,則還需要將其添加到您的組中。
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
這將給出與合格條件匹配的所有值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.