我的表格包含字段bytes_in
,mac_src
和mac_dst
。
我想获得字段bytes_in
和mac_src
相等的所有行的字段mac_dst
的总和,然后将此总和从最高到最低排序。返回的Queryset每个mac_src
和mac_dst
值只有一个条目。
换句话说,我需要总结字段bytes_in
,好像mac_src
和mac_dst
是具有相同值的相同字段。
感谢。
+-------------------+-------------------+----------+
| mac_src | mac_dst | bytes_in |
+-------------------+-------------------+----------+
| aa:aa:aa:aa:aa:aa | bb:bb:bb:bb:bb:bb | 10 |
| bb:bb:bb:bb:bb:bb | aa:aa:aa:aa:aa:aa | 20 |
| cc:cc:cc:cc:cc:cc | aa:aa:aa:aa:aa:aa | 30 |
+-------------------+-------------------+----------+
答案 0 :(得分:0)
select mac_src,sum(case when mac_src=mac_dst then bytes_in else null end)
from table
group by mac_src
order by sum(case when mac_src=mac_dst then bytes_in else null end) desc;
答案 1 :(得分:0)
from django.db.models import F, Sum
items = (
Item.objects
.filter(mac_src=F('mac_dst'))
.values('mac_src', 'mac_dst')
.annotate(sum_bytes=Sum('bytes_in'))
.order_by('-sum_bytes')
)
答案 2 :(得分:0)
select
t1.mac_src as mac,
t1.sum_bytes_in + t2.sum_bytes_in as sum_bytes_in
from
(select
mac_src,
sum(bytes_in) as sum_bytes_in
from tbl
group by mac_src) as t1
inner join
(select
mac_dst,
sum(bytes_in) as sum_bytes_in
from tbl
group by mac_dst) as t2
on t1.mac_src = t2.mac_dst
order by sum_bytes_in desc
这假定任何行的row.mac_src!= row.mac_dst。