Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Add a join of a query

Posted on 2013-12-11
6
Medium Priority
?
503 Views
Last Modified: 2013-12-11
I have this query to compare values in two tables, Lindoc and ObrLinDoc.  Now i need join another table (Customers) to return in each line also Name and Id of customers.

SELECT
      	
       CodigoProduto
      , Designacao
      , CONVERT(DECIMAL(18,4),SUM(Quant_Orc))                                              AS [Quant Orcamentado]
      , CONVERT(DECIMAL(18,4),SUM(Quant_Imputado))                                         AS [Quant Imputado]
      , CONVERT(DECIMAL(18,4),SUM(Quant_Imputado)) - CONVERT(DECIMAL(18,4),SUM(Quant_Orc)) AS Desvio
	  , CONVERT(DECIMAL(18,2),sum (Venda_Imputado))                                        AS [Imputado Venda]  
	  , CONVERT(DECIMAL(18,2),sum (Custo_Imputado))                                        As [Imputado Custo]
FROM (
       
	    SELECT
              CodigoProduto
			  , '0' as mov
              , Designacao
              , SUM(quantidade)        AS Quant_Orc
              , 0                      AS Quant_Imputado 
			  , sum(TotalLinha)        As Venda_Imputado 
			  ,0                       AS Custo_Imputado
			 
        FROM lindoc
		     inner join cabdoc on
		     lindoc.IdStampCab=cabdoc.IdStamp
		WHERE CABdoc.TipoDoc='DO' and cabdoc.IdStamp='DOC20131015162329687'                   -- Preciso saber qual o numero documento
		 
		GROUP BY
              CodigoProduto
              , designacao
			 

        UNION ALL


                SELECT
                      CodigoProduto
					  , mov
                      , Designacao
                      , 0                                                                             AS Quant_Orc
					  , CASE mov WHEN 'S' THEN sum(quantidade) ELSE sum(quantidade)*-1                END AS Quant_Imputado
					  , 0                                                                             As Venda_Imputado 
			          , CASE mov WHEN 'S' THEN sum(TotalLinhaCusto) ELSE sum(TotalLinhaCusto)*-1 END  AS Custo_Imputado
                
				FROM ObrLinDoc
				WHERE CodigoObra=1                                      -- Preciso saber numero de obra
                GROUP BY
                        CodigoProduto
						,mov
                      , Designacao

     ) as ObrLin
	 Where CodigoProduto Is Not Null
	 
GROUP BY
         CodigoProduto
       , designacao

Open in new window

0
Comment
Question by:rflorencio
  • 4
  • 2
6 Comments
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39711136
>Now i need join another table (Customers) to return in each line also Name and Id of customers.

Insert in line 52, and replace ?? with whatever column is the relationship between Customers and your subquery.  May need to add this column to the subquery if it doesn't already exists.
LEFT JOIN Customers c ON OrbLin.?? = c.??

Open in new window

Then you can add to your SELECT clause,
,c.id as customer_id, c.name as customer_name

Open in new window

0
 

Author Comment

by:rflorencio
ID: 39711232
I need join CustId but is in  Cabdoc.Custid table (line 23), can you help.
0
 
LVL 66

Accepted Solution

by:
Jim Horn earned 2000 total points
ID: 39711313
>Cabdoc.Custid table (line 23)
table.column, so technically Cabdoc.Custid is a column.

In that case, you're going to have to add CustId to both SELECT statements in the UNION subquery.  Once that's done, the main query can use it in the LEFT JOIN.
0
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 

Author Comment

by:rflorencio
ID: 39711526
Hi  jimhorn, can you take a look to see if all is well, the result returned to me after running it seems correct.

SELECT
        CodCli
	  , NomeCli
	  , CodigoProduto
      , Designacao
      , CONVERT(DECIMAL(18,4),SUM(Quant_Orc))                                              AS [Quant Orcamentado]
      , CONVERT(DECIMAL(18,4),SUM(Quant_Imputado))                                         AS [Quant Imputado]
      , CONVERT(DECIMAL(18,4),SUM(Quant_Imputado)) - CONVERT(DECIMAL(18,4),SUM(Quant_Orc)) AS Desvio
	  , CONVERT(DECIMAL(18,2),sum (Venda_Imputado))                                        AS [Imputado Venda]  
	  , CONVERT(DECIMAL(18,2),sum (Custo_Imputado))                                        As [Imputado Custo]
FROM (
       
	    SELECT
		      clientes.CodigoCliente as CodCli
			  ,clientes.Nome as NomeCli	
              ,CodigoProduto
			  , '0' as mov
              , Designacao
              , SUM(quantidade)        AS Quant_Orc
              , 0                      AS Quant_Imputado 
			  , sum(TotalLinha)        As Venda_Imputado 
			  ,0                       AS Custo_Imputado
			 
        FROM lindoc
		     inner join cabdoc on lindoc.IdStampCab=cabdoc.IdStamp
			 inner join Clientes on CabDoc.CodigoEntidade=Clientes.CodigoCliente
		WHERE CABdoc.TipoDoc='DO' and cabdoc.IdStamp='DOC20131015162329687'                   -- Preciso saber qual o numero documento
		 
		GROUP BY
		
              CodigoProduto
              , designacao
			  , Clientes.CodigoCliente
			  , Clientes.Nome
			 

        UNION ALL


                SELECT
					  clientes.CodigoCliente as CodCli
					  ,clientes.Nome as NomeCli	
                      ,CodigoProduto
					  , ObrLinDoc.mov
                      , Designacao
                      , 0                                                                             AS Quant_Orc
					  , CASE ObrLinDoc.mov WHEN 'S' THEN sum(quantidade) ELSE sum(quantidade)*-1                END AS Quant_Imputado
					  , 0                                                                             As Venda_Imputado 
			          , CASE ObrLinDoc.mov WHEN 'S' THEN sum(TotalLinhaCusto) ELSE sum(TotalLinhaCusto)*-1 END  AS Custo_Imputado
                
				FROM ObrLinDoc
				 inner join ObrFichaObra on ObrLinDoc.CodigoObra=ObrFichaObra.CodigoObra
			     inner join Clientes on ObrFichaObra.CodigoCliente=Clientes.CodigoCliente
				WHERE ObrLinDoc.CodigoObra=1                                      -- Preciso saber numero de obra
                GROUP BY
                        CodigoProduto
						,ObrLinDoc.mov
                      , Designacao
					  , Clientes.CodigoCliente
			  , Clientes.Nome

     ) as ObrLin
	 Where CodigoProduto Is Not Null
	
GROUP BY
         CodigoProduto
       , designacao
	   , CodCli
	   , nomecli

Open in new window

0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39711537
Looks correct, although since I'm not connected to your data source I can't verify.
0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39711556
Thanks for the grade.  Good luck with your project.  -Jim
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question