📜  MS SQL Server 中的 Select 语句(1)

📅  最后修改于: 2023-12-03 14:44:24.985000             🧑  作者: Mango

MS SQL Server 中的 Select 语句

在 MS SQL Server 中,SELECT 语句用于从一个或多个表中选择数据。

基本语法

由以下关键字组成:

  • SELECT: 选择要返回的列。
  • FROM: 指定从哪些表中选择。
  • WHERE: 过滤条件。
  • DISTINCT: 返回不同的值。

示例:

SELECT column1, column2, ...
FROM table_name
WHERE condition;
选择全部列

使用 * 来选择表中的所有列。

SELECT * FROM table_name;
选择特定列

使用列名称逗号分隔列表来选择特定列。

SELECT column1, column2, ... FROM table_name;
过滤数据

使用 WHERE 子句来过滤所选的行。

SELECT column1, column2, ...
FROM table_name
WHERE condition;

示例:

SELECT *
FROM customers
WHERE country = 'USA';
使用通配符

WHERE 子句中使用通配符(%_)来匹配模式。

  • % 匹配任意字符。
  • _ 匹配任意单个字符。

示例:

SELECT *
FROM customers
WHERE city LIKE 'L%';

SELECT *
FROM customers
WHERE contact_name LIKE 'A%o';
排序数据

使用 ORDER BY 子句来按照一个或多个列排序数据。

默认情况下,数据按升序排序。使用 DESC 关键字来按降序排序。

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 ASC|DESC, column2 ASC|DESC, ...;

示例:

SELECT *
FROM customers
ORDER BY country ASC;

SELECT *
FROM customers
ORDER BY city DESC, country ASC;
返回唯一值

使用 DISTINCT 关键字返回唯一的值。

SELECT DISTINCT column1, column2, ...
FROM table_name;

示例:

SELECT DISTINCT country
FROM customers;
聚合函数

使用聚合函数来计算数据的汇总值。

  • COUNT: 计算行数。
  • SUM: 计算数字总和。
  • AVG: 计算数字平均值。
  • MAX: 返回最大值。
  • MIN: 返回最小值。

示例:

SELECT COUNT(*) AS total_customers
FROM customers;

SELECT SUM(price) AS total_price
FROM orders;

SELECT AVG(price) AS avg_price
FROM orders
WHERE customer_id = 101;

SELECT MAX(price) AS max_price
FROM orders;

SELECT MIN(price) AS min_price
FROM orders;
分组数据

使用 GROUP BY 子句将数据分组,并使用聚合函数计算每个组的汇总值。

SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;

示例:

SELECT city, COUNT(*) AS total_customers
FROM customers
GROUP BY city;

SELECT country, AVG(price) AS avg_price
FROM orders
GROUP BY country;
过滤分组数据

使用 HAVING 子句来过滤分组数据。

SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING condition;

示例:

SELECT country, COUNT(*) AS total_customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 10;

SELECT country, AVG(price) AS avg_price
FROM orders
GROUP BY country
HAVING AVG(price) > 100;

以上就是 MS SQL Server 中的 SELECT 语句的介绍。希望对你有所帮助!