库存计算vb.net和sql

时间:2018-07-06 13:48:05

标签: sql sql-server vb.net sum

我的代码正在工作,但是我认为还有另一种方法可以仅使用sql。我正在考虑将此代码简化为更简单。请帮忙 代码获取库存表的总和,然后从事务表中减去相同的饭号,然后显示结果。但是,如果第二个查询没有null,则显示第一个查询的结果,而不必从第二个查询中减去。

 Dim commnd2 As New SqlCommand("SELECT RICETYPE.RICENAME, Sum(STOCK.NUMBEROFSTOCKS) AS SumOfNUMBEROFSTOCKS FROM SUPPLIER INNER JOIN (RICETYPE INNER JOIN STOCK ON RICETYPE.ID = STOCK.RICETYPEID) ON SUPPLIER.ID = STOCK.SUPPLIER GROUP BY RICETYPE.RICENAME", cn)
    dr = commnd2.ExecuteReader()
    If dr.HasRows Then
        While dr.Read
            Dim commnd3 As New SqlCommand("SELECT RICETYPE.RICENAME, Sum(TRANSAC.NUMBEROFSALES) AS SumOfNUMBEROFSALES
            FROM RICETYPE INNER JOIN TRANSAC ON RICETYPE.ID = TRANSAC.RICETYPEID WHERE RICETYPE.RICENAME = '" & dr.Item(0) & "'
            GROUP BY RICETYPE.RICENAME
            ", cn)
            dr2 = commnd3.ExecuteReader()
            If dr2.HasRows Then
                While dr2.Read
                    dt.Rows.Add(dr2.GetValue(0), dr.GetValue(1) - dr2.GetValue(1), dr2.GetValue(1))
                End While
            Else
                dt.Rows.Add(dr.GetValue(0), dr.GetValue(1), 0)
            End If
        End While
    End If

1 个答案:

答案 0 :(得分:1)

这是使用嵌套总和作为单个查询来完成此操作的一种方法。

SELECT RTO.RICENAME, Sum(ST.NUMBEROFSTOCKS) AS SumOfNUMBEROFSTOCKS, (SELECT Sum(TRANSAC.NUMBEROFSALES) AS SumOfNUMBEROFSALES
            FROM RICETYPE RTI INNER JOIN TRANSAC T ON RTI.ID = T.RICETYPEID WHERE RTI.RICENAME = RTO.RICENAME) 
FROM SUPPLIER S INNER JOIN (RICETYPE RTO INNER JOIN STOCK ST ON RTO.ID = ST.RICETYPEID) ON S.ID = ST.SUPPLIER GROUP BY RTO.RICENAME

是RICETYPE的内部引用,RTO是外部的。