考虑员工表:
Employerid ssn year Seqnumber q1taxamt q2taxamt q3taxamt q4taxamt
1004 101 2013 1 2000 0 0 0
1004 101 2013 2 2000 100 0 0
1004 101 2013 3 2000 100 200 0
1004 101 2013 4 2000 100 200 300
1004 102 2013 1 3000 0 0 0
1004 102 2013 2 3000 200 0 0
1004 102 2013 3 3000 200 300 0
1004 102 2013 4 3000 200 300 400
1004 102 2013 5 3000 200 300 400
这里的转换规则是我们需要选择每年每个ssn最高的Seqnumber Employerid和金额。
,即总和(q1taxamt)的10004是2000 +3000 = 5000
逻辑是ssn 101的seq编号最高为4,而ssn 102的seq编号最高为5,因此我们需要选择那些值为雇主的值
实施例: 想检查q1taxamt:2000 +3000 = 5000
想要查看q4taxamt:300 +400 = 700
输出必须是:
Employerid YEAR q1taxamt q2taxamt q3taxamt q4taxamt
10004 2013 5000 300 500 700
以下查询产生了错误的结果:
Select
Sum(E1.q1taxamt) q1taxamt,
Sum(E1.q2taxamt) q2taxamt,
Sum(E1.q3taxamt) q3taxamt,
Sum(E1.q4taxamt) q4taxamt,
E1.Employerid,
E1.YEAR
from Employee E1
join
(
select
E.Employerid,
MAX(E.seqnumber) seqnumber,
E.YEAR
from Employee E
group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
and E1.seqnumber=E2.Taxseqnumber
答案 0 :(得分:2)
只需使用select e.*
from (select e.*,
row_number() over (partition by E.Employerid, E.SSn, E.year
order by e.seqnumber desc
) as seqnum
from Employee e
) e
where seqnum = 1;
:
Employee(EmployerId, SSN, seqnumber desc)
为获得最佳效果,您需要class MenuItems(models.Model):
menu_item_title = models.CharField(max_length=256)
menu_item_description = models.TextField()
menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)
customer_favorite = models.BooleanField(default=False)
is_on_menu = models.BooleanField(default=True)
group = models.ForeignKey(MenuGrouping)
上的索引。
答案 1 :(得分:0)
您在SSN
和E1
之间遗漏了E2
个联接谓词,这就是您收到错误结果的原因。我认为这可能比Row_Number
方法更快。
Select
Sum(E1.q1taxamt) q1taxamt,
Sum(E1.q2taxamt) q2taxamt,
Sum(E1.q3taxamt) q3taxamt,
Sum(E1.q4taxamt) q4taxamt,
E1.Employerid,
E1.YEAR
from Employee E1
join
(
select
E.Employerid,
E.SSn,
MAX(E.seqnumber) seqnumber,
E.YEAR
from Employee E
group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
AND E1.SSN = E2.SSN --Here
and E1.seqnumber=E2.Taxseqnumber