简体   繁体   中英

sql query using temp table

I have a query as follows

select VendorNumber,sum(EY_AmountIncl_LC)AmountIncl_LC ,SUm(EY_AmountExcl_LC)AmountExcl_LC,max(EY_datedocumented) Datedocumented
            ,stuff( (select distinct ','+dbo.table2.InvoiceStatus
                           from dbo.table2
                           where dbo.table2.VendorNumber = dbo.table2.VendorNumber 
                           for xml path('')
                          ), 1, 1, ''
                        ) as InvoiceStatus
from dbo.table2
group by VendorNumber

How do i write the same query using temptable in sql server management studio.can anyone help?

First i would correct your subquery condition which should be referenced from outer query :

select VendorNumber, sum(EY_AmountIncl_LC) AmountIncl_LC, 
       max(EY_datedocumented) Datedocumented,
       stuff( (select distinct ','+t22.InvoiceStatus
               from dbo.table2 t22 -- create alias & use them 
               where t22.VendorNumber = t2.VendorNumber 
               for xml path('')
              ), 1, 1, ''
            ) as InvoiceStatus
from dbo.table2 t2 -- create alias & use them
group by VendorNumber;

Now, temp table has same functionality as base table, you just replace your base table name ( dbo.table2 ) with temp table name ( #temp whatever name you have).

Short Note about alias :

  • You can use alias for table name as well as column name.
  • COLUMN alias are used to make column headings in your result set easier to read.
  • TABLE alias are used to shorten your SQL to make it easier to read or write, when you are performing a self join or using correlated subquery (ie: listing the same table more than once in the FROM clause).

For more you can visit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM