两个 select 结果的计算(乘法)

Calcul (multiplication) of two select-result

我正在尝试将我从唯一查询的 SELECT 语句中得到的两个数字相乘。我想获得提供者的数量和提案的数量(我所做的查询显示),并在同一行上将两者相乘(我做不到)。

我做了一个非常简单的例子给你看(代码如下):DEMO ON FIDDLE

创建在 2 个部门工作的 2 个提供者:

CREATE TABLE ##Provider
(
  id INT,
  p_name VARCHAR(50),
  id_dep INT
)
INSERT INTO ##Provider (id, p_name, id_dep) VALUES 
    (1, 'toto', 10),
    (2, 'toto', 11),
    (3, 'tata', 9);

为 2 个部门创建 4 个提案:

CREATE TABLE ##Proposal
(
  id INT,
  c_name VARCHAR(50),
  id_dep INT
)
INSERT INTO ##Proposal (id, c_name, id_dep) VALUES 
    (1, 'propA', 10),
    (2, 'propB', 09),
    (3, 'propC', 10),
    (4, 'propD', 10);

创建部门 table :

CREATE TABLE ##Department
(
  id INT,
  d_name VARCHAR(50)
)
INSERT INTO ##Department (id, d_name) VALUES 
    (9, 'dep9')
    ,(10, 'dep10')
    ,(11, 'dep11');

在这里我可以按部门显示供应商和提案的数量(实际查询要复杂得多,所以我想保留 2 个子请求):

    select 
        id,
        d_name,
        nb_provider = (
            SELECT COUNT(DISTINCT Id)
            FROM ##Provider p
            WHERE p.id_dep = dep.id
        ),
        nb_proposal = (
            SELECT COUNT(DISTINCT Id)
            FROM ##Proposal pp
            WHERE pp.id_dep = dep.id
        )
    from ##Department dep
    WHERE dep.id = 10

但我无法显示这两个数字的计算结果:

    select 
        id,
        d_name,
        nb_provider = (
            SELECT COUNT(DISTINCT Id)
            FROM ##Provider p
            WHERE p.id_dep = dep.id
        ),
        nb_proposal = (
            SELECT COUNT(DISTINCT Id)
            FROM ##Proposal pp
            WHERE pp.id_dep = dep.id
        ),
        calcul = (nb_provider * nb_proposal)  --> DOESN'T WORK
    from ##Department dep
    WHERE dep.id = 10

我没有尝试很多,因为我不确定这是否可能...也许我应该使用 UNION ?

我推荐横向连接:

select 
    d.id,
    d.d_name,
    p.nb_provider,
    pp.nb_proposal
    (p.nb_provider * pp.nb_proposal) calcul
from ##department d
outer apply (
    select count(distinct id) nb_provider
    from ##provider p
    where p.id_dep = d.id
) p
outer apply (
    select count(distinct id) nb_proposal
    from ##proposal pp
    where pp.id_dep = d.id
) pp
where d.id = 10