Примеры использования инструкции select (transact-sql)select examples (transact-sql)

Пример — сортировка результатов по относительной позиции

Вы также можете использовать SQL оператор ORDER BY для сортировки по относительной позиции в наборе результатов, где первое поле в наборе результатов равно 1, второе поле равно 2, третье поле равно 3 и т.д. В этом примере у нас есть таблица products со следующими данными:

product_id product_name category_id
1 Pear 50
2 Banana 50
3 Orange 50
4 Apple 50
5 Bread 75
6 Sliced Ham 25
7 Kleenex NULL

Теперь введите следующий SQL оператор.

PgSQL

SELECT product_id,
product_name
FROM products
WHERE product_name <> ‘Bread’
ORDER BY 1 DESC;

1
2
3
4
5

SELECTproduct_id,

product_name

FROMproducts

WHEREproduct_name<>’Bread’

ORDERBY1DESC;

Будет выбрано 6 записей. Вот результаты, которые вы должны получить.

product_id product_name
7 Kleenex
6 Sliced Ham
4 Apple
3 Orange
2 Banana
1 Pear

В этом примере результаты сортируются по полю product_id в порядке убывания, поскольку поле product_id находится в позиции № 1 в наборе результатов и будет эквивалентно следующему SQL оператору ORDER BY.

PgSQL

SELECT product_id,
product_name
FROM products
WHERE product_name <> ‘Bread’
ORDER BY product_id DESC;

1
2
3
4
5

SELECTproduct_id,

product_name

FROMproducts

WHEREproduct_name<>’Bread’

ORDERBYproduct_idDESC;

Difference between SELECT COUNT, COUNT(*) and SQL COUNT distinct

COUNT

Count(*)

Count(Distinct)

It returns the total number of rows after satisfying conditions specified in the where clause.

It returns the total number of rows after satisfying conditions specified in the where clause.

It returns the distinct number of rows after satisfying conditions specified in the where clause.

It gives the counts of rows. It does not eliminate duplicate values.

It considers all rows regardless of any duplicate, NULL values.

It gives a distinct number of rows after eliminating NULL and duplicate values.

It eliminates the NULL values in the output.

It does not eliminate the NULL values in the output.

It eliminates the NULL values in the output.

Практическое упражнение №3

На основании таблиц suppliers и orders ниже, выберите поля supplier_id и supplier_name из таблицы suppliers, и выберите поле order_date из таблицы orders, где значение поля supplier_id в таблице suppliers соответствует значению поля supplier_id в таблице orders. Сортировать результаты по supplier_id в порядке убывания.

Oracle PL/SQL

—создаем таблицу suppliers
CREATE TABLE suppliers
( supplier_id int NOT NULL,
supplier_name char(50) NOT NULL,
city char(50),
state char(25),
CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);
—вставляем записи в таблицу suppliers
insert into suppliers values (1,’Mari’,’Houston’,’Texas’);
insert into suppliers values (2,’Frida’,’ Melbourne’, ‘Florida’);
insert into suppliers values (3,’Madlen’,’Phoenix’,’Arizona’);
insert into suppliers values (4,’Valentina’,’San Diego’,’California’);
insert into suppliers values (5,’Amba’,’Jacksonville’,’Florida’);

1
2
3
4
5
6
7
8
9
10
11
12
13
14

—создаем таблицу suppliers

CREATETABLEsuppliers
(supplier_idintNOTNULL,

supplier_namechar(50)NOTNULL,

citychar(50),

statechar(25),

CONSTRAINTsuppliers_pkPRIMARYKEY(supplier_id)
);
—вставляем записи в таблицу suppliers

insertintosuppliersvalues(1,’Mari’,’Houston’,’Texas’);

insertintosuppliersvalues(2,’Frida’,’ Melbourne’,’Florida’);

insertintosuppliersvalues(3,’Madlen’,’Phoenix’,’Arizona’);

insertintosuppliersvalues(4,’Valentina’,’San Diego’,’California’);

insertintosuppliersvalues(5,’Amba’,’Jacksonville’,’Florida’);

Содержимое таблицы suppliers:

supplier_id supplier_name city state
1 Mari Houston Texas
2 Frida Philadelphia Pennsylvania
3 Madlen Phoenix Arizona
4 Valentina SanDiego California
5 Amba Jacksonville Florida

Oracle PL/SQL

—создаем таблицу orders
CREATE TABLE orders
( order_id int NOT NULL,
supplier_id int NOT NULL,
order_date date NOT NULL,
quantity int,
CONSTRAINT orders_pk PRIMARY KEY (order_id)
);
—вставляем записи в таблицу orders
insert into orders values (1,1,’05.05.2014′,100);
insert into orders values (2,3,’12.02.2015′,300);
insert into orders values (3,5,’12.01.2016′,500);

1
2
3
4
5
6
7
8
9
10
11
12

—создаем таблицу orders

CREATETABLEorders
(order_idintNOTNULL,

supplier_idintNOTNULL,

order_datedateNOTNULL,

quantityint,

CONSTRAINTorders_pkPRIMARYKEY(order_id)
);
—вставляем записи в таблицу orders

insertintoordersvalues(1,1,’05.05.2014′,100);

insertintoordersvalues(2,3,’12.02.2015′,300);

insertintoordersvalues(3,5,’12.01.2016′,500);

Содержимое таблицы orders:

order_id supplier_id order_date quantity
1 1 05.05.2014 100
2 3 12.02.2015 300
3 5 12.01.2016 500

Introduction to PostgreSQL SELECT DISTINCT clause

The clause is used in the statement to remove duplicate rows from a result set. The clause keeps one row for each group of duplicates. The clause can be applied to one or more columns in the select list of the statement.

The following illustrates the syntax of the  clause:

In this statement, the values in the column are used to evaluate the duplicate.

If you specify multiple columns, the clause will evaluate the duplicate based on the combination of values of these columns.

In this case, the combination of values in both and columns will be used for evaluating the duplicate.

PostgreSQL also provides the  to keep the “first” row of each group of duplicates using the following syntax:

The order of rows returned from the statement is unspecified therefore the “first” row of each group of the duplicate is also unspecified.

It is a good practice to always use the clause with the  to make the result set predictable.

Notice that the expression must match the leftmost expression in the clause.

Описание

SQL оператор EXCEPT используется для возврата всех строк в первом операторе SELECT, которые не возвращаются вторым оператором SELECT. Каждый оператор SELECT будет определять набор данных. Оператор EXCEPT извлечет все записи из первого набора данных, а затем удалит из результатов все записи из второго набора данных.

Запрос Except

Пояснение: Запрос EXCEPT вернет записи в синей заштрихованной области. Это записи, которые существуют в наборе данных SELECT1, а не в наборе данных SELECT2.

Каждый оператор SELECT в запросе EXCEPT должен иметь одинаковое количество полей в наборах результатов с одинаковыми типами данных.

Подсказка: оператор EXCEPT поддерживается не во всех базах данных SQL. Он может использоваться в таких базах данных, как SQL Server, PostgreSQL и SQLite.

Для таких баз данных, как Oracle, используйте оператор MINUS для выполнения этого типа запроса.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector