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 |
|
tunc260
Starting Member
5 Posts |
Posted - 2009-05-30 : 09:53:27
|
| i want to write a query list all customers' sales. there is a complexity. we should combine main customers with branches of them. TBLCUSTOMER is like thatLNGCUSTCODE TXTNAME100 WALMART ( center )101 WALMART ( Texas )102 WALMART ( LA )151 PIN RETAIL MARKETactualy 100,101,102 are same customer. we should regard as one customer when calculating its sales.there is a tblbranch table , like that,CUSTCODE BRANCHCODE100 101100 102100 103100 is the main customer101,102,103 are branches of itand also we have a tblinvoice which holds sales dataTBLINVOICE is like thatLNGCUSTCODE DDBLGROSSAMOUNT DBLDISCOUNT100 500 2101 100 3151 150 10102 200 0121 200 10according to these table , i should get this report as a result of the query we build.customer sales 100 795 which gotten from ((500+100+200)-5)151 140 ( this customer doesnt have any branch so ( 150-10 )121 91 actualy customer 100's sales is the total sales of 100,101 and 102i should compute customers' sales by combining its branchesi builded a query like below , but i couldnt combine customers who have branches.SELECT LNGCUSTCODE, (SUM(DBLGROSSAMOUNT) - SUM(DBLDISCOUNT)) AS SALESFROM TBLINVOICE TF , TBLCUSTOMER AS TMWHERE TF.LNGCUSTCODE = TM.LNGCUSTCODE AND (TF.TXTDATE >= '20090401') AND (TF.TXTDATE <= '20090430')GROUP BY LNGCUSTCODEHAVING (SUM(DBLGROSSAMOUNT) - SUM(DBLDISCOUNT))> 2000Thank u very much for ur intention. |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2009-05-30 : 12:40:58
|
| [code]CREATE TABLE #TBLCUSTOMER(LNGCUSTCODE int, TXTNAME varchar(100))INSERT #TBLCUSTOMERSELECT 100, 'WALMART ( center )' UNION ALLSELECT 101, 'WALMART ( Texas )' UNION ALLSELECT 102, 'WALMART ( LA )' UNION ALLSELECT 121, 'unknown' UNION ALLSELECT 151, 'PIN RETAIL MARKET'CREATE TABLE #TBLBRANCH(CUSTCODE int, BRANCHCODE int)INSERT #TBLBRANCHSELECT 100, 101 UNION ALLSELECT 100, 102 UNION ALLSELECT 100, 103CREATE TABLE #TBLINVOICE(LNGCUSTCODE int, DBLGROSSAMOUNT float, DBLDISCOUNT float)INSERT #TBLINVOICESELECT 100, 500, 2 UNION ALLSELECT 101, 100, 3 UNION ALLSELECT 151, 150, 10 UNION ALLSELECT 102, 200, 0 UNION ALLSELECT 121, 200, 10SELECT coalesce(TB.CUSTCODE, TC.LNGCUSTCODE) AS CUSTCODE, (SUM(TI.DBLGROSSAMOUNT) - SUM(TI.DBLDISCOUNT)) AS SALESFROM #TBLINVOICE TIINNER JOIN #TBLCUSTOMER TC ON TC.LNGCUSTCODE = TI.LNGCUSTCODELEFT JOIN #TBLBRANCH TB ON TB.BRANCHCODE = TC.LNGCUSTCODEGROUP BY coalesce(TB.CUSTCODE, TC.LNGCUSTCODE)[/code] |
 |
|
|
|
|
|
|
|