簡體   English   中英

SQL:使用max(column)選擇不同的列總和

[英]SQL: Select distinct sum of column with max(column)

我有這樣的薪水表:

id | person_id | start_date  | pay
1  | 1234      | 2012-01-01  | 3000
2  | 1234      | 2012-05-01  | 3500
3  | 5678      | 2012-01-01  | 5000
4  | 5678      | 2013-01-01  | 6000
5  | 9101      | 2012-09-01  | 2000
6  | 9101      | 2014-04-01  | 3000
7  | 9101      | 2011-01-01  | 1500
and so on...

現在,我要查詢公司所有人員特定月份的工資總額。

我已經有了在特定公司在特定月份工作的人員的身份證,因此我可以執行WHERE person_id IN(...)

我的薪水查詢有些問題。 例如,2012-08月份的結果應為:

10000

這是3500 + 5000 + 1500。

因此,我需要找到最大start_date <=特定月份的總計工資值(對於IN子句中的所有人員)。

我嘗試了各種INNER JOINS,但這已經是漫長的一天,目前我無法直截了當。

任何提示高度贊賞。

您必須將group by用於這些事情...。

  select person_id,sum(pay) from salary where person_id in(...) group by person_id

可能會幫助您.....

您需要獲取活動記錄。 以下是通過計算相關月份之前的最大開始日期來實現的:

select sum(s.pay)
from (select person_id, max(start_date) as maxstartdate
      from salary
      where person_id in ( . . . ) and
            start_date < <first day of month of interest>
      group by person_id
   ) p join
   salary s
   on s.person_id = p.person_id and
      s.maxstartdate = p.start_date

您需要填寫ID的月份和列表。

您也可以使用排名函數來執行此操作,但是不指定要使用的SQL引擎。

暫無
暫無

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

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