使用一个选择中的别名在另一选择中使用

问题描述 投票:0回答:1

我觉得问这个琐碎的问题有点可笑,但我对 SQL 的了解不是很好!

好吧,我的桌子看起来像这样

TransactionID     Establishment    Client

TR001             Estab1           XXX
TR002             Estab1           YYY
...
TR00X             EstabN           XXX

我需要计算每个机构对特定客户(XX、YY 和 ZZ)的销售额,以及该数字与该机构完成的所有销售额相比的总百分比。结果应该是这样的:

Establishment    Client    Nbr_Sales    %Total_sales

Estab1           XXX       64           0.35%
Estab1           YYY       321          0.17%
Estab2           XXX       2325         25%
...

我写了一个请求来获取每个机构的销售总数:

SELECT Establishment, Count(*) AS tot_sales_by_estab
FROM data_list 
GROUP BY Establishment;

此请求为我提供了每个机构对“XX”“YY”和“ZZ”客户完成的销售总数

SELECT Establishment, Client, Count(*) as Nbr_Sales
FROM data_list 
WHERE Client = 'XX' OR Client = 'YY' OR Client = 'ZZ'
GROUP BY Establishment, Client;

我只需要使用之前的别名“tot_sales_by_estab”向此请求添加另一列,然后执行类似的操作

ROUND((Nbr_Sales / tot_sales_by_estab)*100, 4) AS %Total_sales

但我不知道该怎么做

sql ms-access
1个回答
0
投票

如果您提供示例输入和输出,以便我们进行测试,会更容易。

为了连接两个结果集,我们通常使用 JOIN。

结果集中的公共列是Establishment,因此我们可以使用Establishment进行INNER JOIN。

total_sales
client_sales
是 CTE,本质上包含您提供的代码。

WITH total_sales AS (
    SELECT 
        Establishment, 
        COUNT(*) AS tot_sales_by_estab
    FROM 
        data_list 
    GROUP BY 
        Establishment
),

client_sales AS (
    SELECT 
        Establishment, 
        client, 
        COUNT(*) AS Nbr_Sales
    FROM 
        data_list 
    WHERE 
        client IN ('XXX', 'YYY', 'ZZZ')
    GROUP BY 
        Establishment, client
)

SELECT 
    cs.Establishment,
    cs.Client,
    cs.Nbr_Sales,
    ROUND((cs.Nbr_Sales * 100.0 / ts.tot_sales_by_estab), 2) AS %Total_sales
FROM 
    client_sales cs
INNER JOIN 
    total_sales ts ON cs.Establishment = ts.Establishment
ORDER BY 
    cs.Establishment, cs.Client;
© www.soinside.com 2019 - 2024. All rights reserved.