?
Solved

Add a join of a query

Posted on 2013-12-11
6
Medium Priority
?
498 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 

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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

777 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