在PostgreSQL(通常簡稱為PgSQL)中,GROUP BY
子句用于將相似的數(shù)據(jù)行分組在一起,以便對每個組執(zhí)行聚合函數(shù)
sales_data
的表,其中包含region
(地區(qū))、product
(產(chǎn)品)和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
子句對數(shù)據(jù)進(jìn)行分組和聚合計算。例如,按地區(qū)和產(chǎn)品對銷售數(shù)據(jù)進(jìn)行分組,并計算每個組的總收入:SELECT region, product, SUM(revenue) as total_revenue
FROM sales_data
GROUP BY region, product;
這將返回以下結(jié)果:
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
在此示例中,我們使用了SUM()
聚合函數(shù)來計算每個組的總收入。除了SUM()
之外,還有許多其他聚合函數(shù)可用于PostgreSQL,如COUNT()
、AVG()
、MIN()
和MAX()
等。您可以根據(jù)需要選擇適當(dāng)?shù)木酆虾瘮?shù)來滿足您的查詢需求。