从一个包含两个类型数据的表中减去一列

时间:2019-09-28 11:36:03

标签: sql sql-server

我有两个表包含数量列,它们包含不同的Feed_type列,如何显示数量差异。

Select pm.Prod_ID,pm.Product_Name ,ISNULL(Sum(psd.Quantity),0) as Quantity
 into #MyTempTable1 from dbo.[TBL_ProductStock_Details] psd
 inner join dbo.Tbl_Product_master pm  on psd.Prod_ID=pm.Prod_ID where Feed_Type=0 
 GROUP BY  pm.Prod_ID,pm.Product_Name  

  IF OBJECT_ID('tempdb..#MyTempTable2') IS NOT NULL DROP TABLE #MyTempTable2
  Select pm.Prod_ID,pm.Product_Name ,ISNULL(Sum(psd.Quantity),0) as Quantity 
into #MyTempTable2 from dbo.[TBL_ProductStock_Details] psd 
inner join dbo.Tbl_Product_master pm  on psd.Prod_ID=pm.Prod_ID  where Feed_Type=1 
 GROUP BY  pm.Prod_ID,pm.Product_Name

IF OBJECT_ID('tempdb..#MyTempTable3') IS NOT NULL DROP TABLE #MyTempTable3          
SELECT #MyTempTable1.Prod_ID as Prod_ID,#MyTempTable1.Product_Name as Product_Name ,
ISNULL(#MyTempTable1.Quantity,0) -ISNULL(#MyTempTable2.Quantity,0) AS Quantity_Diff 
into #MyTempTable3 from #MyTempTable1 
join #MyTempTable2 on 1=1 and #MyTempTable1.Prod_ID=#MyTempTable2.Prod_ID ;  

Select * From #MyTempTable3 

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合来简化逻辑并在单个查询中执行操作:

SELECT 
    pm.Prod_ID,
    pm.Product_Name,
    ISNULL(SUM(CASE WHEN Feed_Type = 0 THEN psd.Quantity ELSE 0 END), 0)
        - ISNULL(SUM(CASE WHEN Feed_Type = 1 THEN psd.Quantity ELSE 0 END), 0) AS Quantity_Diff 
INTO #MyTempTable3
FROM 
    dbo.[TBL_ProductStock_Details] psd
    INNER JOIN dbo.Tbl_Product_master pm  
        ON psd.Prod_ID = pm.Prod_ID
WHERE Feed_type IN (0, 1)
GROUP BY 
    pm.Prod_ID,
    pm.Product_Name

根据NULLs列中Quantity的分布,也可以通过单个SUM()进一步简化:

SELECT 
    pm.Prod_ID,
    pm.Product_Name,
    SUM(CASE 
        WHEN Feed_Type = 0 THEN ISNULL(psd.Quantity, 0) 
        ELSE -1 * ISNULL(psd.Quantity, 0) 
    END) AS Quantity_Diff 
INTO #MyTempTable3
FROM 
    dbo.[TBL_ProductStock_Details] psd
    INNER JOIN dbo.Tbl_Product_master pm  
        ON psd.Prod_ID = pm.Prod_ID
WHERE Feed_type IN (0, 1)
GROUP BY 
    pm.Prod_ID,
    pm.Product_Name

注意:考虑将列Feed_type与其所属的表建立索引;正如您所查询的那样,这是无法告知的,这使得它不太容易理解。