filmov
tv
SQL UNION ALL Tutorial: Merging Data from Multiple Queries

Показать описание
In this SQL tutorial, you'll learn how to use the UNION ALL operator to combine the results of multiple SQL queries. Unlike the regular UNION operator, UNION ALL returns all rows, including duplicates, from the SELECT queries. This makes it an ideal choice for scenarios where you need to preserve all data, regardless of duplication. We'll walk through basic usage, syntax, and real-world examples to help you understand how to effectively apply UNION ALL to merge data from different tables or queries. Additionally, we’ll compare it with UNION and explore performance considerations.
SQL Statment
use ContosoRetailDW
select productkey, sum(dbo.FactOnlineSales.SalesQuantity*dbo.FactOnlineSales.UnitPrice) as SalesAmount,'Online' as Salestype
from dbo.FactOnlineSales
group by ProductKey
union all
from dbo.FactSales
group by dbo.FactSales.ProductKey
use ContosoRetailDW
select sum(dbo.FactOnlineSales.SalesAmount) as SalesAmount,'Online' as Salestype
from dbo.FactOnlineSales
union all
select sum(dbo.FactSales.SalesAmount) SalesAmount,'Store' as SalesType
from dbo.FactSales
SQL Statment
use ContosoRetailDW
select productkey, sum(dbo.FactOnlineSales.SalesQuantity*dbo.FactOnlineSales.UnitPrice) as SalesAmount,'Online' as Salestype
from dbo.FactOnlineSales
group by ProductKey
union all
from dbo.FactSales
group by dbo.FactSales.ProductKey
use ContosoRetailDW
select sum(dbo.FactOnlineSales.SalesAmount) as SalesAmount,'Online' as Salestype
from dbo.FactOnlineSales
union all
select sum(dbo.FactSales.SalesAmount) SalesAmount,'Store' as SalesType
from dbo.FactSales