UNION ALL / UNION on Presto - sql

I am using treasure data for data analytics and having trouble with union statement in presto db.
How do i do a Union All on presto. I dont understand the documentation. everytime I try to do UNION like so:
SELECT
COUNT(*) AS ReservationsCreated,
resource
FROM
reservation
WHERE
type = 'create'
UNION
SELECT
COUNT(*) AS ReservationsDeleted,
resource
FROM
reservation
WHERE
type = 'delete'
GROUP BY
resource
;
I get output reformatted like:
SELECT
COUNT(*) AS ReservationsCreated,
resource
FROM
reservation
WHERE
type = 'create'
UNION
SELECT
COUNT(*) AS ReservationsDeleted,
resource
FROM
reservation
WHERE
type = 'delete'
GROUP BY
resource
;
and error that says:
'"resource"' must be an aggregate expression or appear in GROUP BY clause
I think I am not understanding the syntax for Presto. The docs are very confusing on Union. Any help appreciated.

The first part of the query is missing a group by as the error says.
SELECT COUNT(*) AS ReservationsCreated, resource
FROM reservation
WHERE type = 'create'
group by resource
UNION ALL
SELECT COUNT(*) AS ReservationsDeleted, resource
FROM reservation
WHERE type = 'delete'
GROUP BY resource
In fact, the query could be simplified to use conditional aggregation.
select
resource
,sum(case when type = 'create' then 1 else 0 end) as reservationscreated
,sum(case when type = 'delete' then 1 else 0 end) as reservationsdeleted
from reservation
group by resource

Related

Can I rewrite this SQL code to the querydsl one?

I have sql code that's counting number of the records in db for different predicates
SELECT
count(*) as total_count,
count(notAided) as not_aided_count,
count(chatAided) as chat_aided_count
FROM (
SELECT
CASE WHEN aided_with IS NULL THEN 1 END notAided,
CASE WHEN aided_with = 'CHAT' THEN 1 END chatAided
FROM sessions
) sessions
Can I rewrite it with querydsl? I take a look to the CaseBuilder, but founded no idea how to use it in the select query
One can write:
query.select(
QSession.session.id.count().as("total_count"),
new CaseBuilder().when(QSession.session.aidedWith.isNotNull()).then(1).otherwise(Expressions.<Integer> nullExpression()).count().as("not_aided_count"),
new CaseBuilder().when(QSession.session.aidedWith.eq("CHAT")).then(1).otherwise(Expressions.<Integer> nullExpression()).count().as("chat_aided_count")
)
Which would be equivalent to the SQL:
SELECT
count(*) as total_count,
count(CASE WHEN aided_with IS NULL THEN 1 END) as not_aided_count,
count(CASE WHEN aided_with = 'CHAT' THEN 1 END) as chat_aided_count
FROM sessions

Hive SQL - select all rows containing a value; where one of the rows matches a specific value

I have a Hive table like this -
Name ..... Page
Sid ...........Login
Sid ...........Buy
Nancy ......Home
Nancy ......Register
Nancy ......Buy
I'd like to extract all the rows for Name where one of the Names has a Page=login. So, it would extract two rows for for name=Sid but no rows for name=Nancy.
I tried -
select * from table where name in (select name from table where page='login');
However, I get the error -
Error while compiling statement: FAILED: SemanticException [Error 10249]: Line 1:142 Unsupported SubQuery Expression ''login'': SubQuery expression refers to Outer query expressions only.
Can anyone help? This query seems simple enough. Thanks
The following query would work anywhere ANSI SQL is supported:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT Name
FROM yourTable
GROUP BY Name
HAVING SUM(CASE WHEN Page = 'login' THEN 1 ELSE 0 END) > 0
) t2
ON t1.Name = t2.Name
The basic strategy is to do aggregation for each name, count the number of times where login appears as a page, and then retain only those names which meet your criteria.
You can do this using window functions:
select t.*
from (select t.*,
count(case when page = 'login' then 1 else 0 end) over (partition by name) as numlogins
from t
) t
where numlogins > 0;
Look at this : https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries#LanguageManualSubQueries-SubqueriesintheWHEREClause
This is a tutorial for Hive SQL SubQueries

PostgreSQL: How to select 2 different counts from table when x=a and x=b

