我有一张桌子:
Sales ID
100 a
100 a
103.5 c
105 d
105 d
... 我只想获取值 308.5 (即100 + 103.5 + 105,唯一值)。
我已经尝试过了:
select sum(case when rownum=1 then sales end) from
(select sales,id, row_number() over (partition by id) as rownum from table) subquery
但是每次刷新时,我都会得到不同的值。
替代方法是什么?
答案 0 :(得分:0)
但是每次刷新时,我都会得到不同的值。
这表明基础数据正在更改-这在Vertica上不太可能。或更可能您对一个ID具有多个值。您可以测试后者:
select id, count(distinct sales)
from t
where min(sales) <> max(sales);
答案 1 :(得分:0)
您可以将子查询用于不同的销售
select sum(quantity), count(*), . . .
from orders o
where not exists (select 1 from orders o2 where o2.customercd = o.customercd and o2.type = 1);
答案 2 :(得分:0)
您必须先运行SELECT DISTINCT,然后再运行SUM()-ming来进行重复数据删除。像这样:
WITH
-- this is your input - don't use in real query
input(Sales,ID) AS (
SELECT 100,'a'
UNION ALL SELECT 100,'a'
UNION ALL SELECT 103.5,'c'
UNION ALL SELECT 105,'d'
UNION ALL SELECT 105,'d'
)
, -- < - replace this comma with "WITH", and start the real query here ...
uq (sales) AS (
SELECT DISTINCT
sales
FROM input
)
SELECT
SUM(sales)
FROM uq;
-- out SUM
-- out -------
-- out 308.5
-- out (1 row)
-- out
-- out Time: First fetch (1 row): 7.795 ms. All rows formatted: 7.826 ms
-- if ( 100 , 'a' ) is different from ( 100 , 'd' ), then it would be the below
WITH
-- this is your input - don't use in real query
input(Sales,ID) AS (
SELECT 100,'a'
UNION ALL SELECT 100,'a'
UNION ALL SELECT 103.5,'c'
UNION ALL SELECT 105,'d'
UNION ALL SELECT 105,'d'
)
, -- < - replace this comma with "WITH", and start the real query here ...
uq (sales,id) AS (
SELECT DISTINCT
sales
, id
FROM input
)
SELECT
SUM(sales)
FROM uq;
-- out SUM
-- out -------
-- out 308.5
-- out (1 row)
-- out
-- out Time: First fetch (1 row): 11.084 ms. All rows formatted: 11.117 ms
答案 3 :(得分:0)
您想要来自不同的销售对和ID的销售总和:
select sum(t.sales) from (
select distinct sales, id
from table
) t
或:
select sum(t.sales) from (
select sales from table
group by sales, id
) t