hive 中每个计数组的匹配行数和 select 30

count of matching rows and select 30 from each count group in hive

如何计算以下示例数据的匹配行数

ID    Attribute 1  Attribute 2 
        1   A   AA 
        2   B   CC 
        3   C   BB 
        4   A   AA 
        5   C   BB 
        6   D   AA 
        7   B   AA 
        8   C   DD 
        9   A   AB 
        10  A   AA 

输出应该是这样的

 ID    Attribute 1  Attribute 2     count(Attribute1+Attribute2)
        1   A   AA  3
        2   B   CC  1
        3   C   BB  2
        4   A   AA  3
        5   C   BB  2
        6   D   AA  1
        7   B   AA  1
        8   C   DD  1
        9   A   AB  1
        10  A   AA  3

然后 select 来自每个计数组的 50% 的行。例如:对于 mtaching 行 (A,AA),我只需要 select 2 次。这会给我 ID(1 和 4)

您可以像这样使用 SQL 查询。

SELECT *, 
       (SELECT COUNT(*)
        FROM table AS t2
        WHERE t1.[Attribute1] = t2.[Attibute1] 
          AND t1.[Attribute2] = t2.[Attibute2]) AS 'count(Attribute1+Attribute2)' 
FROM table AS t1

这里是查询:

select * from (select product_category_id,
count(1) over (partition by product_category_id) cnt,
row_number() over (partition by product_category_id) rn
from products) p where rn <= 0.5 * cnt;

这是示例结果,product_category_id,cnt,然后是行号。在你的情况下,你需要在分区中有你的两个属性。

59  24  1
59  24  2
59  24  3
59  24  4
59  24  5
59  24  6
59  24  7
59  24  8
59  24  9
59  24  10
59  24  11
59  24  12