计数两个表中的记录

时间:2019-04-22 14:20:59

标签: sql postgresql

我在tab1和tab2中有两个表,目标是计算tab2中所有出现的次数,并将它们显示在tab1中存在的ID旁边;

tab1外观:

        var places = [
            "Name of the city",
            "Name of Another City!",
            "Another city..."
        ];

        function getPlaceName(day) {
            var index = day - 1;//day 1 = index 0
            return places[index];
        }

        var date = new Date();
        var day = date.getDate();
        var n = date.getMonth();
        var place = getPlaceName(day);

        document.getElementById("CityName").innerHTML = place;

我想得到:

id
A
B
C
D

tab2:
in  out
A   B
A   B
    C
D   

    D
C   

我正在尝试:

id  countIN countOUT
A   2   0
B   0   2
C   1   1
D   1   1

它仅适用于countIN,我不知道如何为countOUT做

3 个答案:

答案 0 :(得分:1)

尝试此查询

SELECT id, 
(SELECT COUNT(*) FROM tab2 t2 WHERE t2.in = t1.id) AS countIn, 
(SELECT COUNT(*) FROM tab2 t2 WHERE t2.out = t1.id) AS countOut
FROM tab1 t1

答案 1 :(得分:1)

我建议加入两个子查询,每个子查询汇总inout列:

SELECT
    t1.id,
    COALESCE(t2.countIN, 0) AS countIN,
    COALESCE(t3.countOUT, 0) AS countOUT
FROM tab1 t1
LEFT JOIN
(
    SELECT "in", COUNT(*) AS countIN
    FROM tab2
    GROUP BY "in"
) t2
    ON t1.id = t2."in"
LEFT JOIN
(
    SELECT out, COUNT(*) AS countOUT
    FROM tab2
    GROUP BY out
) t3
    ON t1.id = t3.out
ORDER BY
    t1.id;

enter image description here

Demo

答案 2 :(得分:0)

我喜欢横向连接:

select v.id, sum(t2.ins) as ins, sum(t2.outs) as outs
from tab2 t2 left join lateral
     (values (t2.in, 1, 0), (t2.out, 0, 1)) v(id, ins, outs)
group by v.id;

这不使用tab1,因此不会返回0计数(在两列中)。如果您同时需要:

select t1.id, sum(v.ins) as ins, sum(v.outs) as outs
from tab1 t1 left join
     (tab2 t2 left join lateral
      (values (t2.in, 1, 0), (t2.out, 0, 1)) v(id, ins, outs)
     )
     on t1.id = v.id
group by t1.id;