Use TSQL
Use TSQL
Use TSQL
from Sales.Customers
------------------------------------------
-- OJO: Para texto en filtros usar -> ' ' y para números (van solos) ejm -> 7,8,9
from Sales.Customers
from Sales.Customers
where custid = 17
-- Leer todos los clientes que son de Mexico, España y USA:
-- traer solo a los que son del país de France, Spain, Brazil
where custid >= 35 and custid <=80 ---> para evitar el doble filtro utilizar el between
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
-- Tipos de Datos:
-- Texto -> varchar(50) "caracteres no definidos" , char(8) "caracteres definidos"
-- OJO:
--> ejemplo dni 04678944 en texto -> llegará así -> 4678944 en número
IdAlumno int,
Nombres varchar(50),
Edad int,
MesCumpleaños varchar(15)
where IdAlumno=5
where IdAlumno=5
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
where contactname like '_a_a%' --- empiecen con "A" en la segunda y cuarta letra
------------------------------------------------------------------------------
select (5+5*5/5)-1
------------------------------------------------------------------------------------------
companyname as Compañia,
contactname as NombreContacto,
city as Ciudad,
country as País,
from Sales.Customers
------------------------------------------------------------------------------------------
-- EJEMPLOS:
-------------
-- SEGMENTOS
-------------
end as Segmento_Cliente
from Sales.Customers
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
IdAlumno int,
Nombres varchar(50),
Edad int,
MesCumpleaños varchar(15)
-------------------------------------------------
------------------------------------------------
-- LLAVES:
Nombres varchar(50) )
Nombre varchar(50) )
IdAlumno int,
IdProfesor int,
IdAsignatura int,
Fecha date,
---------------------------------------------------------
---------------------------------------------------------
from Sales.Customers
from Sales.Customers
from Sales.Customers
-- Uso del OR
from Sales.Customers
from Sales.Customers
from Sales.Customers
-- Texto -> varchar(50) -> Se lee con comillas simples -> Ejm. country='Canada'
-- Número -> enteros -> int -> no lleva comillas simples -> Ejm. custid=5
-- Número -> decimal -> decimal(18,2) -> Ejm. VentaTotal > 500.50
-- Fecha -> date -> YYYY/MM/DD -> '2007/10/17' -> Se lee con comillas simples
-----------------------------------------------------------
-------------------------------------------
--- Black
end as Segmento_Cliente
from Sales.Customers
--- OTRA CONDICIONAL -> USO DEL IIF (IGUAL AL SI DEL EXCEL)
from Sales.Customers
-------------------------------------------------------------------------------
USE TSQL ---> Nosotros le decimos que haga referencia a esa BD!!!
-------------------------------------------------------------------------------
---------------------
from Production.Products as A
---------------------------------------
-- USO DE SUBCONSULTAS
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
FROM Sales.Orders
GROUP BY custid
from Sales.Customers as A
group by A.custid
order by 2
-- Uso de Joins
from Sales.Orders as O
-- Claúsulas de BD
-- Quiero hallar la cantidad de ordenes por año:
from Sales.Orders
group by year(orderdate)
from Sales.Orders as O
group by YEAR(orderdate)
from Sales.Orders as O
group by YEAR(orderdate),OD.orderid
from Sales.Orders
from Production.Products
group by categoryid
from Production.Products as P
group by S.companyname
from Production.Products
---------
into #TablaEjemplo
from Production.Products
group by categoryid
from Production.Products
group by categoryid
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-- Uso de Vistas
as
from Production.Products as P
group by S.companyname
select * from
(
from Sales.Orders
) as Tablon
select *,
from Production.Products
select categoryid,
COUNT(productid) as ConteoProductos,
from Production.Products
group by categoryid
select categoryid,
COUNT(productid) as ConteoProductos,
group by categoryid
select custid,contactname,address,city,country
from Sales.Customers
select custid,contactname,address,city,country
from Sales.Customers
where custid not in (select custid from Lista_Negra) -- Descartando a Lista Negra
-----
FROM Sales.Orders
GROUP BY custid
ORDER BY 1 asc
GROUP BY custid
ORDER BY 1 asc
--- Solo quedate con las categorías que tienen más de 6 productos
from Production.Products
group by categoryid
into #TablaBase
from Sales.Orders as o
group by o.custid,o.orderid
order by o.custid
into #TablaMax
from #TablaBase
group by custid
order by 1
select * from #TablaBase where custid=1
from #TablaMax as a
order by 1
--------------------------------------------------------------------------------
from Sales.Orders as o
group by o.custid,o.orderid
) as Resultado
where RankByVentaTotal = 1
-----------------------------------------------------------------------------------------
---------
-- Uso de Having!!!!
select orderid,
count(productid) as ConteoProd ,
SUM(qty*unitprice) as VentaTotal,
MAX(qty*unitprice) as VentaTotalMAX
from Sales.OrderDetails
group by orderid
order by 1 desc
-----------------------------------------------------------------------------------
select shipcountry,
YEAR(orderdate) as Año,
MONTH(orderdate) as Mes,
COUNT(orderid) as ConteoOrdenes
from Sales.Orders
group by shipcountry,YEAR(orderdate),MONTH(orderdate)
select shipcountry,
YEAR(orderdate) as Año,
MONTH(orderdate) as Mes,
COUNT(orderid) as ConteoOrdenes,
from Sales.Orders
group by shipcountry,YEAR(orderdate),MONTH(orderdate)
select productid,productname,categoryid,unitprice,
from Production.Products
-------------------------------------------------------------------------------
---Uso de Cte's
;with cte_ejemplo as
select productid,productname,categoryid,unitprice,
from Production.Products
),
cte_test2 as
),
cte_test3 as
UNION ALL--- muestra toda la unión de todos los registros de ambas tablas (incluído
duplicados)
INTERSECT
select country, region, city from Sales.Customers -- solo va leer esto ---> excluyendo el
resultado de abajo
EXCEPT
----
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
as
group by custid
exec sp_miprimersp2021
----- PASO N° 2
set @var=28
group by custid
exec sp_miprimersp2021
---- PASO N° 3
as
--set @var=28
group by custid
---------------------------------------------
-- Ejercicio N° 1 - SP
as
begin
end
exec sp_ejercicio1 3
as
begin
from Sales.Orders
group by custid
end
---------------------------------------------
begin
end
exec SP_INFO2008 14
-----------------------------------------------------------------------
as
begin
end
-------------------------------------------------------------
--- Crear un procedimiento que inserte las ordenes de un cliente específico (@custid)
---
as
begin
--- Paso 1
--- Paso 2
end
exec SP_INSERCIONORDEN 35
-----
from Sales.OrderDetails as od
------------
select *, RANK() OVER(partition by categoryid
from Production.Products
USE AdventureWorks
SalesQuota AS CurrentQuota,
FROM Sales.SalesPersonQuotaHistory
----------
--------
-----------------------------------------------------------------------------------------------------------
--NOMBRE : SP_TEST
--SCHEMA : STG
--TIPO : SQL
--VERSIONES :
-----------------------------------------------------------------------------------------------------------
AS
BEGIN TRY
IF @TipoCarga=0
IF @TipoCarga=1
END TRY
BEGIN CATCH
END CATCH
GO
GO
GO
USE EmpData4;
GO
EmpID INT PRIMARY KEY, ---> Llave primaria (solo aceptará ID únicos)
EmailAddress NVARCHAR(50),
SickLeave INT,
SalesYTD MONEY,
NatID NVARCHAR(15),
PhoneNumber NVARCHAR(25));
GO
FROM AdventureWorks.HumanResources.Employee e
-- Creamos un usuario al cual le asignaremos los permisos para que vea nuestra tabla EmpInfo
GO
REVERT;
ALTER COLUMN SickLeave INT MASKED WITH (FUNCTION = 'random(1, 50)') NOT NULL;
-------------------------------------------------------------------------------------------------
--- Máscara parcial -- Funciona mejor para los datos como números de tarjetas de crédito o ID -
--
--- Aplicando una máscara parcial reemplazando los 5 primeros caracteres por 'xxxxx'
ALTER COLUMN NatID NVARCHAR(15) MASKED WITH (FUNCTION = 'partial(0, "xxxxx", 4)') NOT
NULL;
--- Aplicando una máscara parcial si es un Celular, solo mostrando los 4 primeros caracteres:
--- Aplicando una máscara parcial si es un Celular, solo mostrando los 4 primeros caracteres:
name ColumnName,
masking_function MaskFunction
FROM sys.masked_columns