多个表MSSQL查询的计数总和

时间:2016-11-22 18:50:28

标签: sql sql-server

我有以下查询。

SELECT  (
    SELECT
        COUNT (fibre_circuit.data_id) 
    FROM fibre_circuit
        INNER JOIN bus_std_iptv
            ON  bus_std_iptv.d_parent_id = fibre_circuit.data_id
    where fibre_circuit.data_id = 778
) AS Count1,
(
    SELECT
        COUNT (fibre_circuit.data_id)
    FROM fibre_circuit
        INNER JOIN bus_pre_iptv
            ON bus_pre_iptv.d_parent_id = fibre_circuit.data_id
    where fibre_circuit.data_id = 778
) AS Count2,
(
    SELECT
        COUNT (fibre_circuit.data_id)
    FROM
        fibre_circuit
            INNER JOIN iptv
                ON iptv.d_parent_id = fibre_circuit.data_id
    where fibre_circuit.data_id = 778
) AS Count3,
(
    SELECT DISTINCT
        fibre_circuit.data_id
    FROM fibre_circuit
        INNER JOIN bus_std_iptv
            ON bus_std_iptv.d_parent_id = fibre_circuit.data_id
    where fibre_circuit.data_id = 778
)
AS circuit

结果是:

Count 1 | Count 2 | Count 3 | Circuit

3       | 1       | 1       | 778

我需要SUM Count1 + Count2 + Count3才能收到:

Total | Circuit

5     | 778

任何人都可以帮助详细说明正确的查询以获得所需的结果吗?

提前致谢,

米格尔

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT  (  
    SELECT
    COUNT (fibre_circuit.data_id)   
    FROM
    fibre_circuit  
      INNER JOIN
    bus_std_iptv  
    ON
    bus_std_iptv.d_parent_id = fibre_circuit.data_id  
    where
    fibre_circuit.data_id = 778
    )  +  
    (SELECT
    COUNT (fibre_circuit.data_id)  
    FROM
    fibre_circuit  
    INNER JOIN
    bus_pre_iptv  
    ON
    bus_pre_iptv.d_parent_id = fibre_circuit.data_id  
    where
    fibre_circuit.data_id = 778
    ) +  
    (
    SELECT
    COUNT (fibre_circuit.data_id)  
    FROM
    fibre_circuit  
    INNER JOIN
    iptv  
    ON
    iptv.d_parent_id = fibre_circuit.data_id  
    where
    fibre_circuit.data_id = 778  
    ) AS Total,  
    (
    SELECT DISTINCT
    fibre_circuit.data_id  
    FROM
    fibre_circuit  
    INNER JOIN
    bus_std_iptv  
    ON
    bus_std_iptv.d_parent_id = fibre_circuit.data_id  
    where
    fibre_circuit.data_id = 778  
    )
    AS circuit

答案 1 :(得分:0)

如果您在这三张牌桌上有一张主键,您可以加入fibre_circuit,那么您可以这样做:

select
    fc.data_id as [Circuit],
    count(distinct piptv.[whatever primary key there is here]) + 
    count(distinct iptv.[whatever primary key there is here]) +
    count(distinct siptv.[whatever primary key there is here]) as [Tota]
from fibre_circuit fc
    left outer join bus_pre_iptv piptv
        on fc.data_id = piptv.d_parent_id
    left outer join iptv
        on fc.data_id = iptv.d_parent_id
    left outer join bus_std_iptv siptv
        on fc.data_id = siptv.d_parent_id
where fc.data_id = 778
group by fc.data_id