我通常不做数据库编程,所以我对如何做某些事情很生气。但是我有一个问题,我要采取一个项目,如果这个项目位于相同的位置,但在不同的位置,则将所述项目的值除以展示位置之间的总和数。
这是我的表结构:
LOCATION PLACEMENT VALUE COUNT ITEM
25 12345 100 10 55555 <----
25 67890 100 20 55555 <----
25 11111 50 5 00000
25 22222 75 5 11111
换句话说,Item (55555)
位于2个展示位置,此商品的价值为100
新值应为:PLACEMENT 12345
将是(10/30)* 100 = 33.3而PLACEMENT 67890
将是(20/30)* 100 = 66.7
知道如何在SQL或HQL中执行此操作吗?
答案 0 :(得分:3)
create table new as
select item,count(distinct placement) as dist_placement,count(count)as count,sum(count) as s_count
from mytable
group by item,location;
hive> select * from new;
OK
00000 1 1 5
11111 1 1 5
55555 2 2 30
Create table final as
select b.location as location,b.placement as placement, CASE
WHEN a.count=2 and a.dist_placement=2 then cast(((b.count/a.s_count)*b.value) as double)
ELSE cast(b.value as double)
END , b.count as count, b.item as item
from new a
join mytable b
on a.item=b.item;
select * from final;
输出
location placement value count item
25 12345 33.33333333333333 10 55555
25 67890 66.66666666666666 20 55555
25 11111 50.0 5 00000
25 22222 75.0 5 11111
如果您为输入提供相同的展示位置和不同的商品
LOCATION PLACEMENT VALUE COUNT ITEM
25 12345 100 10 55555 <----
25 12345 100 20 55555 <----
25 11111 50 5 00000
25 22222 75 5 11111
输出
LOCATION PLACEMENT VALUE COUNT ITEM
25 12345 100.0 10 55555
25 12345 100.0 20 55555
25 11111 50.0 5 00000
25 22222 75.0 5 11111
我可以,如果您有其他要求,请告诉我。
答案 1 :(得分:1)
可能有一种更有效的方法,但是通过两个步骤,您可以添加item_count,然后通过将其分开来创建新值。
create table new as select
item, sum(count) as item_count
from old
group by item, location, placement;
create table new2 as select
a.*,
b.item_count,
a.count/b.item_count as new_count
from old a
left join new b
on a.item=b.item;
答案 2 :(得分:1)
您的样本表
SELECT * INTO #TEMP FROM
(
SELECT 25 LOCATION,12345 PLACEMENT,100 VALUE ,10 [COUNT], 55555 ITEM
UNION ALL
SELECT 25 , 67890 , 100 , 20,55555
UNION ALL
SELECT 25 , 11111 , 50 , 5,00000
UNION ALL
SELECT 25 , 22222 , 75 , 5, 11111
)TAB
您的结果在
之下SELECT *,
CAST(([COUNT]/CAST(SUM([COUNT]) OVER(PARTITION BY ITEM)AS NUMERIC(20,2)))*VALUE AS NUMERIC(20,1)) Result
FROM #TEMP