
# 单表查询
示例表：
```
CREATE TABLE newproducts
(
product_id INTEGER,
product_name VARCHAR2(60),
category VARCHAR2(60),
quantity  INTEGER
)
STORE AS orc;
INSERT INTO newproducts VALUES (1502, 'earphones', 'electronics',150);
INSERT INTO newproducts VALUES (1601, 'telescope', 'toys',80);
INSERT INTO newproducts VALUES (1666, 'Frisbee', 'toys',244);
INSERT INTO newproducts VALUES (1700, 'interface', 'books',100);
INSERT INTO newproducts VALUES (2344, 'milklotion', 'skin care',320);
INSERT INTO newproducts VALUES (3577, 'dumbbell', 'sports',550);
INSERT INTO newproducts VALUES (1210, 'necklace', 'jewels', 200);
```
#### 简单查询
通过SELECT ... FROM ... 语句从数据库中获取结果。
```
SELECT category FROM newproducts;
  category
------------
 electr
 sports
 jewels
 toys
 books
 skin care
 toys
(7 rows)
```
#### 对结果进行筛选
通过WHERE语句对查询的结果进行过滤，找到想要查询的部分。
```
SELECT * FROM newproducts WHERE category='toys';
 product_id | product_name | category | quantity
------------+--------------+----------+----------
       1601 | telescope    | toys     |       80
       1666 | Frisbee      | toys     |      244
(2 rows)
```
#### 对结果进行排序
使用ORDER BY语句可以让查询结果按照期望的方式进行排序。
```
SELECT product_id,product_name,category,quantity FROM newproducts ORDER BY quantity DESC;
 product_id | product_name |  category   | quantity
------------+--------------+-------------+----------
       3577 | dumbbell     | sports      |      550
       2344 | milklotion   | skin care   |      320
       1666 | Frisbee      | toys        |      244
       1210 | necklace     | jewels      |      200
       1502 | earphones    | electronics |      150
       1700 | interface    | books       |      100
       1601 | telescope    | toys        |       80
(7 rows)
```
#### 限制结果查询数量
如果需要查询只返回部分结果，可以使用LIMIT语句限制查询结果返回的记录数。
```
SELECT product_id,product_name,category,quantity FROM newproducts ORDER BY quantity DESC limit 5;
 product_id | product_name |  category   | quantity
------------+--------------+-------------+----------
       3577 | dumbbell     | sports      |      550
       2344 | milklotion   | skin care   |      320
       1666 | Frisbee      | toys        |      244
       1210 | necklace     | jewels      |      200
       1502 | earphones    | electronics |      150
(5 rows)
```
#### 聚合查询
可以通过使用GROUP BY语句配合聚合函数，构建一个聚合查询来关注数据的整体情况。
```
SELECT category, string_agg(quantity,',') FROM newproducts GROUP BY category;
  category   | string_agg
-------------+------------
 books       | 100
 electronics | 150
 skin care   | 320
 jewels      | 200
 toys        | 80,244
 sports      | 550
(6 rows)
```
