Ejemplos de SELECT (Transact-SQL)SELECT Examples (Transact-SQL)

ESTE TEMA SE APLICA A:síSQL Server (a partir de 2008)síAzure SQL DatabasenoAzure SQL Data Warehouse noAlmacenamiento de datos paralelos THIS TOPIC APPLIES TO:yesSQL Server (starting with 2008)yesAzure SQL DatabasenoAzure SQL Data Warehouse noParallel Data Warehouse

Este tema proporcionan ejemplos del uso de la seleccione instrucción.This topic provides examples of using the SELECT statement.

A.A. Usar SELECT para recuperar filas y columnasUsing SELECT to retrieve rows and columns

En el siguiente ejemplo se muestran tres fragmentos de código.The following example shows three code examples. En el primer ejemplo de código, se devuelven todas las filas (no se especifica la cláusula WHERE) y todas las columnas (con *) de la tabla Product de la base de datos AdventureWorks2012AdventureWorks2012.This first code example returns all rows (no WHERE clause is specified) and all columns (using the *) from the Product table in the AdventureWorks2012AdventureWorks2012 database.

USE AdventureWorks2012;
GO
SELECT *
FROM Production.Product
ORDER BY Name ASC;
-- Alternate way.
USE AdventureWorks2012;
GO
SELECT p.*
FROM Production.Product AS p
ORDER BY Name ASC;
GO

En este ejemplo se devuelven todas las filas (no se ha especificado la cláusula WHERE) y solo un subconjunto de las columnas (Name, ProductNumber, ListPrice) de la tabla Product de la base de datos AdventureWorks2012AdventureWorks2012.This example returns all rows (no WHERE clause is specified), and only a subset of the columns (Name, ProductNumber, ListPrice) from the Product table in the AdventureWorks2012AdventureWorks2012 database. Además, se agrega un encabezado de columna.Additionally, a column heading is added.

USE AdventureWorks2012;
GO
SELECT Name, ProductNumber, ListPrice AS Price
FROM Production.Product 
ORDER BY Name ASC;
GO

En este ejemplo solo se devuelven las filas de Product que tienen una línea de productos de R y cuyo valor correspondiente a los días para fabricar es inferior a 4.This example returns only the rows for Product that have a product line of R and that have days to manufacture that is less than 4.

USE AdventureWorks2012;
GO
SELECT Name, ProductNumber, ListPrice AS Price
FROM Production.Product 
WHERE ProductLine = 'R' 
AND DaysToManufacture < 4
ORDER BY Name ASC;
GO

B.B. Usar SELECT con encabezados de columna y cálculosUsing SELECT with column headings and calculations

En los siguientes ejemplos se devuelven todas las filas de la tabla Product.The following examples return all rows from the Product table. En el primer ejemplo se devuelven las ventas totales y los descuentos de cada producto.The first example returns total sales and the discounts for each product. En el segundo ejemplo se calculan los beneficios totales de cada producto.In the second example, the total revenue is calculated for each product.

USE AdventureWorks2012;
GO
SELECT p.Name AS ProductName, 
NonDiscountSales = (OrderQty * UnitPrice),
Discounts = ((OrderQty * UnitPrice) * UnitPriceDiscount)
FROM Production.Product AS p 
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID 
ORDER BY ProductName DESC;
GO

Ésta es la consulta que calcula el beneficio de cada producto de cada pedido de venta.This is the query that calculates the revenue for each product in each sales order.

USE AdventureWorks2012;
GO
SELECT 'Total income is', ((OrderQty * UnitPrice) * (1.0 - UnitPriceDiscount)), ' for ',
p.Name AS ProductName 
FROM Production.Product AS p 
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID 
ORDER BY ProductName ASC;
GO

C.C. Usar DISTINCT con SELECTUsing DISTINCT with SELECT

En el siguiente ejemplo se utiliza DISTINCT para evitar la recuperación de títulos duplicados.The following example uses DISTINCT to prevent the retrieval of duplicate titles.

USE AdventureWorks2012;
GO
SELECT DISTINCT JobTitle
FROM HumanResources.Employee
ORDER BY JobTitle;
GO

