Cuáles son las características biológicas que están marcadas en tu individual...
Sesión 6
1. [70-461]
Querying Microsoft SQL Server 2012
/ITPROS-DC/ITProsDCITPROS DC
http://itpros-dc.com
COMPARTIR EL CONOCIMIENTO, NUESTRA PASIÓN
2. SESIÓN # 6
• Group By
• Having
• SubConsultas
• Vistas
• Procedimientos Almacenados
• Taller
3. GROUP BY
• GROUP BY crea grupos de registros de acuerdo a lo especificado en la sentencia
GROUP BY
• GROUP BY calcula un un valor de resumen para las funciones de agregación.
SELECT <select_list>
FROM <table_source>
WHERE <search_condition>
GROUP BY <group_by_list>;
SELECT empid, COUNT(*) AS cnt
FROM Sales.Orders
GROUP BY empid;
4. Lógica de GROUP BY • Si una consulta utiliza GROUP BY, en
Adelante todas las fases posteriores
operan sobre los grupos y no sobre los
datos de origen.
• Todas las columnas en SELECT, HAVING,
and ORDER BY deben aparecer en la
clausula GROUP BY.
Logical
Order
Phase Comments
5 SELECT
1 FROM
2 WHERE
3 GROUP BY Creates groups
4 HAVING Operates on groups
6 ORDER BY
5. GROUP BY Workflow
orderid empid custid
10643 6 1
10692 4 1
10926 4 2
10625 3 2
10365 3 3
orderid empid custid
10643 6 1
10692 4 1
10926 4 2
10625 3 2
empid COUNT(*)
6 1
4 2
3 1
GROUP BY empid
WHERE custid IN(1,2)
SELECT orderid, empid, custid
FROM Sales.Orders;
6. GROUP BY con funciones de agregado
• Las funciones de agregación se usan comunmente en la sentencia
SELECT, resumida por grupo.
SELECT productid, MAX(qty) AS largest_order
FROM Sales.OrderDetails
GROUP BY productid;
SELECT custid, COUNT(*) AS cnt
FROM Sales.Orders
GROUP BY custid;
7. HAVING
• HAVING es la condición de busqueda para la sentencia
GROUP BY
• HAVING es procesado despues de GROUP BY
SELECT custid, COUNT(*) AS count_orders
FROM Sales.Orders
GROUP BY custid
HAVING COUNT(*) > 10;
8. SubConsultas
• Son consultas anidadas dentro de consultas
• Resultados de la columna interna pasan a la columna
externa.
• Pueden ser escalares, valores multiples
9. Scalar
• Retorna un solo valor de la consulta
• Puede ser usado en cualquier lugar: SELECT, WHERE, y so
on
• Si la consulta retorna un valor vacio la consulta se vuelve
NULL
SELECT orderid, productid, unitprice, qty
FROM Sales.OrderDetails
WHERE orderid =
(SELECT MAX(orderid) AS lastorder
FROM Sales.Orders);
10. Consulta multiples valores
SELECT custid, orderid
FROM Sales.orders
WHERE custid IN (
SELECT custid
FROM Sales.Customers
WHERE country = N'Mexico');
11. Vistas
CREATE VIEW "NOMBRE_VISTA" AS "Instrucción SQL";
Las vistas pueden considerarse como tablas virtuales. Generalmente hablando, una
tabla tiene un conjunto de definiciones, y almacena datos físicamente. Una vista
también tiene un conjunto de definiciones, que se construye en la parte superior de
la(s) tabla(s) u otra(s) vista(s), y no almacena datos físicamente.
CREATE VIEW HR.EmpPhoneList
AS
SELECT empid, lastname, firstname, phone
FROM HR.Employees;
12. Procedimiento Almacenados
Los procedimientos almacenados pueden recibir y devolver información;
para ello se emplean parámetros, de entrada y salida, respectivamente.
La sintaxis es:
create procedure NOMBREPROCEDIMIENTO
@NOMBREPARAMETRO TIPO =VALORPORDEFECTO
as SENTENCIAS;
Los parámetros se definen luego del nombre del procedimiento,
comenzando el nombre con un signo arroba (@).
13. Procedimientos Almacenados
Creamos un procedimiento que recibe el nombre de un autor como parámetro para mostrar todos los libros del autor
solicitado:
create procedure pa_libros_autor
@autor varchar(30)
as
select titulo, editorial,precio
from libros
where autor= @autor;
El procedimiento se ejecuta colocando "execute" (o "exec") seguido del nombre del procedimiento y un valor para el
parámetro:
exec pa_libros_autor 'Borges';
14. Procedimientos Almacenados
Creamos un procedimiento que recibe 2 parámetros, el nombre de un autor y el de una editorial:
create procedure pa_libros_autor_editorial
@autor varchar(30),
@editorial varchar(20)
as
select titulo, precio
from libros
where autor= @autor and
editorial=@editorial;
El procedimiento se ejecuta colocando "execute" (o "exec") seguido del nombre del procedimiento y los
valores para los parámetros separados por comas:
exec pa_libros_autor_editorial 'Richard Bach','Planeta';
The next topic will review the logical order of operations and expand on the last bullet.
Note: Columns referenced in clauses processed subsequent to the GROUP BY clause must either be specified in a GROUP BY list or in an aggregate function. This is because the output of the GROUP BY clause is a new set (derived from but separate from the set returned by the FROM/WHERE clauses).
The slide images flow clockwise from upper right to lower center, illustrating the phases of the query being processed.
Note: For illustration purposes, the SELECT phase is included, and is depicted as the final query output. The result of the GROUP BY isn't yet a row per group – that's the result of the SELECT. The result of the GROUP BY is that the rows returned from the previous phase (the WHERE) are now associated with their respective groups.
Remind the students that, since the final query result will have only one row per group, the expressions moving forward are restricted to aggregates and columns used in the GROUP BY.
Source queries:
SELECT orderid, empid, custid
FROM Sales.Orders;
SELECT orderid, empid, custid
FROM Sales.Orders
WHERE CUSTID <>3;
SELECT empid, COUNT(*)
FROM Sales.Orders
WHERE CUSTID <>3
GROUP BY empid;
Note: Columns referenced in clauses (HAVING, SELECT) processed subsequent to GROUP BY clause must either be specified in a GROUP BY list or an aggregate function. This is because the output of the GROUP BY clause is a new set (derived from but separate from the set returned by the FROM/WHERE clauses).
You may wish to remind students of the definitions of terms such as predicate, filter, and search condition provided earlier in the course.
Note that self-contained subqueries are easier to test, separate from the outer query.
The example returns details about the most recent order.
This is the error returned if the inner query is not scalar and the outer is written to expect a single value:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when it is used as an expression.
The example returns information about orders placed by customers in Mexico. This may be rewritten as a JOIN:
SELECT c.custid, o.orderid
FROM Sales.Customers AS c JOIN Sales.Orders AS o
ON c.custid = o.custid
WHERE c.country = 'Mexico‘
Point out to the students that sometimes it’s easier to write and test a query one piece at a time, in which case a subquery may be more accessible.
The example returns information about orders placed by customers in Mexico. This may be rewritten as a JOIN:
SELECT c.custid, o.orderid
FROM Sales.Customers AS c JOIN Sales.Orders AS o
ON c.custid = o.custid
WHERE c.country = 'Mexico‘
Point out to the students that sometimes it’s easier to write and test a query one piece at a time, in which case a subquery may be more accessible.