如何组合来自不同表的两个'count'值(2列,NOT union)

时间:2018-02-13 12:21:27

标签: sql count multi-table combiners

我希望用户在2表中获取添加记录的计数。例如,我有一个用户列表(表STF),想知道用户创建了多少产品(在表PV1中)以及他销售了多少产品(在表dpq中),我想显示如下数据: enter image description here

我有这两个查询,并且不知道如何在一个包含3列的表中显示它们...

查询1:

composer update

查询2:

select staff_username,  COUNT(*)  as 'count 1'
from STF right join PV1 on STF.staff_username = PV1.admit_user
group by staff_username, staff_name + ' ' + staff_family

2 个答案:

答案 0 :(得分:1)

我想你想要合并两个表count,你可以join并添加count

但是你给我们的信息较少,所以我不确定。

SELECT
    STF.staff_username,
    STF.Data_in_PV1,
    dpq.Data_in_dpq
FROM
(
    SELECT
        staff_username,
        COUNT(PV1.admit_user) AS 'Data_in_PV1'
    FROM
        STF
    RIGHT JOIN
        PV1
    ON
        STF.staff_username = PV1.admit_user
    GROUP BY
        staff_username
) STF 
INNER JOIN
(
    SELECT
        dpq.trf_staff_id,
        COUNT(trf_staff_id) AS 'Data_in_dpq'
    FROM
        dpq
    INNER JOIN
        stf
    ON
        dpq.trf_staff_id = stf.staff_username
    GROUP BY
        dpq.trf_staff_id 
) dpq ON dpq.trf_staff_id = STF.staff_username

答案 1 :(得分:1)

您可以尝试加入两个这样的查询。从您提供的有限信息来看,似乎staff_username与trf_staff_id相同,因为您在第二个查询的连接条件中使用了它。

SELECT
    staff_username,
    count_1,
    count_2 FROM
    (
        SELECT
            staff_username,
            COUNT(*) AS count_1
        FROM
            STF
        RIGHT JOIN
            PV1
        ON
            STF.staff_username = PV1.admit_user
        GROUP BY
            staff_username,
            staff_name + ' ' + staff_family ) QRY_CNT_1 INNEER JOIN
    (
        SELECT
            trf_staff_id,
            COUNT(trf_staff_id) AS count_2
        FROM
            dpq
        JOIN
            stf
        ON
            trf_staff_id = stf.staff_username
        GROUP BY
            trf_staff_id ) QRY_CNT_2 ON
    QRY_CNT_2.trf_staff_id = QRY_CNT_1.staff_username