如何在SQL语句中复制以下excel计算?

时间:2018-11-28 23:54:51

标签: mysql sql excel oracle

我从WeekProdQty列开始:

Initial Dataset

我希望输出如下:

Desired output

我已使用以下excel公式获取此输出:

在单元格D2中:=IF(B2=B1, IF(C2=C1, "N", "Y"), "N") 在单元格E2中:=IF(D2="N", "NA", C2-C1)

我想在SQL语句中复制相同的内容。我不确定该如何开始。

3 个答案:

答案 0 :(得分:1)

我了解您正在尝试比较连续几周每种给定产品的数量。在SQL中,您可以通过使用LEFT JOIN子句(相同的产品和下周)将表自身与表连接起来来实现此目的。当没有匹配项时(给定产品的下周没有),join子句将产生NULL值。基于此,您可以然后实现比较逻辑。

您同时用oraclemysql标记了您的问题,我不知道它是否真的是有目的的,但是此解决方案应同时适用于这两个问题:

select
    t1.week,
    t1.prod,
    t1.qty,
    case 
        when t2.week is null or t1.qty = t2.qty then 'N'
        else 'Y' 
    end week_over_week_change,
    case 
        when t2.week is null or t1.qty = t2.qty then 'NA'
        else t1.qty - t2.qty 
    end week_over_week_change_qty
from table t1
left join table t2 on t2.prod = t2.prod and t2.week = t1.week + 1

答案 1 :(得分:1)

直接查询Excel:

Sub TestQuery()

    Dim oConn As New ADODB.Connection
    Dim oRS As ADODB.Recordset
    Dim sPath, t
    Dim sSQL As String, s As String

    sSQL = " select t1.*, t2.qty, IIf(t1.Qty=t2.Qty,'N','Y') as changed,  " & _
           " IIf(t1.Qty=t2.Qty,'NA',t2.qty-t1.qty) as change " & _
           " from [Sheet4$] t1, [Sheet4$] t2 " & _
           " where t1.Prod=t2.Prod and t2.Week = t1.week+1 "

    sPath = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    oConn.Open "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" & _
               "DBQ=" & sPath & ";"

    Set oRS = oConn.Execute(sSQL)

    If Not oRS.EOF And Not oRS.BOF Then
        ToSheet Sheet5.Range("A1"), oRS
    Else
        MsgBox "No records found"
    End If

End Sub

Sub ToSheet(rng, rs)
    Dim f, i
    i = 0
    rng.Resize(1000, 200).ClearContents
    For Each f In rs.Fields
        rng.Offset(0, i).Value = f.Name
        i = i + 1
    Next f
    rng.Offset(1, 0).CopyFromRecordset rs
End Sub

输入/输出:

enter image description here

答案 2 :(得分:1)

这是在Oracle中,但使用的是标准分析功能。在其他SQL产品中,语法可能略有不同,但是函数本身的语法应该相同。我还使用了case表达式,这也是标准的表达式。

select week, prod,
       case when qty != lag(qty) over (partition by prod order by week)
            then 'Y' else 'N' end as week_over_week_change,
       qty - lag(qty) over (partition by prod order by week) as weekly_qty_change
from   [your table, view, or whatever]
........