D.D. Crear tablas con SELECT INTOCreating tables with SELECT INTO

En el primer ejemplo se crea una tabla temporal denominada #Bicycles en tempdb.The following first example creates a temporary table named #Bicycles in tempdb.

USE tempdb;
GO
IF OBJECT_ID (N'#Bicycles',N'U') IS NOT NULL
DROP TABLE #Bicycles;
GO
SELECT * 
INTO #Bicycles
FROM AdventureWorks2012.Production.Product
WHERE ProductNumber LIKE 'BK%';
GO

En el segundo ejemplo se crea la tabla permanente NewProducts.This second example creates the permanent table NewProducts.

USE AdventureWorks2012;
GO
IF OBJECT_ID('dbo.NewProducts', 'U') IS NOT NULL
    DROP TABLE dbo.NewProducts;
GO
ALTER DATABASE AdventureWorks2012 SET RECOVERY BULK_LOGGED;
GO

SELECT * INTO dbo.NewProducts
FROM Production.Product
WHERE ListPrice > $25 
AND ListPrice < $100;
GO
ALTER DATABASE AdventureWorks2012 SET RECOVERY FULL;
GO

E.E. Usar subconsultas correlacionadasUsing correlated subqueries

En el siguiente ejemplo se muestran consultas que son semánticamente equivalentes y se demuestra la diferencia entre la utilización de la palabra clave EXISTS y la palabra clave IN.The following example shows queries that are semantically equivalent and illustrates the difference between using the EXISTS keyword and the IN keyword. Ambos son ejemplos de subconsultas válidas que recuperan una instancia de cada nombre de producto cuyo modelo es un jersey de manga larga con logotipo y cuyos números de ProductModelID coinciden en las tablas Product y ProductModel.Both are examples of a valid subquery that retrieves one instance of each product name for which the product model is a long sleeve logo jersey, and the ProductModelID numbers match between the Product and ProductModel tables.

USE AdventureWorks2012;
GO
SELECT DISTINCT Name
FROM Production.Product AS p 
WHERE EXISTS
    (SELECT *
     FROM Production.ProductModel AS pm 
     WHERE p.ProductModelID = pm.ProductModelID
           AND pm.Name LIKE 'Long-Sleeve Logo Jersey%');
GO

-- OR

USE AdventureWorks2012;
GO
SELECT DISTINCT Name
FROM Production.Product
WHERE ProductModelID IN
    (SELECT ProductModelID 
     FROM Production.ProductModel
     WHERE Name LIKE 'Long-Sleeve Logo Jersey%');
GO

En el siguiente ejemplo se utiliza IN en una subconsulta correlativa o repetitiva.The following example uses IN in a correlated, or repeating, subquery. Se trata de una consulta que depende de la consulta externa de sus valores.This is a query that depends on the outer query for its values. Se ejecuta varias veces, una vez por cada fila que pueda seleccionar la consulta externa.The query is executed repeatedly, one time for each row that may be selected by the outer query. Esta consulta recupera una instancia del nombre y apellido de cada empleado cuya bonificación en la tabla SalesPerson sea de 5000.00 y cuyos números de identificación coincidan en las tablas Employee y SalesPerson.This query retrieves one instance of the first and last name of each employee for which the bonus in the SalesPerson table is 5000.00 and for which the employee identification numbers match in the Employee and SalesPerson tables.

USE AdventureWorks2012;
GO
SELECT DISTINCT p.LastName, p.FirstName 
FROM Person.Person AS p 
JOIN HumanResources.Employee AS e
    ON e.BusinessEntityID = p.BusinessEntityID WHERE 5000.00 IN
    (SELECT Bonus
     FROM Sales.SalesPerson AS sp
     WHERE e.BusinessEntityID = sp.BusinessEntityID);
GO

La subconsulta anterior de esta instrucción no se puede evaluar independientemente de la consulta externa.The previous subquery in this statement cannot be evaluated independently of the outer query. Necesita el valor Employee.EmployeeID, aunque este valor cambia a medida que el Motor de base de datos de SQL ServerSQL Server Database Engine examina diferentes filas de Employee.It requires a value for Employee.EmployeeID, but this value changes as the Motor de base de datos de SQL ServerSQL Server Database Engine examines different rows in Employee.

