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

quhf5bfb  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(313)

我从列开始 Week , Prod 以及 Qty :

我希望我的输出如下:

我已使用以下excel公式获得此输出:
在单元格d2中: =IF(B2=B1, IF(C2=C1, "N", "Y"), "N") 在细胞e2中: =IF(D2="N", "NA", C2-C1) 我想在sql语句中复制相同的内容。我不知道怎么开始。

qeeaahzv

qeeaahzv1#

这是在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]
........
qni6mghb

qni6mghb2#

据我所知,贵公司正试图在连续几周内比较每种产品的数量。在sql中,可以通过使用 LEFT JOIN 条款(同一产品和下周)。如果没有匹配项(给定产品下周没有),join子句将产生空值。在此基础上,可以实现比较逻辑。
你把你的问题都贴上了标签 oracle 以及 mysql ,我不知道它是否真的是故意的,但是这个解决方案应该对这两种情况都适用:

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
v7pvogib

v7pvogib3#

直接查询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

输入/输出:

相关问题