Advertisement
favmatteo

Untitled

Jun 21st, 2023
1,679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 2.21 KB | None | 0 0
  1. CREATE TABLE Products (
  2.     product_id INT PRIMARY KEY,
  3.     product_name VARCHAR(50),
  4.     category_id INT,
  5.     price DECIMAL(10, 2)
  6. );
  7.  
  8. INSERT INTO Products (product_id, product_name, category_id, price)
  9. VALUES
  10.     (1, 'TV', 1, 500.00),
  11.     (2, 'Phone', 1, 800.00),
  12.     (3, 'Laptop', 2, 1200.00),
  13.     (4, 'Headphones', 3, 100.00);
  14.  
  15.    
  16.    CREATE TABLE Categories (
  17.     category_id INT PRIMARY KEY,
  18.     category_name VARCHAR(50)
  19. );
  20.  
  21. INSERT INTO Categories (category_id, category_name)
  22. VALUES
  23.     (1, 'Electronics'),
  24.     (2, 'Computers'),
  25.     (3, 'Audio');
  26.  
  27.    
  28.    CREATE TABLE Customers (
  29.     customer_id INT PRIMARY KEY,
  30.     customer_name VARCHAR(50),
  31.     city VARCHAR(50)
  32. );
  33.  
  34. INSERT INTO Customers (customer_id, customer_name, city)
  35. VALUES
  36.     (1, 'John Smith', 'New York'),
  37.     (2, 'Alice Johnson', 'London'),
  38.     (3, 'Michael Brown', 'Paris'),
  39.     (4, 'Maria Rodriguez', 'Berlin');
  40.  
  41.    CREATE TABLE Orders (
  42.     order_id INT PRIMARY KEY,
  43.     order_date DATE,
  44.     customer_id INT,
  45.     product_id INT,
  46.     quantity INT,
  47.     FOREIGN KEY (customer_id) REFERENCES Customers (customer_id),
  48.     FOREIGN KEY (product_id) REFERENCES Products (product_id)
  49. );
  50.  
  51. INSERT INTO Orders (order_id, order_date, customer_id, product_id, quantity)
  52. VALUES
  53.     (1, '2023-06-01', 1, 2, 2),
  54.     (2, '2023-06-02', 2, 1, 1),
  55.     (3, '2023-06-03', 3, 3, 1),
  56.     (4, '2023-06-04', 4, 2, 3);
  57.    
  58.    
  59. -- Scrivi una query che restituisca il nome del cliente e
  60. -- il numero di ordini effettuati in una determinata città,
  61. -- ordinando i risultati in base al numero di ordini in ordine decrescente.
  62.  
  63. select c.*, count(o.order_id) as 'N ordini'
  64. from Orders o
  65. right join Customers c on o.customer_id = c.customer_id
  66. where c.city = 'Berlin'
  67. group by c.customer_id
  68. order by count(o.order_id) desc
  69.  
  70.  
  71. -- Scrivi una query che restituisca il nome del prodotto e il numero
  72. -- di clienti diversi che lo hanno acquistato, mostrando solo i prodotti con almeno 3 clienti diversi.
  73. select p.product_name, count(c.customer_id) as 'Numero clienti'
  74. from Products p
  75. left join Orders o on o.product_id = o.product_id
  76. left join Customers c on c.customer_id = o.customer_id
  77. group by p.product_id
  78. having count(p.product_id) >= 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement