Reuse the result of a select statement in a GROUP BY? Clause

In MySQL, I might have a query like this:

select  
    cast(from_unixtime(t.time, '%Y-%m-%d %H:00') as datetime) as timeHour
    , ... 
from
    some_table t 
group by
    timeHour, ...
order by
    timeHour, ...

where timeHourin GROUP BYis the result of a select statement.

But I just tried a query similar to query in Sqark SQL, and I got an error

Error: org.apache.spark.sql.AnalysisException: 
cannot resolve '`timeHour`' given input columns: ...

My request for Spark SQLwas as follows:

select  
      cast(t.unixTime as timestamp) as timeHour
    , ...
from
    another_table as t
group by
    timeHour, ...
order by
    timeHour, ...

Is this design possible in Spark SQL?

+4
source share
2 answers

Is this construct possible in Spark SQL?

Yes it is . You can get it working in Spark SQL in two ways of using a new column in partitions GROUP BYandORDER BY

Approach 1 using an auxiliary query:

SELECT timeHour, someThing FROM (SELECT  
      from_unixtime((starttime/1000)) AS timeHour
    , sum(...)                          AS someThing
    , starttime
FROM
    some_table) 
WHERE
    starttime >= 1000*unix_timestamp('2017-09-16 00:00:00')
      AND starttime <= 1000*unix_timestamp('2017-09-16 04:00:00')
GROUP BY
    timeHour
ORDER BY
    timeHour
LIMIT 10;

2, WITH// :

-- create alias 
WITH table_aliase AS(SELECT  
      from_unixtime((starttime/1000)) AS timeHour
    , sum(...)                          AS someThing
    , starttime
FROM
    some_table)

-- use the same alias as table
SELECT timeHour, someThing FROM table_aliase
WHERE
    starttime >= 1000*unix_timestamp('2017-09-16 00:00:00')
      AND starttime <= 1000*unix_timestamp('2017-09-16 04:00:00')
GROUP BY
    timeHour
ORDER BY
    timeHour
LIMIT 10;

, API- Spark DataFrame (wo SQL) Scala:

// This code may need additional import to work well

val df = .... //load the actual table as df

import org.apache.spark.sql.functions._

df.withColumn("timeHour", from_unixtime($"starttime"/1000))
  .groupBy($"timeHour")
  .agg(sum("...").as("someThing"))
  .orderBy($"timeHour")
  .show()

//another way - as per eliasah comment
df.groupBy(from_unixtime($"starttime"/1000).as("timeHour"))
  .agg(sum("...").as("someThing"))
  .orderBy($"timeHour")
  .show()
+4

...

, select GROUP BY. :

select  
      from_unixtime((t.starttime/1000)) as timeHour
    , sum(...)                          as someThing
from
    some_table as t
where
    t.starttime>=1000*unix_timestamp('2017-09-16 00:00:00')
      and t.starttime<=1000*unix_timestamp('2017-09-16 04:00:00')
group by
    from_unixtime((t.starttime/1000))
order by
    from_unixtime((t.starttime/1000))
limit 10;       
+1

Source: https://habr.com/ru/post/1686312/


All Articles