SQL/Hive 计算不同列

问题描述 投票:0回答:3

如何在 SQL/Hive 中执行此操作?

    columnA       columnB    columnC
     100.10      50.60       30
     100.10      50.60       30
     100.10      50.60       20
     100.10      70.80       40
 

输出应该是:

  columnA   columnB    No_of_distinct_colC
  100.10    50.60       2
  100.10    70.80       1

我认为正确的查询:

SELECT columnA,columnB,COUNT(distinct column C)
from table_name
group by columnA,columnB
sql hive
3个回答
37
投票

是的,这几乎是正确的。但你有一个简单的错误。您的列名在 COUNT 内是错误的。

SELECT columnA,columnB,COUNT(DISTINCT columnC) No_of_distinct_colC
from table_name
group by columnA,columnB

0
投票

如果您使用 PySpark,以下代码应该可以工作:

import pyspark.sql.functions as F
spark.sql('select * from table_name')\
         .groupby(columnA, columnB)\
         .agg(F.countDistinct('columnC') ).show()

-3
投票
SELECT * 
FROM
(
    SELECT columnA, columnB, COUNT(DISTINCT column C) AS dis_col
    FROM table_name
    GROUP BY columnA, columnB
) A;
© www.soinside.com 2019 - 2024. All rights reserved.