Una subconsulta correlativa se puede usar también en la cláusula HAVING de una consulta externa.A correlated subquery can also be used in the HAVING clause of an outer query. En este ejemplo se buscan los modelos cuyo precio máximo es superior al doble de la media del modelo.This example finds the product models for which the maximum list price is more than twice the average for the model.

USE AdventureWorks2012;
GO
SELECT p1.ProductModelID
FROM Production.Product AS p1
GROUP BY p1.ProductModelID
HAVING MAX(p1.ListPrice) >= ALL
    (SELECT AVG(p2.ListPrice)
     FROM Production.Product AS p2
     WHERE p1.ProductModelID = p2.ProductModelID);
GO

En este ejemplo se utilizan dos subconsultas correlativas para buscar los nombres de los empleados que han vendido un producto específico.This example uses two correlated subqueries to find the names of employees who have sold a particular product.

USE AdventureWorks2012;
GO
SELECT DISTINCT pp.LastName, pp.FirstName 
FROM Person.Person pp JOIN HumanResources.Employee e
ON e.BusinessEntityID = pp.BusinessEntityID WHERE pp.BusinessEntityID IN 
(SELECT SalesPersonID 
FROM Sales.SalesOrderHeader
WHERE SalesOrderID IN 
(SELECT SalesOrderID 
FROM Sales.SalesOrderDetail
WHERE ProductID IN 
(SELECT ProductID 
FROM Production.Product p 
WHERE ProductNumber = 'BK-M68B-42')));
GO

F.F. Usar GROUP BYUsing GROUP BY

En este ejemplo se busca el total de cada pedido de venta de la base de datos.The following example finds the total of each sales order in the database.

USE AdventureWorks2012;
GO
SELECT SalesOrderID, SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID
ORDER BY SalesOrderID;
GO

Debido a la cláusula GROUP BY, solo se devuelve una fila que contiene la suma de todas las ventas por cada pedido de venta.Because of the GROUP BY clause, only one row containing the sum of all sales is returned for each sales order.

G.G. Usar GROUP BY con varios gruposUsing GROUP BY with multiple groups

En este ejemplo se busca el precio medio y la suma de las ventas anuales hasta la fecha, agrupados por Id. de producto e Id. de oferta especial.The following example finds the average price and the sum of year-to-date sales, grouped by product ID and special offer ID.

USE AdventureWorks2012;
GO
SELECT ProductID, SpecialOfferID, AVG(UnitPrice) AS [Average Price], 
    SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY ProductID, SpecialOfferID
ORDER BY ProductID;
GO

H.H. Usar GROUP BY y WHEREUsing GROUP BY and WHERE

En el siguiente ejemplo se colocan los resultados en grupos después de recuperar únicamente las filas con precios superiores a $1000.The following example puts the results into groups after retrieving only the rows with list prices greater than $1000.

USE AdventureWorks2012;
GO
SELECT ProductModelID, AVG(ListPrice) AS [Average List Price]
FROM Production.Product
WHERE ListPrice > $1000
GROUP BY ProductModelID
ORDER BY ProductModelID;
GO

I.I. Usar GROUP BY con una expresiónUsing GROUP BY with an expression

En este ejemplo se agrupa por una expresión.The following example groups by an expression. Puede agrupar por una expresión si ésta no incluye funciones de agregado.You can group by an expression if the expression does not include aggregate functions.

USE AdventureWorks2012;
GO
SELECT AVG(OrderQty) AS [Average Quantity], 
NonDiscountSales = (OrderQty * UnitPrice)
FROM Sales.SalesOrderDetail
GROUP BY (OrderQty * UnitPrice)
ORDER BY (OrderQty * UnitPrice) DESC;
GO

J.J. Usar GROUP BY con ORDER BYUsing GROUP BY with ORDER BY

En este ejemplo se busca el precio medio de cada tipo de producto y se ordenan los resultados por precio medio.The following example finds the average price of each type of product and orders the results by average price.

