Sql how to select from select sql

Sql how to select from select sql

Примеры использования инструкции SELECT (Transact-SQL)

В этом разделе приведены примеры применения инструкции SELECT.

A. Использование SELECT для получения строк и столбцов

В следующем примере приведены три примера кода. В ходе выполнения первого примера кода возвращаются все строки (предложение WHERE не указано), а также все столбцы (используется звездочка, * ) таблицы Product базы данных AdventureWorks2012.

Б. Использование SELECT с заголовками столбцов и вычислениями

Данный запрос вычисляет доход от продажи по каждому виду продукции для каждого заказа.

В. Совместное использование DISTINCT и SELECT

Г. Создание таблиц с помощью SELECT INTO

Д. Использование связанных вложенных запросов

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

Коррелированный вложенный запрос также может использоваться в предложении HAVING внешнего запроса. В данном примере осуществляется поиск моделей продуктов, для которых максимальная цена в каталоге в два раза превышает среднюю цену по нему.

В данном примере с помощью двух коррелированных запросов осуществляется поиск сотрудников, продавших определенную продукцию.

Е. Использование GROUP BY

В следующем примере находится общий объем продаж для каждого заказа в базе данных.

Ж. Использование GROUP BY с несколькими группами

В данном примере вычисляются средние цены и объемы продаж за последний год, сгруппированные по коду продукта и идентификатору специального предложения.

З. Использование GROUP BY и WHERE

И. Использование GROUP BY с выражением

В следующем примере производится группировка с помощью выражения. Группировку можно производить только с помощью выражения, не содержащего агрегатных функций.

К. Использование GROUP BY с ORDER BY

В следующем примере для каждого типа продуктов вычисляется средняя цена, а также осуществляется сортировка полученных результатов по возрастанию.

Л. Использование предложения HAVING

В первом из приведенных ниже примеров показывается использование предложения HAVING с агрегатной функцией. В нем производится группировка строк таблицы SalesOrderDetail по коду продукта, а также удаляются строки, соответствующие продуктам, для которых средний объем заказа не превышает пяти. Во втором примере показывается использование предложения HAVING без агрегатной функции.

М. Использование HAVING с GROUP BY

Н. Использование HAVING с SUM и AVG

О. Использование указания оптимизатора INDEX

Н. Использование указаний OPTION и GROUP

П. Использование указания запроса UNION

Т. Использование простого UNION

У. Использование SELECT INTO с UNION

Ф. Использование UNION двух инструкций SELECT с ORDER BY

Х. Использование UNION трех инструкций SELECT для демонстрации эффекта от использования скобок и ALL

SQL SELECT from SELECT

I am trying to build a single select statement from two separate ones.

Basically I have a list of Names in a table which do repeat like so:

I need to do a Select distinct Name from Records which returns John, Joe, Jack, Bob.

I then want to so a Select on another table where I pass in the rows returned above.

Having trouble with the syntax.

Sql how to select from select sql. Смотреть фото Sql how to select from select sql. Смотреть картинку Sql how to select from select sql. Картинка про Sql how to select from select sql. Фото Sql how to select from select sql

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you do not want to return any values from the subquery, you can use either IN or EXISTS

(In most RDBMS the EXISTS is less resource intensive).

If you want to return values from the subquery, you should use JOIN

SIDENOTE These are sample queries, it is possible that you have to fine tune them to match your exact requirements.

Sql how to select from select sql. Смотреть фото Sql how to select from select sql. Смотреть картинку Sql how to select from select sql. Картинка про Sql how to select from select sql. Фото Sql how to select from select sql

Additionally the following should work:

So there are two ways you can go about doing this. One, create a temporary table and perform a join (*actually in retrospect you could also join to your second table as a subquery, or use something like a CTE if you’re using SQL SERVER, but the modifications if you wanted to go that route should be pretty obvious)

Another option would be to perform an IN or EXISTS query using your select query

You might have to modify the syntax slightly, depending on if you are using MySQL or SQL Server (not sure about that later, honestly). But this should get you started down the right path

Nested select statement in SQL Server

Why doesn’t the following work?

I guess my understanding of SQL is wrong, because I would have thought this would return the same thing as

Doesn’t the inner select statement create a result set which the outer SELECT statement then queries?

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You need to alias the subquery.

or to be more explicit

The answer provided by Joe Stefanelli is already correct.

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

More examples of Nested Subqueries.

IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

Выражение SELECT (Transact-SQL)

Указывает столбцы, возвращаемые запросом.

Sql how to select from select sql. Смотреть фото Sql how to select from select sql. Смотреть картинку Sql how to select from select sql. Картинка про Sql how to select from select sql. Фото Sql how to select from select sqlСинтаксические обозначения в Transact-SQL

Синтаксис

Ссылки на описание синтаксиса Transact-SQL для SQL Server 2014 и более ранних версий, см. в статье Документация по предыдущим версиям.

Аргументы

ALL
Указывает, что в результирующем наборе могут появиться повторяющиеся строки. ALL является параметром по умолчанию.

DISTINCT
Указывает, что в результирующем наборе могут появиться только уникальные строки. Значения NULL считаются равными для ключевого слова DISTINCT.

TOP (expression ) [ PERCENT ] [ WITH TIES ]
Указывает на то, что только заданное число или процент строк будет возвращен из результирующего набора запроса. expression может быть либо числом, либо процентом от числа строк.

В целях обратной совместимости использование TOP expression без скобок в инструкциях SELECT поддерживается, но не рекомендуется. Дополнительные сведения см. в разделе TOP (Transact-SQL).

Столбцы, выбираемые в результирующий набор. Список выбора представляет собой серию выражений, отделяемых запятыми. Максимальное число выражений, которое можно задать в списке выбора — 4 096.

*
Указывает на то, что все столбцы из всех таблиц и представлений в предложении FROM должны быть возвращены. Столбцы возвращаются таблицей или представлением, как указано в предложении FROM, и в порядке, в котором они находятся в таблице или представлении.

table_name | view_name | table_alias.*
Ограничивает область * указанной таблицей или представлением.

column_name
Имя возвращаемого столбца. Указывайте квалификатор для аргумента column_name во избежание неоднозначных ссылок, которые могут возникнуть, если в двух таблицах из предложения FROM содержатся столбцы с повторяющимися именами. Например, таблицы SalesOrderHeader и SalesOrderDetail в базе данных AdventureWorks2012 содержат столбцы с именем ModifiedDate. Если в запросе соединяются две таблицы, то данные о дате изменения из таблицы SalesOrderDetail могут быть заданы в списке выбора как SalesOrderDetail.ModifiedDate.

expression
Является константой, функцией, любым сочетанием имен столбцов, констант и функций, соединенных оператором (операторами) или вложенным запросом.

$ROWGUID
Возвращает столбец с идентификаторами GUID строки.

udt_column_name
Имя возвращаемого, определяемого пользователем типа данных CLR столбца.

Среда SQL Server Management Studio возвращает значения определяемого пользователем типа в двоичном представлении. Чтобы вернуть значения пользовательского типа в виде строки или в формате XML, используйте функцию CAST или CONVERT.

property_name
Открытое свойство столбца udt_column_name.

field_name
Открытый элемент данных столбца udt_column_name.

method_name
Открытый метод столбца udt_column_name, принимающий один или несколько аргументов. Метод method_name не может быть методом мутатора.

column_alias
Альтернативное имя, которым можно заменить имя столбца в результирующем наборе запроса. Например, для столбца «quantity» может быть указан псевдоним «Quantity», «Quantity to Date» или «Qty».

Кроме того, псевдонимы используются для указания имен для результатов выражений, например:

column_alias может использоваться в предложении ORDER BY. Однако он не может быть использован в предложениях WHERE, GROUP BY или HAVING. Если выражение запроса является частью инструкции DECLARE CURSOR, column_alias не может использоваться в предложении FOR UPDATE.

Remarks

