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
 SQL Server View Query

Author  Topic 

Jmekubo
Starting Member

2 Posts

Posted - 2013-06-19 : 06:04:02
Kindly help on sql query to create a view that merges data from two tables with same columns but second table (sales) has missing rows that correspond first table(Inventory)

In essense: I need those items that are in Inventory table but don’t have entries in sales table to be included in my sales view with (0) quantities.

Inventory
ItemID ItemName Qty
1 Bread 5
2 Soda 10
3 Cocoa 4
4 Blueband 15
5 Omo 20
6 Biscuits 30
7 Pens 50
8 Note book 5

Sales
ItemID ItemName Qty
1 Bread 3
2 Soda 5
5 Omo 10
6 Biscuits 15
8 Note book 2

I want my sales view to look like below
Sales View
ItemID ItemName Qty
1 Bread 3
2 Soda 5
3 Cocoa 0
4 Blueband 0
5 Omo 10
6 Biscuits 15
7 Pens 0
8 Note book 5

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-06-19 : 06:07:46
SELECT I.ItemID, I.ItemName, COALESCE(s.Qty, 0) Qty
FROM Inventory I
LEFT JOIN Sales s ON I.ItemID = s.ItemId

--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-19 : 06:08:03
sorry reading again i think i misunderstood

can you explain that qty part

why its comes from Sales in some case and Inventory in someother?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-19 : 06:11:30
for example for Note book 5
it comes from Inventory while

for 5 Omo 10
its from sales

so whats the rule?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-06-19 : 06:15:28
quote:
Originally posted by visakh16

for example for Note book 5
it comes from Inventory while

for 5 Omo 10
its from sales

so whats the rule?

I think there was a typo in Qty value for NoteBook.. Remaining item's quantities are from Sales table only...

--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-19 : 06:16:31
ideally as per your table names, this is logical

CREATE VIEW SalesView
AS
SELECT I.ItemID, I.ItemName, i.Qty AS QtyInStock,
COALESCE(s.Qty, 0) AS SalesQty,
i.Qty - COALESCE(s.Qty, 0) AS ResidualQty
FROM Inventory I
LEFT JOIN Sales s ON I.ItemID = s.ItemId


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -