Bin*_*gic 6 sql database postgresql distinct aggregate-functions
这是一个非常基本的问题,无论出于何种原因,我找不到合理的解决方案.我会尽力解释.
假设你有一个活动门票(部分,行,座位#).每张票都属于与会者.多张票可以属于同一个与会者.每位与会者都有一个价值(例如:参加者#1价值10,000美元).那就是说,这就是我想做的事情:
1. Group the tickets by their section
2. Get number of tickets (count)
3. Get total worth of the attendees in that section
Run Code Online (Sandbox Code Playgroud)
这就是我遇到问题的地方:如果参加者#1价值10,000美元且使用4张门票,那么sum(attendees.worth)将返还40,000美元.哪个不准确.价值应该是10,000美元.然而,当我将结果与参与者区分开来时,计数并不准确.在一个理想的世界里,做一些像这样的事情会很好
select
tickets.section,
count(tickets.*) as count,
sum(DISTINCT ON (attendees.id) attendees.worth) as total_worth
from
tickets
INNER JOIN
attendees ON attendees.id = tickets.attendee_id
GROUP BY tickets.section
Run Code Online (Sandbox Code Playgroud)
显然这个查询不起作用.如何在单个查询中完成同样的事情?或者甚至可能吗?我更愿意远离子查询,因为这是一个更大的解决方案的一部分,我需要在多个表中执行此操作.
此外,值得按照票价平均分配.例如:$ 10,000/4.每张门票的参加者价值5,000美元.因此,如果门票分别在不同的部分,他们会按比例分配门票.
谢谢你的帮助.
您需要在与会者之前聚合门票:
select ta.section, sum(ta.numtickets) as count, sum(a.worth) as total_worth
from (select attendee_id, section, count(*) as numtickets
from tickets
group by attendee_id, section
) ta INNER JOIN
attendees a
ON a.id = ta.attendee_id
GROUP BY ta.section
Run Code Online (Sandbox Code Playgroud)
您仍然遇到单个与会者在多个区域拥有座位的问题。但是,您没有指定如何解决该问题(分配价值?随机选择一个部分?将其归因于所有部分?规范地选择一个部分?)
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |