SELECT
trade_date,
symbol,
shares * price AS 'Total Trade',
(
SELECT
COUNT(*)
FROM
trades
WHERE
trade_date > GETDATE() - 365
AND cust_ID = CID --CID is in Customer not the trades which is the only table in this
-- subquery's from clause
) AS 'Count',
(
SELECT
SUM(price) * SUM(shares)
FROM
trades
WHERE
trades.trade_date >= GETDATE() - 365
AND cust_ID = CID
) AS 'Total $ Volume)',
CID AS 'Cust ID',
TRIM(f_name)+' '+l_name AS 'Customer'
FROM
EI.CUSTOMERS
JOIN EI.TRADES
ON
CID = cust_CID
WHERE
shares * price >= 100000
AND trade_date >= GETDATE() -365
ORDER BY
customer;
subquery(nested query)可以使用主查詢中的FROM列出的表中的列
In short, a nested query works independent
of the enclosing SQL statement and can make use of any of the column values
from the tables listed in the enclosing statement's FROM clause. You can use nested queries to perform multi-table operations without having to JOIN rows in multiple related tables. However, if you
need data values from multiple tables, or if you want individual column values and aggregate function values in the same row in the results table, you can nest a subquery with the aggregate function that you need in the SELECT clause of a multi-table query
or JOIN.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.