【问题标题】:How to link a database table to itself and get the query results如何将数据库表链接到自身并获取查询结果
【发布时间】:2016-07-16 01:13:08
【问题描述】:

我需要您帮助我从名为“Earnings”的表中获取数据并将其链接到自身两次。 “收益”表包含以下列:

PaymentDate   EmployeeID   Description   Amount

30-Jun-2016   111          Basic         100

30-Jun-2016   111          Telephone     20

31-May-2016   111          Basic         100

31-May-2016   111          Telephone     10

31-May-2016   222          Basic         200

我需要准备一个查询来计算所选月份“2016 年 6 月”与上个月之间的员工付款差异,我应该再添加 3 列(当月付款 - 上个月付款 - 差额) .

如果付款与上个月相同,我不应该显示它们。但是,如果付款在上个月存在,并且在本月不可用或本月为空,我应该显示上个月的值,当月我应该显示为零。

我才开始发起查询,然后我需要您的帮助才能继续:

select e.paymentdate, e.employeeid,e.Description,e.amount
from earnings e, earnings x
where e.employeeid = x.employeeid

需要添加3个字段currentmonthpayment-previousmonthpayment-差值(current-previous)

【问题讨论】:

  • 第 1 步 - 将 * 替换为您需要的适用别名(e 和 x)中的字段。
  • @DanBracuk 我已经添加了表格中的字段,但我不确定如何在我将添加它们的正确列下显示金额(当月 - 上个月 - 差异)跨度>
  • 我建议你去办公时间(或你学校的任何同等时间)并从你的老师那里获得帮助。 SO 不是学习如何在 select 子句中包含所需列名的地方。

标签: sql oracle oracle11g


【解决方案1】:

您可以使用下面的 SQL 来获取所需的数据

    select e.employeeid, current_month_earning, prev_month_earning, (current_month_earning - prev_month_earning ) as difference
from 
(
    select 
        employeeid
        , sum(amount) as current_month_earning
    from 
        earnings
    where 
        to_char(paymentdate,'YYYYMM') = to_char(SYSDATE,'YYYYMM')
    group by 
        employeeid
) current_month_earnings
(
    select 
        employeeid
        , sum(amount) as prev_month_earning
    from 
        earnings
    where 
        to_char(paymentdate,'YYYYMM') = to_char(trunc(SYSDATE,'MM')-1,'YYYYMM')
    group by 
        employeeid
) prev_month_earnings
where current_month_earnings.employeeid = prev_month_earnings.employeeid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多