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.
Author |
Topic |
GordonCopestake
Starting Member
8 Posts |
Posted - 2012-02-28 : 20:12:24
|
Hi all,I'm a little rusty with (T)SQL and am trying what I thought was initially a very simple thing, but is turning out to be more complex than I thought!I have 3 tables that contain data:ItemsTableItemID(PK)ItemNameProductionTableProdID(PK,Identity)ItemID(FK)DateQtyProducedRejectTableRejectID(PK,Identity)ItemID(FK)DateQtyRejectedSample Data:ItemTable:A1|AppleO1|OrangeP1|PearProductionTable1|A1|01/01/12|102|O1|01/01/12|153|A1|02/01/12|94|P1|02/01/12|11RejectTable1|A1|01/01/12|22|A1|01/01/12|13|A1|02/01/12|2I'm trying to bring all three tables together for a simple summary:ItemIDQtyProduced(Sum)QtyRejected(Sum)PercentRejected(Calc)Summary TableA1|19|3|33.33O1|15|0|0P1|11|0|0I'm trying to do this as a stored procedure so I can pass a @StartDate and @EndDate to it. I'm getting hung up on the GROUP BY though and the sub-queriesAny pointers would be appreciatedThanks in advanceGordon Copestake |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-02-28 : 20:31:10
|
[code]SELECT i.itemID,p.QtyProduced,COALESCE(r.QtyRejected,0),COALESCE(r.QtyRejected,0)*100.0/p.QtyProduced AS PercentRejectedFROM Items iCROSS APPLY (SELECT SUM(QtyProduced) AS QtyProduced FROM ProductionTable WHERE ItemID = i.ItemID )pOUTER APPLY (SELECT SUM(QtyRejected) AS QtyRejected FROM RejectTable WHERE ItemID = i.ItemID )r[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
GordonCopestake
Starting Member
8 Posts |
Posted - 2012-02-28 : 20:46:22
|
Hi visakh16,Thanks for your swift reply. Your answer is very close, but I get the same data in every row!Does it need a tweak? |
 |
|
GordonCopestake
Starting Member
8 Posts |
Posted - 2012-02-29 : 04:22:02
|
Cracked it! Thanks for your help, it's appreciated. |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-02-29 : 12:08:26
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|