在Teradata SQL中按ID对列求和

时间:2018-08-17 15:13:53

标签: sql teradata

现在我从以下代码中得到以下输出...(一个ID只能有1个代码,但是一个代码可以有许多ID)

var tooltip = document.getElementById('tooltip');
document.addEventListener("selectionchange", function(event) {
    var text = window.getSelection().toString();
    tooltip.innerHTML = text;
});

document.addEventListener("mouseup", function(event){
    var x = -1000;
    var y = -1000;
    if(tooltip.innerHTML!=""){
        x =event.clientX;
        y = event.clientY;
    }
    tooltip.style.top = x + 'px';
    tooltip.style.left = y + 'px';
});

我想创建一个新列,以id显示count1的总和。谁能帮我修改我的代码以反映这一点?这是我想要的输出的示例...

SEL a.id, a.code,
CASE WHEN f.fac_id = 80007944 THEN 1
                WHEN f.fac_id = 80007838 THEN 1
                WHEN f.fac_id = 80007998 THEN 1 
                WHEN f.fac_id = 80007823 THEN 1
                END AS Count1
FROM db1.t1 a
INNER JOIN db2.t2 f ON f.fac_id = a.fac_id
AND a.code IN (060, 140)
ORDER BY a.code

id  code    Count1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
CFC 060     1
FAD 140     1
FAD 140     1
FAD 140     1
FAD 140     1
FAD 140     1
FAD 140     1
E5C 140     1
E5C 140     1
E5C 140     1
915 140     1
915 140     1
915 140     1
6AD 140     1
6AD 140     1
6AD 140     1
6AD 140     1
6AD 140     1
6AD 140     1

3 个答案:

答案 0 :(得分:0)

我认为您想要一个窗口函数:

SELECT a.id, a.code,
       (CASE WHEN f.fac_id IN (80007944, 80007838, 80007998, 80007823 THEN 1
        END) AS Count1,
       SUM(CASE WHEN f.fac_id IN (80007944, 80007838, 80007998, 80007823 THEN 1
           END) OVER (PARTITION BY id)
FROM db1.t1 a INNER JOIN
     db2.t2 f ON f.fac_id = a.fac_id AND a.code IN (060, 140)
ORDER BY a.code

答案 1 :(得分:0)

SELECT inner.id , inner.code , inner.Count1 , sum(Count1) Over (partition by inner.id)
FROM ( 
SEL a.id as id, a.code as code
CASE WHEN f.fac_id = 80007944 THEN 1
                WHEN f.fac_id = 80007838 THEN 1
                WHEN f.fac_id = 80007998 THEN 1 
                WHEN f.fac_id = 80007823 THEN 1
                END AS Count1
FROM db1.t1 a
INNER JOIN db2.t2 f ON f.fac_id = a.fac_id
AND a.code IN (060, 140)
) AS inner 
ORDER BY inner.code 

答案 2 :(得分:0)

您可以尝试对子查询使用内部联接,并按ID和代码对总和分组

select  a.id, a.code, t count1 
FROM db1.t1 a
INNER JOIN db2.t2 f ON f.fac_id = a.fac_id AND a.code IN (060, 140)
INNER JOIN (
SELECT  a.id, a.code,
sum(CASE WHEN f.fac_id = 80007944 THEN 1
                WHEN f.fac_id = 80007838 THEN 1
                WHEN f.fac_id = 80007998 THEN 1 
                WHEN f.fac_id = 80007823 THEN 1
                ELSE 0
                END) AS Count1
FROM db1.t1 a
INNER JOIN db2.t2 f ON f.fac_id = a.fac_id
AND a.code IN (060, 140)
GROUP BY a.id, a.code
) t on t.id = a.id and t.code = a.code 
ORDER BY a.code