| Author |
Topic |
|
rcr69er
Constraint Violating Yak Guru
327 Posts |
Posted - 2008-05-26 : 05:53:35
|
| HiI have two tables, Sales Headers and SalesLines. The SalesHeaders table will hold basic details of a sale, and the Sales Lines table will hold details of the items in the sale.An example of tables are as follows:SalesHeaders:Sales_Ref, OrderDate, Customer_No111,01/05,2008,301112,01/05/2008,333113,01/05/2008,309114,03/05/2008,306115,03/05/2008,309...SalesLines:Sales_Ref, PartNumber, Qty111,e4334,3111,d434,1111,r555,20112,r332,1113,f442,5114,d332,2114,s324,7114,s432,5114,l567,2115,p098,10What I am trying to achieve is finding a count of SaleHeaders where it has only 1 item in the SalesLines table. ( I hope this makes sense)I tried using the follwoing query:SELECT sh.[Sales_Ref] ,COUNT(sl.[Sales_Ref])FROM dbo.SalesLines AS slLEFT JOIN dbo.SalesHeaders AS sh ON sl.[Sales_Ref] = sh.[Sales_Ref]GROUP BY sh.[Sales_Ref]HAVING COUNT(sl.[Sales_Ref) = 1But this returned all the record with a count of 1. Is it possible to just return the number?Thanking you in Advance! |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-05-26 : 06:08:02
|
| [code]SELECT COUNT(*)FROM(SELECT sh.Sales_RefFROM SalesHeaders shINNER JOIN SalesLines slON sl.Sales_Ref=sh.Sales_RefGROUP BY sh.Sales_RefHAVING COUNT(*) >1)t[/code] |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-05-26 : 06:09:13
|
Why join at all? If you want all associated records with a number of 1, they already exists on detailed table, as well as master table.DECLARE @Sample TABLE (Ref INT, PartNumber INT, Qty INT)INSERT @SampleSELECT 111, 434, 3 UNION ALLSELECT 111, 434, 1 UNION ALLSELECT 111, 555, 20 UNION ALLSELECT 112, 332, 1 UNION ALLSELECT 113, 442, 5 UNION ALLSELECT 114, 332, 2 UNION ALLSELECT 114, 324, 7 UNION ALLSELECT 114, 432, 5 UNION ALLSELECT 114, 567, 2 UNION ALLSELECT 115, 098, 10SELECT SUM(Items) AS YakFROM ( SELECT 1 AS Items FROM @Sample GROUP BY Ref HAVING COUNT(*) = 1 ) AS d E 12°55'05.25"N 56°04'39.16" |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-05-26 : 06:20:18
|
orSELECT SUM(1) AS YakFROM ( SELECT 1 AS Items FROM @Sample GROUP BY Ref HAVING COUNT(*) = 1 ) AS d MadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|