如何在mysql查询中获得列的前4个结果?

时间:2018-03-27 10:29:13

标签: mysql sql select

我在mySQL方面不是很有经验,但是

我有一个SQL查询表,我需要返回:

Salary_amount_1
Salary_amount_2
Salary_amount_3
Salary_amount_4

(not relevant below)
Salary_Date_1
Salary_Date_2
Salary_Date_3
Salary_Date_4

我已经为我们要插入的目标表中的每个工资金额选择了4个单独的列,以及在源表中有15个以上不同金额的Salary列我们& #39;重新选择,但是我如何专门选择第1列的第一个薪水,第2列的第二个薪水,第4个列的第三个薪水和第四个薪水? 提前致谢

我尝试过:

这就是我所拥有的(并且还没有为我工作)

Select 
  ID,
  Bank Name,
  UserName,
  min(details_Credit) as Salary_Amount_1,
  max(details_Credit) as Salary_Amount_2,
  Case 
    when details_Credit = min(details_Credit)
         and details_Credit > min(details_Credit)
  end Salary_Amount_3,
  ????? as Salary_Amount_4,

任何帮助将不胜感激。谢谢

示例数据:

Salary| SalaryDate| UserName| BankName
=====================================
1000  |2013-05-23 |MikeRoss |NetBank
1500  |2013-06-23 |MikeRoss |NetBank
2000  |2013-07-22 |MikeRoss |NetBank
1000  |2013-08-15 |MikeRoss |NetBank

期望的结果:

 Username|Bank|Salary1|Salary2|Salary3|Salary4|Date1|Date2|Date3|Date4
MikeRoss|Netbank|1000|1500|2000|1000|2013-05-23| 2013-06-23| 2013-06-22| 2013-08-15

2 个答案:

答案 0 :(得分:0)

我认为你需要的是这样的:

Select ID, Bank Name, UserName, Salary_amount_1 from yourTable
order by Salary_amount_1 limit 1

Union

Select ID, Bank Name, UserName, Salary_amount_2 from yourTable
order by Salary_amount_2 limit 1,1

Union

Select ID, Bank Name, UserName, Salary_amount_3 from yourTable
order by Salary_amount_3 limit 2,1

Union

Select ID, Bank Name, UserName, Salary_amount_4 from yourTable
order by Salary_amount_4 limit 3,1

这将执行4个查询,每个查询返回一个您想要的结果。 在{/ strong>跳过limit offset, rowcount行后,rowcount会占用第一个offset

那就是说,我强烈建议你检查一下桌子的结构。

答案 1 :(得分:0)

我使用Left Join来解决这个问题,任何人都在想。即

left join DB.Table_Name as a1 on a1.ID=a.ID and a1.TransactionDate=a0.maxDate 
left join DB.Table_Name as a2 on a2.ID=a1.ID and a2.TransactionDate<a1.TransactionDate
left join DB.Table_Name as a3 on a3.ID=a2.ID and a3.TransactionDate<a2.TransactionDate