分组和划分Netezza

时间:2012-10-26 11:36:46

标签: sql sql-server netezza

我有以下查询将sum(rev)列中的每一行除以列的总和。

对于以下示例,sum(rev)列的总和为23193.Divide列派生自:sum in sum(rev)/ sum(rev)

select date,id,sum(rev), 
NULLIF(rev,0) / sum(rev) over() as Divide
from test 
where month(date) = 11
and year(date) = 2012
and day(date) = 02
and id = 'Client1'
group by date,id,rev
having sum(rev) <> 0
order by date


date                  id      sum(rev)      Divide

2012-11-02 00:00:00 Client1     1562.00     0.067348
2012-11-02 00:00:00 Client1     1.00        0.000043
2012-11-02 00:00:00 Client1     4689.00     0.202173
2012-11-02 00:00:00 Client1     267.00      0.011512
2012-11-02 00:00:00 Client1     16674.00    0.718924

有2个问题

1。)当评论日期(日期)条件时,检索到的值是错误的。它在分割计算中没有给出正确的值

    date               sum(rev)         Divide
    2012-11-02 00:00:00 1.00            0.000002
    2012-11-02 00:00:00 267.00          0.000412
    2012-11-02 00:00:00 1562.00         0.002412
    2012-11-02 00:00:00 4689.00         0.007241
    2012-11-02 00:00:00 16674.00        0.025749

2。)我想按日期分组。因为我们只有2-11-2012的记录,所以每天必须只有一行记录

请帮助解决这两个错误

参考:Find column Value by dividing with sum of a column

1 个答案:

答案 0 :(得分:2)

如果您想按date进行分组并将每日总数除以总计,则可以这样做:

SELECT
  date,
  SUM(rev) AS total,
  SUM(rev) / SUM(SUM(rev)) OVER () AS portion
FROM test
GROUP BY
  date
;

也就是说,SUM() OVER ()的参数应该是一个有效的表达式,rev不是此GROUP BY查询中的有效表达式,因为GROUP中不包含rev通过。但是你可以(并且应该)使用SUM(rev)作为参数,它将按预期工作。

如果要为单独的客户端分别生成结果,请将id添加到GROUP BY子句,并将PARTITION BY id添加到窗口SUM()的OVER子句中,如下所示:

SELECT
  date,
  id,
  SUM(rev) AS total,
  SUM(rev) / SUM(SUM(rev)) OVER (PARTITION BY id) AS portion
FROM test
GROUP BY
  date,
  id
;

详细了解OVER条款in the manual