Sum of part of a column in a join statement

爷,独闯天下 提交于 2020-01-06 07:39:06

问题


SteelOrders

OrderNumber
-----------
0000843989    
0000843124    
0000881234    
0000123456    
-----------

FinalizedPrintedStickers

SN                  |  PanelBuildTime
-------------------------------------
0000843989-8R8-4-0  |  360
0000843989-8R8-4-1  |  200
0000843989-8R8-4-2  |  900    
0000843989-8R8-4-3  |  360
0000843989-8R8-4-4  |  460
0000843989-8S-1-0   |  220    
0000843989-8-2-0    |  360
etc..
-------------------------------------

The desired result would be:

OrderNumber |  PanelBuildTime
-----------------------------
0000843989  |  2860    
etc..
-----------------------------

What have I tried?

Select OrderNumber, Sum(PanelBuildTime) from SteelOrders 
INNER JOIN FinalizedPrintedStickers 
ON 
SteelOrders.OrderNumber = LEFT(FinalizedPrintedStickers.SN,10)

Unfortunately I have no idea how to add a WHERE clause on to this per item in the steelorder table

Also (Since I'm using oledb in my C# code to read from the steel order table) I've tried for every read of the OleDbDataReader Executing the Select Sum(PanelBuildtime) where ordernumber = reader["OrderNumber"], but that's extremely slow


回答1:


You can group by the order number to show the summary of the build times

Select OrderNumber, Sum(PanelBuildTime) from SteelOrders 
INNER JOIN FinalizedPrintedStickers 
ON 
SteelOrders.OrderNumber = LEFT(FinalizedPrintedStickers.SN,10)
GROUP BY SteelOrders.OrderNumber 



回答2:


Because you often might want to different columns with different conditions, you should also know about the case statement:

Select OrderNumber, Sum(case when SteelOrders.item = '0000843989' then PanelBuildTime end)
from SteelOrders INNER JOIN
    FinalizedPrintedStickers 
    ON SteelOrders.OrderNumber = LEFT(FinalizedPrintedStickers.SN,10)

In Access (sorry, I missed the tag), you have to use IIF instead of case.

Oh, based on your comment above, you want a group by:

Select OrderNumber, Sum(PanelBuildTime)
from SteelOrders INNER JOIN
    FinalizedPrintedStickers 
    ON SteelOrders.OrderNumber = LEFT(FinalizedPrintedStickers.SN,10)
group by OrderNumber


来源:https://stackoverflow.com/questions/13879917/sum-of-part-of-a-column-in-a-join-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!