在PostgreSQL(通常簡稱為PgSQL)中,GROUP BY
子句用于將相似的行分組在一起,以便對每個組執行聚合函數
sales_data
的表,其中包含region
(地區)、product
(產品)和revenue
(收入)列:CREATE TABLE sales_data (
id SERIAL PRIMARY KEY,
region VARCHAR(50),
product VARCHAR(50),
revenue NUMERIC(10, 2)
);
INSERT INTO sales_data (region, product, revenue) VALUES
('North America', 'Product A', 1000),
('North America', 'Product B', 2000),
('Europe', 'Product A', 1500),
('Europe', 'Product B', 1800),
('Asia', 'Product A', 2500),
('Asia', 'Product B', 2200);
GROUP BY
子句對數據進行分組。例如,按地區對銷售數據進行分組,并計算每個地區的總收入:SELECT region, SUM(revenue) as total_revenue
FROM sales_data
GROUP BY region;
這將返回以下結果:
region | total_revenue
-------------+---------------
North America | 3000.00
Europe | 3300.00
Asia | 4700.00
SELECT region, product, SUM(revenue) as total_revenue
FROM sales_data
GROUP BY region, product;
這將返回以下結果:
region | product | total_revenue
-------------+-----------+---------------
North America | Product A | 1000.00
North America | Product B | 2000.00
Europe | Product A | 1500.00
Europe | Product B | 1800.00
Asia | Product A | 2500.00
Asia | Product B | 2200.00
這就是在PostgreSQL(PgSQL)中使用GROUP BY
子句進行數據分組的方法。請根據您的需求調整查詢以滿足您的需求。