USE AdventureWorks2012;
GO
SELECT ProductID, AVG(UnitPrice) AS [Average Price]
FROM Sales.SalesOrderDetail
WHERE OrderQty > 10
GROUP BY ProductID
ORDER BY AVG(UnitPrice);
GO

K.K. Usar la cláusula HAVINGUsing the HAVING clause

En el primer ejemplo se muestra una cláusula HAVING con una función de agregado.The first example that follows shows a HAVING clause with an aggregate function. Agrupa las filas de la tabla SalesOrderDetail por Id. de producto y elimina aquellos productos cuyas cantidades de pedido medias son cinco o menos.It groups the rows in the SalesOrderDetail table by product ID and eliminates products whose average order quantities are five or less. En el segundo ejemplo se muestra una cláusula HAVING sin funciones de agregado.The second example shows a HAVING clause without aggregate functions.

USE AdventureWorks2012;
GO
SELECT ProductID 
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING AVG(OrderQty) > 5
ORDER BY ProductID;
GO

En esta consulta se utiliza la cláusula LIKE en la cláusula HAVING.This query uses the LIKE clause in the HAVING clause.

USE AdventureWorks2012 ;  
GO  
SELECT SalesOrderID, CarrierTrackingNumber   
FROM Sales.SalesOrderDetail  
GROUP BY SalesOrderID, CarrierTrackingNumber  
HAVING CarrierTrackingNumber LIKE '4BD%'  
ORDER BY SalesOrderID ;  
GO  

L.L. Usar HAVING y GROUP BYUsing HAVING and GROUP BY

En el siguiente ejemplo se muestra el uso de las cláusulas GROUP BY, HAVING, WHERE y ORDER BY en una instrucción SELECT.The following example shows using GROUP BY, HAVING, WHERE, and ORDER BY clauses in one SELECT statement. Genera grupos y valores de resumen pero lo hace tras eliminar los productos cuyos precios superan los 25 $ y cuyas cantidades de pedido medias son inferiores a 5.It produces groups and summary values but does so after eliminating the products with prices over $25 and average order quantities under 5. También organiza los resultados por ProductID.It also organizes the results by ProductID.

USE AdventureWorks2012;
GO
SELECT ProductID 
FROM Sales.SalesOrderDetail
WHERE UnitPrice < 25.00
GROUP BY ProductID
HAVING AVG(OrderQty) > 5
ORDER BY ProductID;
GO

M.M. Usar HAVING con SUM y AVGUsing HAVING with SUM and AVG

En el siguiente ejemplo se agrupa la tabla SalesOrderDetail por Id. de producto y solo se incluyen aquellos grupos de productos cuyos pedidos suman más de $1000000.00 y cuyas cantidades de pedido medias son inferiores a 3.The following example groups the SalesOrderDetail table by product ID and includes only those groups of products that have orders totaling more than $1000000.00 and whose average order quantities are less than 3.

USE AdventureWorks2012;
GO
SELECT ProductID, AVG(OrderQty) AS AverageQuantity, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING SUM(LineTotal) > $1000000.00
AND AVG(OrderQty) < 3;
GO

Para ver los productos cuyas ventas totales son superiores a $2000000.00, utilice esta consulta:To see the products that have had total sales greater than $2000000.00, use this query:

USE AdventureWorks2012;
GO
SELECT ProductID, Total = SUM(LineTotal)
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING SUM(LineTotal) > $2000000.00;
GO

Si desea asegurarse de que hay al menos mil quinientos elementos para los cálculos de cada producto, use HAVING COUNT(*) > 1500 para eliminar los productos que devuelven totales inferiores a 1500 elementos vendidos.If you want to make sure there are at least one thousand five hundred items involved in the calculations for each product, use HAVING COUNT(*) > 1500 to eliminate the products that return totals for fewer than 1500 items sold. La consulta sería la siguiente:The query looks like this:

USE AdventureWorks2012;
GO
SELECT ProductID, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING COUNT(*) > 1500;
GO

N.N. Usar la sugerencia del optimizador INDEXUsing the INDEX optimizer hint

