簡體   English   中英

涉及帶條件的部分組的 SQL 查詢?

[英]SQL query involving partial group with condition?

以下是我無法理解正確方法的 SQL 查詢問題:

數據庫表:

Employee: emp_id, emp_name
Credit: credit_id, emp_id, credit_date, credit_amount
debit: debit_id, emp_id, debit_date, debit_amount

在這里,每個人都可以有多種收入和支出。

查詢要求:每天結束時,每個員工都會有一些資產('貸到現在' - '借到現在')。 我們需要根據最大資產以及他們擁有此最大資產的日期來查找前五名員工。

我已經嘗試了以下查詢,但似乎我遺漏了一些東西:

select Credit.emp_id, Credit.date, (Credit.income_amount - Debit.credit_amount) from 
(select emp_id, sum(amount) as credit_amount 
from credit) Credit
LEFT JOIN LATERAL (
     select emp_id, sum(amount) as debit_amount
     from debits
     where debits.emp_id = Credit.emp_id and Credit.date >= debits.date
     group by debits.emp_id
    ) Debit
ON true

在這里,我打破了查詢以使其更具可讀性。

首先,我們需要獲取credit和debit兩者在一天級別的總金額,以便我們可以使用相同的emp_id加入天級別的credit和debit表。

with 
credit as(
    select emp_id,credit_date date,sum(credit_amount) as amount
    from credit  
    group by 1,2),

debit as(
    select emp_id,debit_date,sum(debit_amount) as amount
    from expenses 
    group by 1,2),

現在我們需要完全外部加入“credit”和“debit”子查詢

payments as (
    select distinct
    case when c.emp_id is null then d.person_id else c.emp_id  end as emp_id ,
    case when c.emp_id is null then d.date else c.date end as date,
    case when c.emp_id is null then 0 else i.amount end as credit ,
    case when d.emp_id is null then 0 else d.amount end as debit 
    from credit c
    full outer join debit d on d.emp_id=c.emp_id and d.date=c.date
    ),

現在我們將按天計算貸方、借方和總余額的累計金額,如下所示。

total_balance as(
    SELECT emp_id, date, 
    sum(credit) OVER (PARTITION BY emp_id ORDER BY date asc) AS total_credit,
    sum(debit) OVER (PARTITION BY emp_id ORDER BY date asc) AS total_debit,
    (sum(income) OVER (PARTITION BY person_id ORDER BY date asc) - 
    sum(expense) OVER (PARTITION BY person_id ORDER BY date asc)) as total_balance
    FROM group_payment
    ORDER BY person_id, date),

現在我們需要使用 rank() 函數根據總余額 (desc) 為 emp_id 分配排名(即 rank=1 將分配給特定 emp_id 一天中最大的總余額)。 查詢如下所示。

ranks as (select emp_id,date,total_balance,
rank() over (partition by emp_id order by total_balance desc) as rank
from total_balance ),

現在選擇 rank=1 的行(即 emp_id 的一天中 total_balance 的 MAX 和它是 MAX 的日期)。 按 total_balance 降序排序並選擇前 5 行

emp_order as (select emp_id,date,total_balance 
from ranks
where rank=1
order by 3 desc
limit 5)

現在從員工表中選擇姓名。

select emp_id,name, date, total_balance as balance
from emp_order eo
join Employee e on e.emp_id = eo.emp_id
order by 4 desc

Group by 和 sum 允許您將每個人的總學分分成 1 條記錄。 您可以在子查詢中做類似的事情來減去借方。

Select top 5 emp_id, credit_date, (sum(credit_amount) - 
(select sum(debit_amount) from debit d 
where c.emp_id = d.emp_id and c.credit_date = d.debit_date)
) as total
from Credit c group by emp_id, credit_date order by total

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM