Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 On Insert need to calculate a quantity

Author  Topic 

snufse
Constraint Violating Yak Guru

469 Posts

Posted - 2008-01-31 : 14:59:07
In my Insert into #TempTable I need to calculate the 'qty_wasted' as difference between 'qty_received' and 'qty_used' Where would I put the calc statement?


CREATE TABLE	#TempTable
(
job_date datetime,
job_number char(15),
cost_code char(15),
qty_received decimal(8,2),
qty_used decimal(8,2),
qty_wasted decimal(8,2),
productId char(25),
plant_id char(10)
)



INSERT INTO     #TempTable (job_date, job_number, cost_code, qty_received, qty_used, qty_wasted, productId, plant_id)
SELECT dbo.Batch.ReportDate AS job_date, dbo.Job.CompanyJobId AS job_number, dbo.Item.CompanyItemId AS cost_code, dbo.Product.CompanyProductId as productId, SUBSTRING(dbo.Job.CompanyJobId, 1,3) as plant_id,
qty_received = CASE dbo.SourceType.CompanySourceTypeId WHEN 'MA' then SUM(dbo.ProductionEvent.Quantity) ELSE 0 END,
qty_used = CASE dbo.SourceType.CompanySourceTypeId WHEN 'PR' THEN SUM(dbo.ProductionEvent.AlternateQuantity) ELSE 0 END
FROM dbo.Batch INNER JOIN
dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN.....

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-01-31 : 15:17:44
Here is one way. (your select list order doesn't match your column list order)

INSERT INTO #TempTable
(job_date,
job_number,
cost_code,
qty_received,
qty_used,
qty_wasted,
productId,
plant_id)
SELECT dbo.Batch.ReportDate AS job_date,
dbo.Job.CompanyJobId AS job_number,
dbo.Item.CompanyItemId AS cost_code,

qty_received = CASE dbo.SourceType.CompanySourceTypeId
WHEN 'MA' then SUM(dbo.ProductionEvent.Quantity)
ELSE 0
END,
qty_used = CASE dbo.SourceType.CompanySourceTypeId
WHEN 'PR' THEN SUM(dbo.ProductionEvent.AlternateQuantity)
ELSE 0
END,

qty_wasted = CASE dbo.SourceType.CompanySourceTypeId
WHEN 'MA' then SUM(dbo.ProductionEvent.Quantity)
ELSE 0
END
-
CASE dbo.SourceType.CompanySourceTypeId
WHEN 'PR' THEN SUM(dbo.ProductionEvent.AlternateQuantity)
ELSE 0
END,

dbo.Product.CompanyProductId as productId,
SUBSTRING(dbo.Job.CompanyJobId, 1,3) as plant_id

FROM dbo.Batch
INNER JOIN dbo.Event
ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid
INNER JOIN.....


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -