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 |
|
lyealain
Starting Member
4 Posts |
Posted - 2009-02-03 : 22:46:48
|
hi i got a question on my query.imagine u want to get data from 2 tables.Services - product details {Id, Name, Category}Inventories- contains buy in/ sell out stock quantity {ServiceId, LedgerId,Qty,DateCreatd}LedgerId =4 is Buy inLedgerId = 5 is sell outi would like to get the product left unit with the product description in one query. so i do like this.. but this seems to be a very long query..Please advice whether i am doing a good way?select *from Services AS S left outer join (select BuyIn.serviceId,IsNull(BuyIn.Total,0)-IsNull(SoldOut.Total,0) AS Remain from (select serviceId,sum(qty) as Total from Inventories where ledgerId=4 group by serviceId) as BuyIn left outer join (select serviceId,sum(qty) as Total from Inventories where ledgerId=5 group by serviceId) as SoldOuton BuyIn.serviceId=SoldOut.serviceId) AS Soldon Sold.ServiceId=S.Idwhere S.Status = 1 lyealain hong loon |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2009-02-04 : 01:07:57
|
Shouldn't it be like this?Select desired columnsfrom Services AS S Inner join (Select ServiceId,(Buyin - Soldout) AS Remain from (Select serviceId, Sum(Case When ledgerId=4 then qty else 0 end) as Buyin, Sum(Case When ledgerId=5 then qty else 0 end) as Soldout, from Inventories group by serviceId) Z)M On M.ServiceId=S.IdWhere S.Status = 1 |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-02-04 : 02:42:36
|
| hi sodeep, how will u get the difference in subquery once check this sample data outputdeclare @tab table( EMPID int NOT NULL, EMPNAME nvarchar(32) , EMPSAL decimal(10, 5) , EMPDATE datetime )INSERT INTO @tab VALUES(1, 'B.Kaladhar', 33433.11000, '2008-09-08 18:18:27');INSERT INTO @tab VALUES(2, 'RAMU', 2232.11000, '2008-09-08 18:18:27');INSERT INTO @tab VALUES(5, 'RAJU', 2232.11000, '2008-09-08 18:18:27');INSERT INTO @tab VALUES(7, 'KUMAR', 2232.11000, '2008-09-08 18:18:27');INSERT INTO @tab VALUES(76, 'HARI', 2343.00000, '2008-09-08 18:18:27');select * from @tabSelect empid,(Buyin - Soldout) AS Remainfrom (Select empid, Sum(Case When EMPID=1 then EMPSAL else 0 end) as Buyin, Sum(Case When EMPID=5 then EMPSAL else 0 end) as Soldout from @tab group by empid) Z |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-02-04 : 03:07:19
|
| [code]SELECT s.Name,SUM(CASE WHEN i.LedgerId =4 THEN i.qty ELSE -1 * i.qty END) AS RemainFROM Services sINNER JOIN Inventories iON i.ServiceId=s.IdAND i.LedgerId IN (4,5)WHERE s.Status=1GROUP BY s.Name[/code] |
 |
|
|
|
|
|
|
|