Quantcast
Channel: Getting started with SQL Server forum
Viewing all articles
Browse latest Browse all 9243

SELECTING TWO COLUMNS FROM DIFFERENT TABLES USING PIVOT.

$
0
0

Hello to all. I have two different views in SQL, one gives me the total sales from a specific product and the other one gives me the current stock. Then with two pivot tables i get the results for every store (Tienda) on different columns.

I need to combine my pivot tables so i can get both the sales and stock columns in the same table.

The SELECT from the views are as follows:


The pivot tables gives me the sales (cantidad) and the stock (existe) as follows:

This first one is for SALES and the second for STOCK:


The Pivot Querys i'm using are like this:

For the Sales

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX), @InvID AS INT SET @InvID =1
	SELECT @cols = STUFF(
		(SELECT ',' + QUOTENAME(des_caja) FROM tblM_Cajas FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
	SET @query = 'SELECT Prod, Atrib,' + @cols + ' FROM vwVentasT
		PIVOT(MAX(cantidad) FOR Tienda IN (' + @cols + ')) AS pvt WHERE InvID = @InvID ORDER BY Prod'

And for the Stock

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX), @InvID AS INT SET @InvID =1
    SELECT @cols = STUFF(
		(SELECT ',' + QUOTENAME(des_caja) FROM tblM_Cajas FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
	SET @query = 'SELECT Prod, Atrib,' + @cols + ' FROM vwStockInv
		PIVOT(MAX(existe) FOR Tienda IN (' + @cols + ')) AS pvt WHERE InvID = ' + REPLACE(@InvID, '''','''''') + ' ORDER BY Prod'

The result for the Querys are:

Sales:

SELECT Prod, Atrib,[MARIANO2],[SOLER ],[OTAY] FROM vwVentasT PIVOT(
	MAX(cantidad) FOR Tienda IN ([MARIANO2],[SOLER],[OTAY])) AS pvt WHERE InvID = 1 ORDER BY Prod

Stock:

SELECT Prod, Atrib,[MARIANO2],[SOLER ],[OTAY] FROM vwStockInv PIVOT(
	MAX(existe) FOR Tienda IN ([MARIANO2],[SOLER ],[OTAY])) AS pvt WHERE InvID = 1 ORDER BY Prod
I eliminated some column names from @cols to shorten the outputs.

How do i combine this Pivots so i can get, for Example:

Prod     Atrib Mariano(Sls)Mariano(Stk)Soler(Sls) Soler(Stk)Otay(Sls)Otay(Stk)

Prod

Atrib

Mariano(Sls)

Mariano(Stk)

Soler(Sls)

Soler(Stk)

Otay(Sls)

Otay(Stk)

Name

Desc

1

-1

3

2

4

0

I really need help with this, thanks for any help you can give me.


Omar Mtz



Viewing all articles
Browse latest Browse all 9243

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>