2017-01-09 98 views
0

以下为TXN表的架构 -PostgreSQL的:计数根据不同的项目在不同的列

ID | SrcNO | DstNO | SrcCountry | DstCountry | Type | 
    1  A   B   USA   UK   RECV 
    2  A   B   USA   UK   RECV 
    3  B   H   UK   IND  SEND 
    4  C   D   UK   GER  SEND 

目的是从SrcNO英国/ DstNo到其他国家抓住txns的计数。换句话说,我希望将TXN的的计数,其中英国是SrcCountry/DstCountry任何SrcNo/DstNo分别 -

No | Country | Send | RECV 
    B  USA  0  2 
    B  IND  1  0 
    B  GER  0  0 
    C  USA  0  0 
    C  IND  0  0 
    C  GER  1  0 

备注 - 由于没有对于B与GER和C任何TXN发送/ recv的与美国,IND我们必须显示两个案件SEND/RECV计数为0。

任何帮助,将不胜感激。

+0

“C”,“H”和“D”的“否”值发生了什么? –

回答

0

如何:

select country, No, sum(send) as send, sum(recv) as recv 
from ((select srcCountry as country, dstNo as No, 1 as send, 0 as recv 
     from t 
     where dstCountry = 'UK' and type = 'SEND' 
    ) union all 
     (select srcCountry as country, dstNo as No, 0 as send, 1 as recv 
     from t 
     where dstCountry = 'UK' and type = 'RECV' 
    ) union all 
     (select destCountry as country, dstNo as No, 1 as send, 0 as recv 
     from t 
     where srcCountry = 'UK' and type = 'SEND' 
    ) union all 
     (select dstCountry as country, dstNo as No, 0 as send, 1 as recv 
     from t 
     where srcCountry = 'UK' and type = 'RECV' 
    ) 
    ) c 
group by country, no; 

我要指出,这将跳过国家,所有的值都是0。如果你真的需要这些,您可以在子查询额外行。然而,我不清楚发生了什么事,比如说“H”的行数为No,所以我不清楚你真正想要什么。

+0

我不想要对应于H的数据。H是属于印度的DstNo。我担心的是SrcNo和DstNo属于英国。 – davyjones

0

使用简单的热膨胀系数:

WITH config (c) AS (SELECT 'UK'::varchar), 
countries (country) AS (
    SELECT srccountry FROM t WHERE srccountry NOT IN (SELECT c FROM config) 
    UNION 
    SELECT dstcountry FROM t WHERE dstcountry NOT IN (SELECT c FROM config) 
), 
nos (no) AS (
    SELECT srcno FROM t WHERE srccountry IN (SELECT c FROM config) AND type = 'SEND' 
    UNION 
    SELECT dstno FROM t WHERE dstcountry IN (SELECT c FROM config) AND type = 'RECV' 
), 
send (no, country, send) AS (
    SELECT srcno, dstcountry, COUNT(*) 
    FROM config LEFT JOIN t ON srccountry = c 
    GROUP BY srcno, dstcountry 
), 
recv (no, country, recv) AS (
    SELECT dstno, srccountry, COUNT(*) 
    FROM config LEFT JOIN t ON dstcountry = c 
    GROUP BY dstno, srccountry 
) 
SELECT no, country, COALESCE(send, 0) AS send, COALESCE(recv, 0) AS recv 
FROM countries 
CROSS JOIN nos 
LEFT JOIN send USING (no, country) 
LEFT JOIN recv USING (no, country); 
  • 的配置“表”是只存在,这样你就不必改变英国在查询不同的地方;
  • 国家“表”检索所有与英国不同的国家(或您在配置中输入的国家/地区);
  • nos“table”检索英国发送或接收的所有nos;
  • 发送“表”计算英国(以及谁收到)发送的每件产品的数量;
  • recv“table”统计英国(以及谁发送的)每件产品的数量;
  • 最终查询加入所有这些结果。