CREATE TABLE orders(
order_id SERIAL PRIMARY KEY,
purchase_total NUMERIC,
timestamp TIMESTAMPTZ,
customer_id INT
REFERENCES customers(customer_id)
ON DELETE CASCADE);
DELETE FROM customers
WHERE customer_id = 4
RETURNING *;
SELECT customer_id,
MAX(purchase_total)
AS top_order_amt
FROM orders
GROUP BY customer_id
ORDER BY top_order_amt DESC;
SELECT customer_id,
SUM(purchase_total::NUMERIC)
FROM orders
GROUP BY customer_id
ORDER BY sum DESC LIMIT 2;
SELECT * FROM customers;
INSERT INTO orders(purchase_total, timestamp, customer_id)
VALUES('50.50', '2023-06-01 08:01:31.876335-07',
(SELECT customer_id FROM customers WHERE email='[email protected]'))
RETURNING *;
-使用子查询查找了与电子邮件为 ‘[email protected]’ 相对应的“customers”表中的“customer_id”值。
SELECT * FROM orders;
SELECT * FROM bookmarks;
SELECT url, name, COUNT(*)
FROM bookmarks
GROUP BY url, name
HAVING COUNT(*) > 1;
SELECT * FROM bookmarks
WHERE id IN (
SELECT id FROM bookmarks
EXCEPT SELECT MAX(id)
FROM bookmarks
GROUP BY url, name, description)
ORDER BY url, name, description;
DELETE FROM bookmarks
WHERE id IN (
SELECT id FROM bookmarks
EXCEPT SELECT MAX(id)
FROM bookmarks
GROUP BY url, name, description)
RETURNING *;
SELECT * FROM bookmarks;
SELECT o.order_id, o.purchase_total, c.email
FROM orders o
INNER JOIN customers c ON
o.customer_id = c.customer_id;
SELECT p.program_name,
COUNT(s.student_id) AS student_count
FROM programs p
LEFT OUTER JOIN students s ON
p.program_id = s.program_id
GROUP BY p.program_name;
CREATE TEMPORARY TABLE temp_customer_purchases AS
SELECT c.customer_id, c.email,
SUM(o.purchase_total) AS purchases
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.email;
SELECT * FROM temp_customer_purchases;