从单个SQL查询中的多个表中获取结果

时间:2015-07-31 07:06:11

标签: sql join

我有两张桌子

  1. REPORT_API_USAGE enter image description here
  2. 2.REPORT_API_PAGES enter image description here

    我需要从TERMNAMECOUNT(TERMNAME)从REPORT_API_PAGES中提取REPORT_API_USAGECOUNT(CTYPE) WHERE CTYPE = 'download'。两个表都有TERMID列。

    这是我的SQL查询。但它没有给出任何结果。任何人都可以帮助我。

    SELECT AP.TERMNAME
        ,AP.COUNT(TERMNAME) AS tot
        ,AI.COUNT(CTYPE) AS event
    FROM REPORT_API_USAGE AP
    INNER JOIN REPORT_API_PAGES AI ON AP.TERMID = AI.TERMID
    WHERE AI.CTYPE = 'download'
        AND AP.VOCID = '21'
    

    结果图片

    enter image description here

    模拟了 ------------ enter image description here

2 个答案:

答案 0 :(得分:1)

您的查询的正确语法是:

SELECT AP.TERMNAME
    ,COUNT(DISTINCT AP.TERMID) AS tot
    ,COUNT(DISTINCT AI.CTYPE) AS event
    ,COUNT(DISTINCT CASE WHEN AI.CTYPE = 'event' THEN AI.CTYPE ELSE NULL END) AS page
FROM REPORT_API_USAGE AP
INNER JOIN REPORT_API_PAGES AI ON AP.TERMID = AI.TERMID
WHERE AI.CTYPE IN ( 'download', 'event' )
    AND AP.VOCID = '21'
GROUP BY AP.TERMNAME

现在,我不确定这是您想要的确切数据,您需要向我们展示您的样本数据的预期输出。

答案 1 :(得分:0)

试试这个

SELECT AP.TERMNAME, COUNT(1) AS tot, COUNT(1) AS event  
FROM REPORT_API_USAGE AP 
INNER JOIN REPORT_API_PAGES AI ON AP.TERMID = AI.TERMID 
WHERE AI.CTYPE = 'download' AND AP.VOCID = '21'
GROUP BY AP.TERMNAME

这将有效,

您添加了AP.COUNT和AI.COUNT但它应该只有COUNT