Netezza有条件地计算每个ID

时间:2017-04-07 10:00:43

标签: sql netezza

我是Netezza的新手,需要计算拥有非零密钥的ID数量。我的KEY是一种交易类型,我想返回有任何交易的ID的计数。基本上我想要计算所有具有非零键的UID。

我的数据:

SRC UID KEY ...
A   118 3   ...
A   517 0   ...
A   517 1   ...
A   517 4   ...
B   623 4   ...
C   972 0   ...
C   972 0   ...

我想要回归:

SOURCE  UIDs    UIDs_W_TRANS
A       2       2
B       1       1
C       1       0

这是我的代码:

SELECT
    SRC AS SOURCE,
    COUNT(DISTINCT(UID)) AS UIDs,
    SUM(CASE WHEN KEY = 0 THEN 0 ELSE 1) AS UIDs_W_TRANS

FROM
    DATABASE

GROUP BY
    UID,
    SOURCE

我回来的是

SOURCE  UIDs    UIDs_W_TRANS
A       2       3
B       1       1
C       1       0

您可以看到我的查询正在计算每个非零KEY。我已经尝试了上述查询的一些变体,但没有什么让我更接近。如何才能为每个UID计算1个非零KEY?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找条件count(distinct)

SELECT SRC AS SOURCE,
       COUNT(DISTINCT(UID)) AS UIDs,
       COUNT(DISTINCT CASE WHEN KEY <> 0 THEN UID END) AS UIDs_W_TRANS
FROM DATABASE
GROUP BY SOURCE