I have three tables in my ERP and I need a query, by SQL Server, for join all rows. Here are the three tables I have with its properties, filtering by product code (SL.CodProduct = 'AL4301') to simplify:
TABLE PRODUCTS:
- CodProduct
- DescProduct
- Family
TABLE STOCKS:
- CodProduct
- Color
- Number
- UnitsStock
TABLE SELLS:
- CodProduct
- DateSold
- Color
- Number
- UnitsSold
I need to get a list of all item combinations (color - number), showing sales per month and total stock currently. The problem is that for some combinations of items there have been no sales.
I have tried it with this query:
SELECT DatePart(mm, SELLS.DateSold) As Month,
SELLS.CodProduct, PRODUCTS.DescProduct,
SELLS.Color, SELLS.Number,
SUM(SELLS.UnitsSold,
(SELECT STOCKS.UnitsStock
FROM STOCKS WITH(NOLOCK)
WHERE STOCKS.CodProduct = SELLS.CodProduct
AND STOCKS.Color = SELLS.Color AND STOCKS.Number = SELLS.Number) As Stock
FROM SELLS WITH(NOLOCK)
JOIN PRODUCTS WITH (NOLOCK) ON PRODUCTS.CodProduct = SELLS.CodProduct
WHERE PRODUCTS.Family = 05 AND SELLS.CodProducto = 'AL4301'
GROUP BY DatePart(mm, SELLS.DateSold), SELLS.CodProduct, SELLS.DescProduct, SELLS.Color, SELLS.Number
ORDER BY SELLS.CodProduct, SELLS.Color, SELLS.Number
With this query I obtain this:
But I would need to get this:
Thanks to @Gordon Linoff, I get solution. Finally I used this:
SELECT ST.CODPRODUCT, ST.DESPRODUCT, ST.COLOR, ST.NUMBER,
P.FAMILY, ST.UNITSSTOCK STOCK, SLL.MONTH, SLL.UNITSSOLD
FROM STOCKS ST
JOIN PRODUCTS P ON P.CODPRODUCT = ST.CODPRODUCT
LEFT OUTER JOIN
(SELECT SL.CODPRODUCT, SL.COLOR, SL.NUMBER,
DatePart(mm, SL.DATESOLD) MONTH,
SUM(SL.UNITSSOLD) UNITSSOLD
FROM SELLS SL
GROUP BY SL.CODPRODUCT, DatePart(mm, SL.DATESOLD),
SL.COLOR, SL.NUMBER) SLL
ON SLL.CODPRODUCT = ST.CODPRODUCT
AND SLL.COLOR = ST.COLOR
AND SLL.NUMBER = ST.NUMBER
ORDER BY ST.CODPRODUCT, ST.COLOR, ST.NUMBER