Длина возвращаемых данных для столбцов типа text или ntext, включенных в список выбора, устанавливается в минимальное значение из следующих: фактический размер столбца text, значение настройки TEXTSIZE сеанса по умолчанию или жестко заданное в приложении ограничение. Чтобы изменить длину возвращаемого текста для сеанса, используйте инструкцию SET. По умолчанию ограничение на длину возвращаемых при помощи инструкции SELECT текстовых данных равно 4 000 байт.

Компонент Компонент SQL Server Database Engine вызывает исключение номер 511 и осуществляет откат транзакции до момента выполнения текущей инструкции, если наблюдается одно из следующих явлений.

Следствием инструкции SELECT является строка результата или строка промежуточной таблицы, превышающая 8 060 байт.

Инструкции DELETE, INSERT или UPDATE производят действия со строкой, превышающей 8 060 байт.

Ошибка возникает в случае, если не указано имя столбца, созданного при помощи инструкции SELECT INTO или CREATE VIEW.

SELECT (Transact-SQL)

Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:

The UNION, EXCEPT, and INTERSECT operators can be used between queries to combine or compare their results into one result set.

Sql how to select from select sql. Смотреть фото Sql how to select from select sql. Смотреть картинку Sql how to select from select sql. Картинка про Sql how to select from select sql. Фото Sql how to select from select sqlTransact-SQL Syntax Conventions

Syntax

To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.

Remarks

Because of the complexity of the SELECT statement, detailed syntax elements and arguments are shown by clause:

The order of the clauses in the SELECT statement is significant. Any one of the optional clauses can be omitted, but when the optional clauses are used, they must appear in the appropriate order.

SELECT statements are permitted in user-defined functions only if the select lists of these statements contain expressions that assign values to variables that are local to the functions.

A four-part name constructed with the OPENDATASOURCE function as the server-name part can be used as a table source wherever a table name can appear in a SELECT statement. A four-part name cannot be specified for Azure SQL Database.

Some syntax restrictions apply to SELECT statements that involve remote tables.

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. The actual physical execution of the statement is determined by the query processor and the order may vary from this list.

The preceding sequence is usually true. However, there are uncommon cases where the sequence may differ.

For example, suppose you have a clustered index on a view, and the view excludes some table rows, and the view’s SELECT column list uses a CONVERT that changes a data type from varchar to integer. In this situation, the CONVERT may execute before the WHERE clause executes. Uncommon indeed. Often there is a way to modify your view to avoid the different sequence, if it matters in your case.

Permissions

Selecting data requires SELECT permission on the table or view, which could be inherited from a higher scope such as SELECT permission on the schema or CONTROL permission on the table. Or requires membership in the db_datareader or db_owner fixed database roles, or the sysadmin fixed server role. Creating a new table using SELECT INTO also requires both the CREATE TABLE permission, and the ALTER SCHEMA permission on the schema that owns the new table.

Examples:

The following examples use the AdventureWorksPDW2012 database.

A. Using SELECT to retrieve rows and columns

This section shows three code examples. This first code example returns all rows (no WHERE clause is specified) and all columns (using the * ) from the DimEmployee table.

This next example using table aliasing to achieve the same result.

This example returns only the rows for DimEmployee that have an EndDate that is not NULL and a MaritalStatus of ‘M’ (married).

B. Using SELECT with column headings and calculations

The following example returns all rows from the DimEmployee table, and calculates the gross pay for each employee based on their BaseRate and a 40-hour work week.

C. Using DISTINCT with SELECT

The following example uses DISTINCT to generate a list of all unique titles in the DimEmployee table.

D. Using GROUP BY

The following example finds the total amount for all sales on each day.

Because of the GROUP BY clause, only one row containing the sum of all sales is returned for each day.

E. Using GROUP BY with multiple groups

The following example finds the average price and the sum of Internet sales for each day, grouped by order date and the promotion key.

F. Using GROUP BY and WHERE

The following example puts the results into groups after retrieving only the rows with order dates later than August 1, 2002.

G. Using GROUP BY with an expression

The following example groups by an expression. You can group by an expression if the expression does not include aggregate functions.

H. Using GROUP BY with ORDER BY

The following example finds the sum of sales per day, and orders by the day.

I. Using the HAVING clause

This query uses the HAVING clause to restrict results.

Источники информации:

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

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