USE Northwind
SELECT CompanyName, Country, OrderID, OrderDate
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY Country DESC, CompanyName
SELECT CompanyName, Country, OrderID, OrderDate
FROM Customers LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
--TOP: primi n record che escono dalla select
SELECT TOP 10 CustomerID,CompanyName, Country, City
FROM Customers
ORDER BY CompanyName DESC
--DISTINCT: per aver la certezza di tirar fuori record singoli, non doppi
SELECT DISTINCT City, Country
FROM Customers
ORDER BY Country
--Ordine: select, from, where, order by
--WHERE: imponi dei requisiti che devono avere i record che escono dalla SELECT
SELECT CompanyName, Country, OrderID, OrderDate
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
--WHERE Country = 'France'
--WHERE CompanyName Like '%mark%'
--solo i record in cui cn contiene la parola mark
--mettendoli all'inizio o alla fine significa finisce per o inizia per
--WHERE CompanyName > 'Save'
ORDER BY CompanyName
--BETWEEN x AND y: compresi fra
SELECT ProductName, UnitPrice
FROM Products
--WHERE UnitPrice >= 20 AND UnitPrice <= 30
WHERE UnitPrice Between 20 AND 30
--NOT BETWEEN: al di fuori di quell'intervallo
SELECT ProductName, UnitPrice
FROM Products
--WHERE UnitPrice < 20 OR UnitPrice > 30
WHERE UnitPrice Not Between 20 AND 30
--CONVERT: per trasformare una string (adeguatamente formattata)
-- nel tipo specificato nel primo parametro
SELECT OrderID, OrderDate
FROM Orders
WHERE OrderDate >= CONVERT(datetime,'01/04/2017',101)
SELECT CompanyName, Country, OrderID, OrderDate
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
WHERE OrderDate Between CONVERT(datetime, '2017-05-01', 102)
AND CONVERT(datetime,'2017-05-31', 102)
--IN:
--WHERE campo IN ('valorepermesso1', 'valorepermesso2',...)
SELECT CompanyName, City, Country
FROM Suppliers
--WHERE Country = 'Italy' OR Country = 'France' OR Country = 'Germany'
WHERE Country IN ('Italy', 'France', 'Germany')
--Si possono fare delle operazioni direttamente sul select
--I campi già salvati nel database si chiamano "persistenti";
--Quelli battezzati con l'AS si chiamano alias
-- l'AS si può omettere; mettendo "UnitPrice*0.1 TenPercentUP" con lo spazio avrebbe comunque rinominato il campo
-- (l'AS si può usare anche su un campo esistente, non necessariamente su un campo elaborato con un calcolo)
select ProductName, UnitPrice, UnitPrice*0.1 as TenPercentUP
from Products
--gli alias si possono usare anche per le tabelle oltre che per i campi
select CompanyName, OrderDate, ProductName, P.UnitPrice ProdUP, OD.UnitPrice OrderDetailsUP
--from Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
--from Customers AS C INNER JOIN Orders AS O ON C.CustomerID = O.CustomerID
from Customers C
INNER JOIN Orders O ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] OD ON O.OrderID=OD.OrderID
INNER JOIN Products P ON OD.ProductID = P.ProductID
-- Programmabilità->Funzioni
-- ->Funzioni di sistema
select CompanyName, YEAR(OrderDate) AS Anno, ProductName, P.UnitPrice ProdUP, OD.UnitPrice OrderDetailsUP
from Customers C
INNER JOIN Orders O ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] OD ON O.OrderID=OD.OrderID
INNER JOIN Products P ON OD.ProductID = P.ProductID
select CompanyName, YEAR(OrderDate) AS Anno, ProductName, P.UnitPrice ProdUP, OD.UnitPrice OrderDetailsUP
from Customers C
INNER JOIN Orders O ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] OD ON O.OrderID=OD.OrderID
INNER JOIN Products P ON OD.ProductID = P.ProductID
where YEAR(OrderDate) = 2017 -- Anno non può essere usato nella WHERE
order by Anno -- Anno può essere usato nell'ORDER BY
--funzione iif(condizione da verificare, cosa scrivere nel caso vero, cosa scrivere nel caso falso)
select ProductName, IIF(Discontinued=1, UnitPrice, 0) as UP_or_Zero_IfDiscontinued
from Products
--ESERCIZI
--LISTA DEI PRODOTTI NON SOSPESI (DISCONTINUED)
select *
from Products
where Discontinued = 0
GO
-- il go chiude il batch; in questo modo, se anche mandassi in esecuzione tutto, eseguirebbe un pezzo alla volta
--ELENCO DI TUTTI I CLIENTI CHE NON HANNO NEMMENO UN ORDINE
select Customers.CustomerID, OrderID
from Customers left join Orders on Customers.CustomerID=Orders.CustomerID
where OrderID is null
--NB: =null non funziona; bisogna usare IS null
-- perché qualunque operazione logica o matematica con null darebbe come risultato null
--ELENCO DI TUTTE LE NAZIONI DA CUI ACQUISTO PRODOTTI (CAMPO Country di Suppliers)
select distinct Country
from Suppliers
--LISTA DI TUTTI GLI ORDINI VENDUTI A CLIENTI FRANCESI, ITALIANI, TEDESCHI, INGLESI
select * --OrderID, OrderDate, CompanyName, Country
from Orders inner join Customers on Customers.CustomerID=Orders.CustomerID
where Customers.Country IN ('France', 'Italy', 'Germany', 'UK')
--con l'asterisco in select vengono fuori tutti i campi di Customers e di Orders
--LISTA DI TUTTE LE RIGHE ORDINE (DETTAGLIO)
--CHE HANNO UN IMPORTO DI RIGA (QUANTITA * PREZZO UNITARIO - SCONTO) SUPERIORE O UGUALE A 500
select [Order Details].*, (Quantity*(UnitPrice-UnitPrice*Discount)) as boh
from [Order Details]
where (Quantity*(UnitPrice-UnitPrice*Discount))>=500
order by boh asc --desc
--ELENCO DEI NOMI DEI PRODOTTI CON ABBINATE LE LORO CATEGORIE.
--PRODURRE UN CAMPO CHE CHIAMI 'TIPO' CHE VALGA 'DEPERIBILI' SE LA CATEGORIA E' MEAT, DAIRY O SEAFOOD E 'NON DEPERIBILI' NEGLI ALTRI CASI
select ProductName, CategoryName, IIF(CategoryName = 'MEAT/POULTRY' OR CategoryName= 'DAIRY PRODUCTS' OR CategoryName= 'SEAFOOD', 'DEPERIBILI', 'NON DEPERIBILI') as TIPO
from Products inner join Categories on Products.CategoryID=Categories.CategoryID
--equivalente
select ProductName, CategoryName,
IIF(CategoryName IN ('MEAT/POULTRY','DAIRY PRODUCTS','SEAFOOD'), 'DEPERIBILI', 'NON DEPERIBILI') as TIPO
from Products inner join Categories on Products.CategoryID=Categories.CategoryID
-----------------------------------------------
--21 NOVEMBRE
-----------------------------------------------
select *
from customers
--(l'unica cosa che il count non conta sono i valori null)
select count(CustomerID) as NumClienti
from Customers
--GROUP BY
--questa query conta i CustomerID PER OGNI COUNTRY
select Country, count(CustomerID) as NumClienti
from Customers
group by Country
--GROUP BY coppia
-- conta i customerID per ogni combinazione di (Country, City) presente
select Country, City, count(CustomerID) as NumClienti, Count(Region) as N
from Customers
group by Country, City
order by Country
select distinct Country, City
from Customers
--Questo non funzionerebbe, perché ogni Country ha più di un CompanyName
select Country, CompanyName
from Customers
group by Country
--Questo funziona; conta il numero di CompanyName per ogni Country (ogni country ha un singolo conteggio aggregato)
select Country, count(CompanyName)
from Customers
group by Country
--l'HAVING è come un WHERE che si fa dopo il GROUP BY
select country, count(customerID) as N
from customers
group by country
having count(customerID)=1
--
select country, count(customerID) as N
from customers
where country NOT IN ('Ireland','Poland')
group by country
having count(customerID) between 1 and 5
order by country desc
-- ESERCIZI
-- Numero dei SUPPLIERS per ogni Country
select count(supplierID), country
from suppliers
group by country
-- Numero degli EMPLOYEES Per ogni TITLE (Ruolo) disponibile
select count(employeeID), title
from Employees
group by title
-- Elenco degli EMPLOYEES con a fianco il numero degli ordini gestiti da ognuno
select lastname, firstname, count(orderID)
from employees inner join orders on employees.EmployeeID=orders.EmployeeID
group by lastname, firstname
--ELENCO DI TUTTI I CUSTOMERS (CompanyName e Country)
--con a fianco il fatturato (somma degli importi di tutti gli ordini)
--SELEZIONARE SOLO GLI ORDINI DELL'ANNO 2017
select CompanyName, Country, sum(quantity*unitprice*(1-discount)) as fatturato
from customers c inner join orders o on c.CustomerID=o.CustomerID
inner join [Order Details] od on o.orderID=od.orderid
where YEAR(OrderDate)=2017
group by CompanyName, Country
-- ELENCO DI TUTTI I PRODUCTS(ProductName e QuantityPerUnit) con a fianco la quantità venduta
--SELEZIONARE SOLO IL VENDUTO DEL 2016
--solo i prodotti di cui ho venduto almeno 500 pezzi
select ProductName, QuantityPerUnit, sum(quantity)
from Products P inner join [Order Details] OD on P.ProductID=OD.ProductID
inner join orders o on o.OrderID=OD.OrderID
where YEAR(OrderDate)=2016
group by ProductName, QuantityPerUnit
having sum(Quantity)>=500
-- ELENCO DELLE CATEGORIE IN CUI HO UN NUMERO DI PRODOTTI SUPERIORE A 7
-- NON VA BENE
select categoryname, categories.categoryid
from products inner join categories on categories.CategoryID=products.CategoryID
group by categoryname, categories.CategoryID
having count(productid)>7
select CategoryID, COUNT(ProductID) NumProdotti
from Products
group by CategoryID
having count(productid)>7
-- ELENCO DELLE NAZIONI IN CUI HO UN NUMERO DI CLIENTI SUPERIORE AL NUMERO DI CLIENTI CHE HO IN SPAGNA
select country, count(customerid) numClienti
from customers
group by country
having count(customerid)>=
(select count(customerid)
from customers
where country='spain')
----------------------------------------------------------------------------
-- elenco dei prodotti che hanno un prezzo maggiore della media
select *
from Products
where UnitPrice>
(select AVG(UnitPrice)
from Products)
-- tutti gli ordini fatti da clienti di (Argentina, Brasile, Venezuela)
select CompanyName, Country, OrderID, Year(OrderDate) as AnnoOrdine
from Orders O inner join Customers C on o.CustomerID=c.CustomerID
where country in ('Argentina', 'Brazil', 'Venezuela')
--equivalente, tranne per il fatto che non posso tirar fuori alcuni campi
--(abbiamo le sole colonne di Orders*, non di Customers**)
--prendere i clienti in quelle 3 nazioni
--di cui prendo i customerID
select OrderID, Year(OrderDate) as AnnoOrdine
from Orders --*
where CustomerID in
(select CustomerID
from Customers --**
where Country in ('Argentina', 'Brazil', 'Venezuela'))
--VISTA aka VIEW
--una vista è una ISTRUZIONE SELECT SALVATA lato server
--(se cambiano i dati cambia anche la vista, perché ogni volta rifà la select salvata)
--posso salvare una qualunque istruzione select in una vista, ECCETTO SE contiene un "order by"
--la vista viene salvata nella cartella "viste"
--NB: una create view va racchiusa tra due GO, perché deve andare a sqlServer come istruzione singola
--NB2: ciò che viene salvato in realtà è l'istruzione, non l'output
GO
create view ClientiSA as
select CompanyName, Country, OrderID, OrderDate
from Orders O inner join Customers C on o.CustomerID=c.CustomerID
where country in ('Argentina', 'Brazil', 'Venezuela')
GO
--NB3: una vista si usa come una tabella
--NB4: è vero che l'order by non si può mettere all'interno della lista stessa, ma si può mettere qua
select *
from ClientiSA
order by Country desc
--Se voglio MODIFICARE UNA VISTA esistente,
-- uso la stessa sintassi usata per crearne una,
-- ma con **ALTER** al posto di CREATE
GO
alter view ClientiSA as
select CompanyName, Country, OrderID, Year(OrderDate) as AnnoOrdine
from Orders O inner join Customers C on o.CustomerID=c.CustomerID
where country in ('Argentina', 'Brazil', 'Venezuela')
GO
--Crea Tabella
--INTO
--La vista è dinamica: se cambiano i dati cambia anche la vista, perché ogni volta rifà la select salvata
--La tabella creata con INTO invece è statica; la tabella creata si può trovare tra Tabelle
select ProductID, ProductName, UnitPrice, QuantityPerUnit
INTO Cat1 --*
from Products
where CategoryID= 1
--NB: il fatto di aver incluso tra i campi quella che era la Primary Key nella tabella originale,
-- non significa che sarà la PK anche nella nuova tabella creata
--Si può usare ALTER TABLE per modificare la struttura della tabella
--ADD PRIMARY KEY(nomechiave)
ALTER TABLE Cat1 ADD PRIMARY KEY(ProductID)
--Come si fa per dire
-- se la tabella Cat1 esiste già, la cancelli e la rifai;
-- se non esiste, la crei nuova.
--SOLUZIONE
--Object_ID prende 2 parametri:
-- 1) nome dell'oggetto
-- 2) tipo dell'oggetto ('U' significa Usertable, i.e. tabella)
-- 'V' per la view
-- 'TR' per un trigger
--Object_ID può restituire 2 cose
-- 1) un codice identificativo dell'oggetto
-- 2) null se l'oggetto non esiste
--DROP TABLE nometabella serve a cancellare la tabella
IF OBJECT_ID('Cat1', 'U') IS NOT null
DROP TABLE Cat1
select ProductID, ProductName, UnitPrice, QuantityPerUnit
INTO Cat1
from Products
where CategoryID= 1
ALTER TABLE Cat1 ADD PRIMARY KEY(ProductID)
--/SOLUZIONE
--INSERT INTO
-- =/= select ... into
--serve per accodare dei record ad una tabella che già esiste
--Ha 2 sintassi alternative:
-- 1) insert into nometab(campo1,campo2...)
-- VALUES (v1campo1,v1campo2...),(v2campo1,v2campo2...)
-- se ci sono dei vincoli nei campi vanno rispettati, ad esempio:
-- -non null
-- -relazioni con altre tabelle
-- 2) insert into nometab(campo1,campo2...)
-- select campouno, campo2... from altratabella
--prima sintassi
insert into Cat1(ProductName, UnitPrice, QuantityPerUnit)
VALUES ('Nutella Biscuit', 5.5, 'Conf. da 20'),('Oreos',7.0,'Conf. da 8')
--seconda sintassi: al posto di scrivere i valori, selezioniamo i campi (di tipo corrisp) da un'altra tabella
insert into Cat1(ProductName, UnitPrice, QuantityPerUnit)
select ProductName, UnitPrice, QuantityPerUnit
from Products
where CategoryID = 7
--test
select * from Cat1
--UPDATE: per modificare il contenuto di uno o più record (da una tabella alla volta)
-- update nometab
-- set modifica1, modifica2...
--aumentare il prezzo di una categ di prodotti del 20%;
--aggiungere un asterisco al nome del prodotto
update Products
set UnitPrice = UnitPrice*1.2, ProductName= '*' + ProductName
where CategoryID=2 --(questo where si applica ad entrambe le modifiche)
select * from Products
--per togliere l'asterisco
--SUBSTRING(Campo,posizione carattere da cui iniziare, posizione del carattere in cui finire)
-- nella pos del carattere in cui finire avrei potuto anche mettere un numero maggiore della lunghezza
--LEN(campo) mi da la lunghezza massima del campo
update Products
set UnitPrice = UnitPrice/1.2, ProductName=substring(ProductName,2,LEN(ProductName))
where CategoryID=2
update Products
set UnitPrice = UnitPrice*1.2, ProductName= '*' + ProductName
from Products P inner join Categories C on P.CategoryID = C.CategoryID
where CategoryName = 'Beverages'
select * from Products P inner join Categories C on P.CategoryID = C.CategoryID
/*
update Products
set UnitPrice = UnitPrice/1.2, ProductName=substring(ProductName,2,LEN(ProductName))
from Products P inner join Categories C on P.CategoryID = C.CategoryID
where CategoryName='Beverages'
*/
--DELETE
--elimina record interi; non si può buttare via un solo campo
--il delete potrebbe non funzionare se c'è un disallow
delete from Cat1 --svuota TUTTA la tabella
delete from Cat1
where ProductID>76 --svuota solo i record con ID > 76
--ELIMINARE CAMPO
--unico modo per "eliminare" un singolo campo (ammesso che il campo sia nullable)
Update Cat1
SET QuantityPerUnit = null
where ProductID=76
---ESERCIZI
/* Produrre una nuova tabella (pippo - nome a piacere)
-- che contenga l'elenco di tutti gli ordini venduti nel 2016 in italia
- Includere un campo che possa funzionare da chiave
- definire questo campo come PK
- Fare in modo che la tabella si possa costruire più volte*/
select * from Ordini2016
drop table Ordini2016
if OBJECT_ID('Ordini2016', 'U') IS NOT NULL
drop table Ordini2016
select OrderID, OrderDate, CompanyName, Country
INTO Ordini2016 --*
from Orders O INNER JOIN Customers C on O.CustomerID = C.CustomerID
where year(OrderDate)=2016 and Country='Italy'
ALTER TABLE Ordini2016 ADD PRIMARY KEY(OrderID)
/* Produrre una tabella
che contenga tutti i prodotti contenuti in Products con Nome, UnitPrice, CategoryName (da categories)
, Country (da Suppliers) e un campo identity creato appositamente per la tabella,
solo per i prodotti che vengono acquistati da un supplier italiano.
Impostare la PK sul campo Identity.*/
drop table pippo2
drop table ProdottiItaliani
select ProductName, CompanyName, UnitPrice, CategoryName, Country
INTO ProdottiItaliani --*
from Products P left join Categories C on P.CategoryID = C.CategoryID
left join Suppliers S on S.SupplierID=P.SupplierID
where country='Italy'
ALTER TABLE ProdottiItaliani ADD Chiave INT IDENTITY
ALTER TABLE ProdottiItaliani ADD PRIMARY KEY(Chiave)
--modo2 (meglio)
select identity(int) as Id, ProductName, CompanyName, UnitPrice, CategoryName, Country
INTO ProdottiItaliani --*
from Products P left join Categories C on P.CategoryID = C.CategoryID
left join Suppliers S on S.SupplierID=P.SupplierID
where country='Italy'
GO
ALTER TABLE ProdottiItaliani ADD PRIMARY KEY(Id)
select *
from ProdottiItaliani
drop table ProdottiItaliani
/* Aggiornare tutti prezzi della tabella precedente raddoppiandoli
e aggiornare il campo Country da Italy a Italia
- fare in modo che in output si possano leggere i vecchi valori e quelli nuovi*/
--Ogni volta che si fa un update, si genera una tabella "deleted" e una "inserted"
-- che contengono rispettivamente i vecchi valori e quelli nuovi;
update ProdottiItaliani
set UnitPrice=UnitPrice*2, Country='Italia'
output deleted.*, inserted.UnitPrice as NewPrice, inserted.Country as NewCountry
/*
update Pippo2
set UPNuovo=UnitPrice*2, CountryNuovo='Italia'
*/
/* Scrivere un'istruzione che elimini dalla tabella pippo (Ordini2016)
tutti gli ordini di settembre 2016 dopo averli inseriti in una tabella separata opportunamente costruita*/
drop table pippo3
drop table Eliminati
drop table Ordini2016
select * from Eliminati
select * from Ordini2016
select *
INTO Eliminati
from Ordini2016
where (YEAR(OrderDate)=2016 and MONTH(OrderDate)=9)
delete from Ordini2016
where (YEAR(OrderDate)=2016 and MONTH(OrderDate)=9)
/*Creare una tabella inserendo all'interno I campi
NomeSocietà, Città, Paese, Indirizzo da Clienti, più un campo Tipo che contenga il valore -- fisso 'CL'
accodare alla stessa tabella i campi NomeSocietà, Città, Paese, Indirizzo da Fornitori più Tipo = 'FO'
accodare alla stessa tabella il campo NomeSocietà da Corrieri più Tipo = 'CO'*/
Select * from Companies
Select CompanyName,City,Country,Address, 'CL' as Tipo --!!!!!!!
Into Companies
from Customers
insert into Companies(CompanyName,City,Country,Address,Tipo)
select CompanyName, City, Country, Address, 'FO' -- non perché i nomi siano gli stessi; il 1° va nel 1°, il 2° nel 2°, etc
from Suppliers
insert into Companies(CompanyName, Tipo)
select CompanyName, 'CO'
from Shippers
-----------------------------------------------------------------
-----------------------------------------------------------------
-- MANCA LEZIONE SUI TRIGGER --
-----------------------------------------------------------------
-----------------------------------------------------------------
--4-12-2019
select * from categories
------------------------------------
--14-1-2020--
--SIMULAZIONE VERIFICA--
--1. Lista di tutti gli Stores il cui nome compare più di una volta (più di un record con lo stesso
--Name) nella tabella Stores
--Usa il Database AdventureWorks presente su classroom
select name, count(*)
from Stores
group by name
having count(*)>1
--test
select *
from stores
where name='All Cycle Shop' Or name='Aerobic Exercise Company'
--2. Lista degli Stores doppi (stesso Name, stesso AddressLine1, stesso AddressLine2)
select name, AddressLine1, AddressLine2
from Stores
group by name, AddressLine1, AddressLine2
having count(*)=2
--3. Elenco di tutti gli OrderDetails (in Output metti: OrderQty, UnitPrice e UnitPriceDiscount) con
--associati: numero e data dell’Ordine e spese di spedizione (Freight), nome dello Store con
--Country e StateRegion, nome del Prodotto, Colore del prodotto, Nome della Categoria e nome
--della Sottocategoria di prodotto più un campo Tot calcolato nel seguente modo:
--OrderQty*UnitPrice*(1-UnitPriceDiscount)
select OrderQty, UnitPrice, UnitPriceDiscount,
SalesOrderNumber, OrderDate, Freight, s.Name, Country, StateRegion, p.Name, p.Color, pc.Name, psc.Name,
(OrderQty*UnitPrice*(1-UnitPriceDiscount))as Tot
from SalesOrderDetails sod inner join SalesOrderHeader soh on sod.SalesOrderID=soh.SalesOrderID
inner join Stores s on soh.StoreID=s.StoreID inner join Products p on sod.ProductID=p.ProductID
inner join ProductSubcategory psc on psc.ProductSubcategoryID=p.ProductSubcategoryID
inner join ProductCategories pc on pc.ProductCategoryID=psc.ProductCategoryID
--4. Lista di tutti gli Stores che non hanno mai acquistato nulla cioè che non compaiono nella tabella
--SalesOrderHeader (non è detto che ce ne siano)
select *
from Stores
where StoreID NOT IN(
select StoreID
from SalesOrderHeader
)
--modo 2 (meglio)
select *
from Stores s LEFT JOIN SalesOrderHeader soh on s.StoreID = soh.StoreID
where soh.StoreID is null
--5. Lista dei soli prodotti che appartengono alle Categorie ‘Clothing’ e ‘Accessories’
select *
from Products p inner join ProductSubcategory psc on p.ProductSubcategoryID=psc.ProductSubcategoryID
inner join ProductCategories pc on psc.ProductCategoryID=pc.ProductCategoryID
where pc.Name IN ('Clothing','Accessories')
--6. Lista dei soli prodotti appartenenti alla SottoCategoria ‘Mountain Bikes’ di colore ‘Silver’
select *
from Products p inner join ProductSubcategory psc on p.ProductSubcategoryID=psc.ProductSubcategoryID
where psc.Name='Mountain Bikes' and p.Color='Silver'
--7. Lista di tutte le biciclette (Categoria ‘Bikes’) che pesano meno di 15 Libbre
select *
from Products p inner join ProductSubcategory psc on p.ProductSubcategoryID=psc.ProductSubcategoryID
inner join ProductCategories pc on psc.ProductCategoryID=pc.ProductCategoryID
where pc.Name='Bikes' and p.Weight<15
--8. Elenco degli Ordini con associato il nome dello Store in cui lo scarto tra la OrderDate e la
--DueDate è maggiore di 12 giorni.
select *
from SalesOrderHeader soh inner join Stores s on soh.StoreID=s.StoreID
where DueDate-OrderDate>12--in questo caso il risultato è in giorni e va bene lo stesso
--Differenza tra date:
--DateDiff(day, OrderDate, DueDate)
--9. Nome dello Store che ha fatto l’ordine con l’importo (SubTotal) più alto. Includere il numero
--dell’ordine nell’Output.
select s.name, soh.SalesOrderNumber
from SalesOrderHeader soh inner join Stores s on soh.StoreID=s.StoreID
where SubTotal=(
select MAX(subtotal)
from SalesOrderHeader)
--metodo economico ma un po' peggiore
-- fare order by subtotal e select top 1
--10. Nomi degli Stores che hanno fatto l’ultimo ordine prima del 30/04/2014
select s.name, max(soh.OrderDate)
from Stores s inner join SalesOrderHeader soh on s.StoreID=soh.StoreID
group by s.name
having max(soh.OrderDate)<CONVERT(smalldatetime, '2014-04-30', 102)
order by name
--========--
--TRIGGERS--
--========--
--I trigger vanno messi tra due GO
--stampa messaggio a console dopo un qualunque INSERT, UPDATE, DELETE;
-- (INSERT messo a commento perché si può avere un solo trigger che agisce sull'insert di una determinata tabella
-- e volevo crearne un altro dopo)
GO
CREATE TRIGGER pull
ON Cat1
AFTER --INSERT,
UPDATE, DELETE
AS
PRINT 'La tabella Cat1 è stata modificata fdhdgfh'
GO
INSERT INTO Cat1 VALUES ('prodotto2',850,20);
--------------------------------
--------------------------------
--mi creo una tabella CatClone da Cat1
select Cat1.*
into CatClone
from Cat1
--trigger
GO
CREATE TRIGGER Grilletto
ON Cat1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @nome nvarchar(40)
DECLARE @up money
DECLARE @qpu int
BEGIN
-- in questo caso prendo i valori dalla tabella "inserted" (che si crea ogni volta che si fa un insert o update)
-- in altri casi avrei potuto prenderli dalla tabella "deleted" (si crea ogni volta che si fa un delete o update)
SET @nome = (SELECT ProductName+'-Ciccia' FROM inserted)
SET @up = (SELECT UnitPrice FROM inserted)
SET @qpu = (SELECT QuantityPerUnit FROM inserted)
END
INSERT INTO Cat1(ProductName, UnitPrice, QuantityPerUnit)
VALUES(@nome+'-Originale', @up, @qpu)
INSERT INTO CatClone(ProductName, UnitPrice, QuantityPerUnit)
VALUES(@nome+'-Clone', @up, @qpu)
END
GO
INSERT INTO Cat1 VALUES ('NonSo',850,20);