En el ejemplo siguiente se muestran dos formas de usar la sugerencia del optimizador INDEX.The following example shows two ways to use the INDEX optimizer hint. En el primer ejemplo se muestra cómo obligar al optimizador a que use un índice no clúster para recuperar filas de una tabla, mientras que en el segundo ejemplo se obliga a realizar un recorrido de tabla mediante un índice igual a 0.The first example shows how to force the optimizer to use a nonclustered index to retrieve rows from a table, and the second example forces a table scan by using an index of 0.

USE AdventureWorks2012;
GO
SELECT pp.FirstName, pp.LastName, e.NationalIDNumber
FROM HumanResources.Employee AS e WITH (INDEX(AK_Employee_NationalIDNumber))
JOIN Person.Person AS pp on e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO

-- Force a table scan by using INDEX = 0.
USE AdventureWorks2012;
GO
SELECT pp.LastName, pp.FirstName, e.JobTitle
FROM HumanResources.Employee AS e WITH (INDEX = 0) JOIN Person.Person AS pp
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO

M.M. Usar OPTION y las sugerencias GROUPUsing OPTION and the GROUP hints

En el ejemplo siguiente se muestra cómo se usa la cláusula OPTION (GROUP) con una cláusula GROUP BY.The following example shows how the OPTION (GROUP) clause is used with a GROUP BY clause.

USE AdventureWorks2012;
GO
SELECT ProductID, OrderQty, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
WHERE UnitPrice < $5.00
GROUP BY ProductID, OrderQty
ORDER BY ProductID, OrderQty
OPTION (HASH GROUP, FAST 10);
GO

O.O. Usar la sugerencia de consulta UNIONUsing the UNION query hint

En el ejemplo siguiente se usa la sugerencia de consulta MERGE UNION.The following example uses the MERGE UNION query hint.

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, JobTitle, HireDate, VacationHours, SickLeaveHours
FROM HumanResources.Employee AS e1
UNION
SELECT BusinessEntityID, JobTitle, HireDate, VacationHours, SickLeaveHours
FROM HumanResources.Employee AS e2
OPTION (MERGE UNION);
GO

P.P. Usar una instrucción UNION simpleUsing a simple UNION

En el ejemplo siguiente, el conjunto de resultados incluye el contenido de las columnas ProductModelID y Name de las tablas ProductModel y Gloves.In the following example, the result set includes the contents of the ProductModelID and Name columns of both the ProductModel and Gloves tables.

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

-- Here is the simple union.
USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves
ORDER BY Name;
GO

Q.Q. Usar SELECT INTO con UNIONUsing SELECT INTO with UNION

En el ejemplo siguiente, la cláusula INTO de la segunda instrucción SELECT especifica que la tabla denominada ProductResults contiene el conjunto final de resultados de la unión de las columnas designadas de las tablas ProductModel y Gloves.In the following example, the INTO clause in the second SELECT statement specifies that the table named ProductResults holds the final result set of the union of the designated columns of the ProductModel and Gloves tables. Tenga en cuenta que la tabla Gloves se crea en la primera instrucción SELECT.Note that the Gloves table is created in the first SELECT statement.

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.ProductResults', 'U') IS NOT NULL
DROP TABLE dbo.ProductResults;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
INTO dbo.ProductResults
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves;
GO

SELECT ProductModelID, Name 
FROM dbo.ProductResults;

R.R. Usar UNION con dos instrucciones SELECT y ORDER BYUsing UNION of two SELECT statements with ORDER BY

El orden de algunos parámetros empleados con la cláusula UNION es importante.The order of certain parameters used with the UNION clause is important. En el ejemplo siguiente se muestra el uso correcto e incorrecto de UNION en dos instrucciones SELECT en las que se va a cambiar el nombre de una columna en el resultado.The following example shows the incorrect and correct use of UNION in two SELECT statements in which a column is to be renamed in the output.

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

/* INCORRECT */
USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
ORDER BY Name
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves;
GO

/* CORRECT */
USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves
ORDER BY Name;
GO

S.S. Usar UNION de tres instrucciones SELECT para mostrar los efectos de ALL y los paréntesisUsing UNION of three SELECT statements to show the effects of ALL and parentheses