Dear fellow Stackoverflowers,
How may one select 2 different counts from the same table for scenarios:
x=a and x=b
specifically, (WHEN type = subdomain) AND (WHEN subtype = subdomain)?
to add them together to create a 'totalcount'?
My attempt (for your reference):
SELECT description, type, count(1), subtype, count(2)
FROM mapping, (dotcom WHERE type = subdomain) AS typecount,
(dotcom WHERE subtype = subdomain) AS subtypecount
GROUP BY description, type, subtype
HAVING count(1)>1
AND count(2)>1
ORDER BY count(*)
DESC LIMIT 10
Second attempt:
SELECT description
FROM mapping, SUM(WHEN subdomain = type OR subdomain = subtype) AS count(1)
GROUP BY description, type, subtype
HAVING count(1)>1
ORDER BY count(*)
DESC LIMIT 10
If you have Postgres 9.4 or newer, you can use FILTER, which is much easier to read than the CASE WHEN ... END syntax.
SELECT
description,
type,
COUNT(*) FILTER (WHERE subdomain = type) AS typecount,
subtype,
COUNT(*) FILTER (WHERE subtype = subdomain) AS subtypecount
FROM mapping
GROUP BY description, type, subtype;
It should be noted that count(1) and count(2) doesn't do what you probably think it does; count is an aggregate function that counts if the given value is not null in each row, and seeing as you're giving it an integer literal, it will effectively only count the number of rows returned.
If I have understood your requirement correctly, You can do like below
SELECT description, SUM(CASE WHEN subdomain = type OR subdomain = subtype THEN 1 ELSE 0 END)
FROM mapping
GROUP BY description
Use
SELECT
SUM(
CASE WHEN type = 'whatever'
THEN column_name_1
ELSE coumn_name_2
END AS column1,
CASE WHEN subtype = 'whatever2'
THEN column_name_3
ELSE coumn_name_4
END AS column2
)

nhibernate complex query of sql with a group by ROLLUP() of permenant table union all derived query

How would you convert the following sql that contains a case count, group by, union all to nhibernate?
This complex sqql with a group by ROLLUP() of permanent table union all derived query columns
select
CASE
WHEN GROUPING([BUSINESS_UNIT]) = 1 THEN 'Total'
ELSE [BUSINESS_UNIT]
END [BUSINESS_UNIT]
, SUM(InjuryIllnessTtlCount) InjuryIllnessTtlCount
from (
select i.INCIDENT_ID
,b.BUSINESS_UNIT
,case
when (i.INJURY_ILLNESS_TYPE_ID=4 ) then 1 --'Injury/Illness (Near Miss with High Severity Potential)'
else 0
end as InjuryIllnessTtlCount
from tblIncident i
join tblBUSINESS_UNIT b on i.BUS_UNIT_ID = b.BUS_UNIT_ID
--where (CONVERT(varchar(10),i.create_dt, 111) between '2015/01/12' and '2015/05/12')
union all
select 0 incident_id
,b.BUSINESS_UNIT
,0 InjuryIllnessTtlCount
from
tblBUSINESS_UNIT b
) abc
group by ROLLUP(abc.BUSINESS_UNIT)
When it comes to this complicated queries, the conversion to NHibernate either not possible or does not worth it. So my two cents is to go with,
var query = <your query>;
var session = sessionFactory.OpenSession();
var result =session.CreateSQLQuery(query)
.List();
Where the Query is directly executed.

CASE SQL Oracle Query - What is wrong?

I have following query to select the view to be used in the query, however I get the error:
FROM keyword not found where expected
select *, (CASE WHEN 'employee' = 'employee' THEN employee ELSE vw END) FROM type1
select type1.*,
(CASE WHEN 'employee' = 'employee'
THEN employee
ELSE vw
END)
FROM type1
I always prefix with the tablename/table alias to the * and it works!!
We just need to specify, fetch all the column from this table, when we specify combination of wildcard and other select expressions!
You cannot use * and individual columns together in select statement.
SELECT (CASE WHEN 'employee' = 'employee' THEN 'employee' ELSE 'vw' END)
FROM dual
You cant do a *, in Oracle without an alias/TableName(.) in front of it. List out the columns you want to see in the result set or add a table alias/tablename.
You cannot set the name of the view the select statement shall retrieve data from in the column list part of the statement.