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.
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;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值