En los siguientes ejemplos se utiliza UNION para combinar los resultados de tres tablas que tienen las mismas 5 filas de datos.The following examples use UNION to combine the results of three tables that all have the same 5 rows of data. En el primer ejemplo se utiliza UNION ALL para mostrar los registros duplicados y se devuelven las 15 filas.The first example uses UNION ALL to show the duplicated records, and returns all 15 rows. En el segundo ejemplo se utiliza UNION sin ALL para eliminar las filas duplicadas de los resultados combinados de las tres instrucciones SELECT y se devuelven 5 filas.The second example uses UNION without ALL to eliminate the duplicate rows from the combined results of the three SELECT statements, and returns 5 rows.

En el tercer ejemplo se utiliza ALL con el primer UNION y los paréntesis incluyen al segundo UNION que no utiliza ALL.The third example uses ALL with the first UNION and parentheses enclose the second UNION that is not using ALL. El segundo UNION se procesa en primer lugar porque se encuentra entre paréntesis. Devuelve 5 filas porque no se utiliza la opción ALL y se quitan los duplicados.The second UNION is processed first because it is in parentheses, and returns 5 rows because the ALL option is not used and the duplicates are removed. Estas 5 filas se combinan con los resultados del primer SELECT mediante las palabras clave UNION ALL.These 5 rows are combined with the results of the first SELECT by using the UNION ALL keywords. Esto no quita los duplicados entre los dos conjuntos de 5 filas.This does not remove the duplicates between the two sets of 5 rows. El resultado final es de 10 filas.The final result has 10 rows.

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.EmployeeOne', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeOne;
GO
IF OBJECT_ID ('dbo.EmployeeTwo', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeTwo;
GO
IF OBJECT_ID ('dbo.EmployeeThree', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeThree;
GO

SELECT pp.LastName, pp.FirstName, e.JobTitle 
INTO dbo.EmployeeOne
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
SELECT pp.LastName, pp.FirstName, e.JobTitle 
INTO dbo.EmployeeTwo
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
SELECT pp.LastName, pp.FirstName, e.JobTitle 
INTO dbo.EmployeeThree
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
-- Union ALL
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeOne
UNION ALL
SELECT LastName, FirstName ,JobTitle
FROM dbo.EmployeeTwo
UNION ALL
SELECT LastName, FirstName,JobTitle 
FROM dbo.EmployeeThree;
GO

SELECT LastName, FirstName,JobTitle
FROM dbo.EmployeeOne
UNION 
SELECT LastName, FirstName, JobTitle 
FROM dbo.EmployeeTwo
UNION 
SELECT LastName, FirstName, JobTitle 
FROM dbo.EmployeeThree;
GO

SELECT LastName, FirstName,JobTitle 
FROM dbo.EmployeeOne
UNION ALL
(
SELECT LastName, FirstName, JobTitle 
FROM dbo.EmployeeTwo
UNION
SELECT LastName, FirstName, JobTitle 
FROM dbo.EmployeeThree
);
GO

Vea tambiénSee Also

CREATE TRIGGER (Transact-SQL) CREATE TRIGGER (Transact-SQL)
CREATE VIEW (Transact-SQL) CREATE VIEW (Transact-SQL)
DELETE (Transact-SQL) DELETE (Transact-SQL)
EXECUTE (Transact-SQL) EXECUTE (Transact-SQL)
Expresiones ( Transact-SQL ) Expressions (Transact-SQL)
INSERT (Transact-SQL) INSERT (Transact-SQL)
COMO ( Transact-SQL ) LIKE (Transact-SQL)
Unión ( Transact-SQL ) UNION (Transact-SQL)
EXCEPTO y INTERSECT ( Transact-SQL ) EXCEPT and INTERSECT (Transact-SQL)
UPDATE (Transact-SQL) UPDATE (Transact-SQL)
DONDE ( Transact-SQL ) WHERE (Transact-SQL)
Ruta de acceso ( Transact-SQL ) PathName (Transact-SQL)
EN la cláusula ( Transact-SQL )INTO Clause (Transact-SQL)