Querys SQL SERVER
ORDEN DE EJECUCIÓN DEL SQL
1.- FROM
2.- WHERE
3.- GROUP BY
4.- HAVING
5.- SELECT
6.- DISTINCT
7.- ORDER BY
8.- TOP
--Creación de base de datos
Create database Clinica
Go
--Para usar la base de datos creada
Use Clinica
go
--Creación de tablas
Create table Paciente
Go
--Llave primaria (PK)
Primary Key
Alter table dbo.categories
Add constraint PK_Categories Primary Key
Clustered (CategoryID)
--Llave Foránea (FK)
Foreign Key
Alter Table dbo.Territories
Add constraint FK_Territories_Region Foreign Key (RegionID)
References dbo.Region (RegionID)
-Chequeos (CHECK)
Valida el campo requerido, como por ejemplo ingresar el N° de DNI solo números y no letras
Alter table Employees with check
Add constraint CK_Birthdate check (Birthdate<getdate())
--Getdate
Te da la fecha actual
Select getdate()
---Constraint por default
Alter table Region add FechaCarga datetime default getdate()
--Indices
Ayuda que la búsqueda se más rápida y que la data sea mas organizada.
Créate nonclustered index IDX_firstname
On employees (FirstName Asc)
--Creación de esquemas
Create Schema ciencias
--Poner en minúscula
select lower(FirstName + ' ' + LastName) as NombreCompleto, city as ciudad
from employees
-- Poner en mayuscula
select upper(FirstName + ' ' + LastName) as NombreCompleto, city as ciudad
from employees
--Ltrim()eliminacion por izquierda
Select ' Eddy Zavala' as Nombbre, ' Chorrillos' as Ciudad
Select Ltrim(' Eddy Zavala') as Nombbre, ltrim(' Chorrillos') as
Ciudad
--Rtrim() eliminacion por derecha
Select ' Eddy Zavala' as Nombbre, ' Chorrillos' as Ciudad
Select rtrim('Eddy Zavala ') as Nombbre, rtrim('Chorrillos ') as
Ciudad
--RTRIM/LTRIM por ambos lados
Select ' Eddy Zavala ' as Nombbre,
' Chorrillos ' as Ciudad
Select rtrim(Ltrim(' Eddy Zavala ')) as Nombbre,
rtrim(Ltrim(' Chorrillos ')) as Ciudad
--substring() extrae los caracteres requeridos
select 'Eddy Zavala Ybañez' as NombreCompleto
select substring('Eddy Zavala Ybañez',6,6) as ApPaterno
--Solucion pdf 6.7
--ejercicio 1
select * from Suppliers
where substring(phone,1,4)='(03)'
select * from Suppliers
where phone like '(03)%'
select * from Suppliers
where left(phone,4)='(03)'
select sqrt(power(abs(round(pi(),2)*-100),2))
--Raiz
select sqrt(9)
--Potencia
select power(5,2)
--absoluto
select (-100)
select abs(-100)
--Solucion del pdf 6.8
--Liste los campos OrderID, ProductID, UnitPrice, Quantity, (UnitPrice *
Quantity) de la tabla OrderDetails
--en donde el campo Discount sea igual a ‘0’ y que los datos numéricos estén
redondeados a dos decimales.
select abs(round(orderID,2)) as NumOrden, abs(round(productId,2))as NumProducto,
abs(round(unitprice,2)) as PrecioUnitario,
abs(round(Quantity,2))as Cantidad, abs(round(unitprice*quantity,2)) as
cantidadXprecio
from [Order Details]
where discount = 0
select orderID, productId,unitprice,Quantity, (unitprice*quantity)
from [Order Details]
where discount = 0
select * from [order details]
--getdate() Devuelve la fecha actual en formato de fecha y hora
select getdate()
--datediff() calcula el intervalo entre dos fechas
select datediff(year,'01/09/1985', getdate()) añoTranscurrido
select datediff(MONTH,'01/09/1985', getdate()) MesesTranscurridos
select datediff(day,'01/09/1985', getdate()) DíasTranscurridos
select @@LANGUAGE
set language 'spanish' --Cambiamos al formato español
select datediff(day,'01/04/2019','31/07/2019') as DiasTrabajados
select datediff(day,'01/04/2019','31/07/2019') as DiasTrabajados
if (month(getdate())>=month('12/10/1985') and day(getdate()) >=day('12/10/1985'))
select datediff(year,'12/10/1985','01/01/2019')
else
select datediff(year,'12/10/1985','31/12/2018')-- Este query funciona cunado el
lenguaje del SQL esta en español
--Datepart --> Devuelve especificada de una fecha
select datepart(year, getdate()) as año
select datepart(MONTH, getdate()) as mes
select datepart(day, getdate()) as dia
select datepart(hour, getdate()) as hora
select datepart(minute, getdate()) as minuto
select datepart(second, getdate()) as segundo
--Datename() Devuelve una cadena de caracteres que representa el parámetro
Datepart de una determidada fecha
select datename(weekday,getdate()),datename(MONTH, getdate())
--Solucion de ejercicio de 6.9
--Crear una consulta utilizando las funciones de fecha DATEDIFF, DATEPART,
GETDATE().
--a. Liste las columnas OrderDate, ShippedDate de la tabla Orders
-- y calcule la diferencia de días entre las dos fechas.
select orderdate, shippeddate, datediff(day,orderdate,shippeddate) as
diferenciaDias
from orders
order by diferenciaDias asc
--b. Liste la columna BirthDate
-- y calcule la edad de los empleados que se encuentran almacenados en la tabla
Employees.
select birthdate, datediff(year, birthdate, getdate()) as edad
from employees
order by datediff(year, birthdate, getdate()) asc
c-- Obtenga la porción del día, mes y año de la columna BirthDate
-- de los empleados que se encuentran almacenados en la tabla Employees
-- en donde la columna Country sea igual a ‘USA’ y la columna City sea igual a
‘Seattle’.
select country, city, birthdate, datepart(year,birthdate)as año,
datepart(month,birthdate)as mes, datepart(day,birthdate)as dia,
datename(year,birthdate)as año, datename(month,birthdate)as mes,
datename(weekday,birthdate)as dia
from employees
--select * from employees
where country ='USA' and city='seattle'
--CONVERSIONES (CONVERT, CAST)
--Convert Convierte el dato a otro tipo de dato
select getdate()
select convert(varchar,getdate())
select convert(varchar,getdate(),112)
declare @valor1 as varchar(10)
declare @valor2 as float
set @valor1='-'
set @valor2=14.5
--select @valor1, @valor2
select convert(int,@valor1) + @valor2
--select
select convert(varchar,getdate())
select cast(getdate()as varchar)
use Northwind
select * from [dbo].[Employees]
--TABLAS TEMPORALES
HAY DOS TIPOS
LOCAL --#tabla
globales --##tabla
select * into #TablaEmpleador from [dbo].[Employees]
select * from #TablaEmpleador
select * into TablaEmpleador from [dbo].[Employees]
where city='london'
select * from TablaEmpleador
drop table TablaEmpleador
select EmployeeID, FirstName, BirthDate from [dbo].[Employees]
select EmployeeID, FirstName, convert(varchar(8),BirthDate,112)as FechaNac from
[dbo].[Employees]
select EmployeeID, FirstName, convert(varchar(8),BirthDate,112)as FechaNac into
EmpleadoResumen from [dbo].[Employees]
select EmployeeID, cast(FirstName as varchar(10)) as PrimerNombre,
convert(varchar(8),BirthDate,112)as FechaNac into EmpleadoResumen
from [dbo].[Employees]
drop table EmpleadoResumen
select EmployeeID, FirstName, FechaNac from EmpleadoResumen
SELECT * from EmpleadoResumen
CONSULTAS AVANZADAS
Group By: Totaliza valores, contar cantidad de clientes,
sumar montos de clientes, determinar el máximo o mínimo valor de
la comisión de cada cliente, hacer el sueldo promedio que tiene
un trabajador, todos estos detalles se hacen con una función de
agrupamiento.
--Sintaxis del group by
select campos*, sum(campo) /* sum(campo) */
from tabla
where crtiterio
group by campos del grupo
having condición de la operación -- por ejemplo sum(campo) >1000
--Donde campos* son los campos del grupo
Consultas_Avanzadas_SQL_20190904
HAVING: Especifica una condición de búsqueda para un
grupo, having solo se puede utilizar con la instrucción
select.
Se utiliza en una cláusula group by .
select distinct city from Employees
select city from employees
group by city
--Ejemplo siguiendo la sintaxis
select country, city, count(*) as cantidadEmpleados from employees
where city in('london', 'seattle')
group by city, Country
select country, city, count(EmployeeID) as cantidadEmpleados from employees
where city in('london', 'seattle')
group by city, Country
select distinct Country, city from employees
select Country, city from employees
select * from employees
--Cantidad de empleados que tienen su region registrada
select country, city,Region, count(region)as can_Empleados from employees
group by country, city, Region
select country, city,Region, count(region)as can_Empleados from employees
where region is not null
group by country, city, Region
--Cantidades de ciudades que hay por país.
select country, count(distinct city)as cat_ciudad_por_país from employees
group by country
select * from [dbo].[Order Details]
where productId='23'
order by ProductID
--Muestra el listado de producto ID únicos de la tabla Order Details
select productID, count(OrderID) from [Order Details]
group by ProductID
--Mostrar El precio untario minimo y maximo por producto de la talbal Order
Details.
select ProductID, min(UnitPrice) as min_precio, max(UnitPrice) as max_precio
from [Order Details]
group by ProductID
--Convert Convierte el dato a otro tipo de dato
select getdate()
select convert(varchar,getdate())
select convert(varchar,getdate(),112)