IN clause with CASE WHEN in SQL - sql

I try to count the number of times a product is ordered two days in a row, over the last seven days.
I tried to implement an IN condition in a CASE WHEN, but I get the following error:
Comparison operator IN not valid
I'm using DB2
Here is what I've tried :
WITH CTE AS (
SELECT ALLPIC, COUNT(DISTINCT(PAL.CODPRO)) AS NBREFSSTOCKS
FROM FGE50NEUV1.GEPAL AS PAL INNER JOIN FGE50NEUV1.GEPIC AS PIC ON PAL.CODPRO = PIC.CODPRO
GROUP BY ALLPIC
),
CTE2 AS (
SELECT ALLSTS AS ALLPIC, COUNT(DISTINCT CASE WHEN DATPRB1 = ` + dateWMS() + ` THEN CODPRO END) AS NBREFSCDE,
COUNT(
DISTINCT CASE WHEN (
CODPRO IN (SELECT DISTINCT(CODPRO) FROM FGE50NEUV1.GESUPD WHERE DATPRB1 = 20221027)
AND CODPRO IN (SELECT DISTINCT(CODPRO) FROM FGE50NEUV1.GESUPD WHERE DATPRB1 = 20221028)
THEN CODPRO END
)
) AS NBCOMMUNVEILLE,
COUNT(
DISTINCT CASE WHEN (
CODPRO IN (SELECT DISTINCT(CODPRO) FROM FGE50NEUV1.GESUPD WHERE DATPRB1 = 20221026)
AND CODPRO IN (SELECT DISTINCT(CODPRO) FROM FGE50NEUV1.GESUPD WHERE DATPRB1 = 20221027)
THEN CODPRO END
)
) AS NBCOMMUNJM2
FROM FGE50NEUV1.GESUPD AS SUP
GROUP BY ALLSTS
)
SELECT * FROM CTE INNER JOIN CTE2 ON CTE.ALLPIC = CTE2.ALLPIC ORDER BY CTE.ALLPIC

Listing of SQL messages:
SQL0115
Message Text:
Comparison operator &1 not valid.
Cause Text:
Simple comparison operators other than equal and not equal cannot be
used with a list of items. ANY, ALL, and SOME comparison operators
must be followed by a fullselect, rather than an expression or a list
of items. Subqueries cannot be specified in a JOIN condition or in a
CASE expression.
Recovery Text:
Change either the comparison or the
operand. Try the request again.

Related

SQL CASE WHEN ELSE not working in AWS Athena

I have the script below setup in AWS Athena, the goal is to replace some budget numbers (total) with 0 if they are within a certain category (costitemid). I'm getting the following error in AWS Athena and could use some advice as to why it isn't working. Is the problem that I need to repeat everything in the FROM and GROUP BY in the WHEN and ELSE? Code below the error. Thank you!
SYNTAX_ERROR: line 6:9: 'projectbudgets.projectid' must be an aggregate expression or appear in GROUP BY clause
This query ran against the "acorn-prod-reports" database, unless qualified by the query. Please post the error message on our forum or contact customer support with Query Id: 077f007b-61a0-4f6b-aa1f-dd38bb401218
SELECT
CASE
WHEN projectbudgetlineitems.costitemid IN (462561,462562,462563,462564,462565,462566,478030) THEN (
SELECT
projectbudgets.projectid
, projectbudgetyears.year fiscalYear
, projectbudgetyears.status
, "sum"(((0 * projectbudgetlineitems.unitcost) * (projectbudgetlineitems.costshare * 1E-2))) total
)
ELSE (
SELECT
projectbudgets.projectid
, projectbudgetyears.year fiscalYear
, projectbudgetyears.status
, "sum"(((projectbudgetlineitems.quantity * projectbudgetlineitems.unitcost) * (projectbudgetlineitems.costshare * 1E-2))) total
)
END
FROM
(("acorn-prod-etl".target_acorn_prod_acorn_projectbudgets projectbudgets
INNER JOIN "acorn-prod-etl".target_acorn_prod_acorn_projectbudgetyears projectbudgetyears ON (projectbudgets.id = projectbudgetyears.projectbudgetid))
INNER JOIN "acorn-prod-etl".target_acorn_prod_acorn_projectbudgetlineitems projectbudgetlineitems ON (projectbudgetyears.id = projectbudgetlineitems.projectbudgetyearid))
--WHERE (((projectbudgetlineitems.costitemid <> 478030) AND (projectbudgetlineitems.costitemid < 462561)) OR (projectbudgetlineitems.costitemid > 462566))
GROUP BY projectbudgets.projectid, projectbudgetyears.year, projectbudgetyears.status
Your syntax is wrong (at least according to most SQL dialects.) You can't generally say "SELECT CASE WHEN (condition) THEN (this select clause) ELSE (that select clause) END FROM (tables)"
You can only use CASE to calculate a single value.
But it looks as if the only change between your two inner SELECT clauses is whether you use 0 or the quantity in the final multiplication. And that is perfect for a CASE!
I do not guarantee this will work right off the bat, because I don't have your setup or an idea of your table layout. However, it's a step in the right direction:
SELECT
projectbudgets.projectid
, projectbudgetyears.year fiscalYear
, projectbudgetyears.status
, "sum"(
((
CASE
WHEN projectbudgetlineitems.costitemid IN (462561,462562,462563,462564,462565,462566,478030)
THEN 0
ELSE projectbudgetlineitems.quantity
END * projectbudgetlineitems.unitcost
) * (
projectbudgetlineitems.costshare * 1E-2
))) total
FROM
(("acorn-prod-etl".target_acorn_prod_acorn_projectbudgets projectbudgets
INNER JOIN
"acorn-prod-etl".target_acorn_prod_acorn_projectbudgetyears projectbudgetyears
ON (projectbudgets.id = projectbudgetyears.projectbudgetid))
INNER JOIN "acorn-prod-etl".target_acorn_prod_acorn_projectbudgetlineitems projectbudgetlineitems
ON (projectbudgetyears.id = projectbudgetlineitems.projectbudgetyearid))
GROUP BY
projectbudgets.projectid, projectbudgetyears.year, projectbudgetyears.status
This could solve your problem if you want to sum the items for each project and year and status except for certain line items. Here, it is correct to use a "where" condition and not "case when" :
SELECT
projectbudgets.projectid,
projectbudgetyears.year,
projectbudgetyears.status,
"sum"(((projectbudgetlineitems.quantity * projectbudgetlineitems.unitcost) *
(projectbudgetlineitems.costshare * 1E-2))) total
FROM
(("acorn-prod-etl".target_acorn_prod_acorn_projectbudgets projectbudgets
INNER JOIN "acorn-prod-etl".target_acorn_prod_acorn_projectbudgetyears
projectbudgetyears ON (projectbudgets.id = projectbudgetyears.projectbudgetid))
INNER JOIN "acorn-prod-etl".target_acorn_prod_acorn_projectbudgetlineitems
projectbudgetlineitems ON (projectbudgetyears.id =
projectbudgetlineitems.projectbudgetyearid))
WHERE projectbudgetlineitems.costitemid NOT IN
(462561,462562,462563,462564,462565,462566,478030)
GROUP BY projectbudgets.projectid, projectbudgetyears.year,
projectbudgetyears.status
;

error incorporating a select within a IFNULL in MariaDB

I'm creating a view in MariaDB and i'm having trouble making it work for a couple of fields. Currently this is working:
( SELECT DISTINCT IFNULL(grades.`grade`,'No Grade')
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
But i need to add a select where the 'No grade' is, in the following form
( SELECT DISTINCT IFNULL( grades.`grade`,
SELECT IF( EXISTS
( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
i know that
SELECT IF( EXISTS( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
),
'Enrolled', 'Not enrolled'
)
is working too, but now the whole thing it's giving me an error, so any suggestions would be greatly appreciated
Thanks
This looks like a subquery:
(SELECT DISTINCT IFNULL(grades.`grade`,
SELECT IF( EXISTS (SELECT *
FROM `another_table`
WHERE userid = 365 AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id` AND
grades.`Item Name` = 'SOMEINFO'
) as SOMENAME,
You are using a subquery that returns two columns in a position where a scalar subquery is expected. A scalar subquery returns one column in at most one row.
Unfortunately, there is no easy way to do what you want in MySQL, because of the restrictions on views. I would advise you to rewrite the logic so the exists is handled using a left join in the from clause.

unexpected token : ( subquery hql

Here's my HQL query
FROM com.mysite.ActeurInterne act WHERE act.acteurId IN
(SELECT DISTINCT COALESCE(acteurInterne.acteurInternePrincipalId, acteurInterne.acteurId)
FROM
(SELECT DISTINCT acteurInterne
FROM com.mysite.ActeurInterne AS acteurInterne
JOIN acteurInterne.roleSet.roles AS role
WHERE acteurInterne.acteurId = acteurInterne.acteurId
AND acteurInterne.nom LIKE :likenom
AND (role.dateFermeture IS NULL
OR role.dateFermeture >= TRUNC(SYSDATE))
AND (role.dateOuverture IS NULL
OR role.dateOuverture <= TRUNC(SYSDATE))
AND (role.type = :type
OR role.type = :typeC)
)
)
I get
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 190
which is the "(" at the begining of the fourth line above.
( SELECT DISTINCT acteurInterne
Hibernate documentation states that sub-queries are allowed only in the SELECT or WHERE clause.
Note that HQL subqueries can occur only in the select or where
clauses.
But in the example above you have a subquery in the FROM clause of the first subquery.
Have you tried consolidating the 2 sub-queries into one?
FROM com.mysite.ActeurInterne act WHERE act.acteurId IN
(SELECT DISTINCT COALESCE(acteurInterne.acteurInternePrincipalId, acteurInterne.acteurId)
FROM com.mysite.ActeurInterne AS acteurInterne
JOIN acteurInterne.roleSet.roles AS role
WHERE acteurInterne.acteurId = acteurInterne.acteurId
AND acteurInterne.nom LIKE :likenom
AND (role.dateFermeture IS NULL
OR role.dateFermeture >= TRUNC(SYSDATE))
AND (role.dateOuverture IS NULL
OR role.dateOuverture <= TRUNC(SYSDATE))
AND (role.type = :type
OR role.type = :typeC)
)

PostgreSQL use case when result in where clause

I use complex CASE WHEN for selecting values. I would like to use this result in WHERE clause, but Postgres says column 'd' does not exists.
SELECT id, name, case when complex_with_subqueries_and_multiple_when END AS d
FROM table t WHERE d IS NOT NULL
LIMIT 100, OFFSET 100;
Then I thought I can use it like this:
select * from (
SELECT id, name, case when complex_with_subqueries_and_multiple_when END AS d
FROM table t
LIMIT 100, OFFSET 100) t
WHERE d IS NOT NULL;
But now I am not getting a 100 rows as result. Probably (I am not sure) I could use LIMIT and OFFSET outside select case statement (where WHERE statement is), but I think (I am not sure why) this would be a performance hit.
Case returns array or null. What is the best/fastest way to exclude some rows if result of case statement is null? I need 100 rows (or less if not exists - of course). I am using Postgres 9.4.
Edited:
SELECT count(*) OVER() AS count, t.id, t.size, t.price, t.location, t.user_id, p.city, t.price_type, ht.value as houses_type_value, ST_X(t.coordinates) as x, ST_Y(t.coordinates) AS y,
CASE WHEN t.classification='public' THEN
ARRAY[(SELECT i.filename FROM table_images i WHERE i.table_id=t.id ORDER BY i.weight ASC LIMIT 1), t.description]
WHEN t.classification='protected' THEN
ARRAY[(SELECT i.filename FROM table_images i WHERE i.table_id=t.id ORDER BY i.weight ASC LIMIT 1), t.description]
WHEN t.id IN (SELECT rl.table_id FROM table_private_list rl WHERE rl.owner_id=t.user_id AND rl.user_id=41026) THEN
ARRAY[(SELECT i.filename FROM table_images i WHERE i.table_id=t.id ORDER BY i.weight ASC LIMIT 1), t.description]
ELSE null
END AS main_image_description
FROM table t LEFT JOIN table_modes m ON m.id = t.mode_id
LEFT JOIN table_types y ON y.id = t.type_id
LEFT JOIN post_codes p ON p.id = t.post_code_id
LEFT JOIN table_houses_types ht on ht.id = t.houses_type_id
WHERE datetime_sold IS NULL AND datetime_deleted IS NULL AND t.published=true AND coordinates IS NOT NULL AND coordinates && ST_MakeEnvelope(17.831490030182, 44.404640972306, 12.151558389557, 47.837396630872) AND main_image_description IS NOT NULL
GROUP BY t.id, m.value, y.value, p.city, ht.value ORDER BY t.id LIMIT 100 OFFSET 0
To use the CASE WHEN result in the WHERE clause you need to wrap it up in a subquery like you did, or in a view.
SELECT * FROM (
SELECT id, name, CASE
WHEN name = 'foo' THEN true
WHEN name = 'bar' THEN false
ELSE NULL
END AS c
FROM case_in_where
) t WHERE c IS NOT NULL
With a table containing 1, 'foo', 2, 'bar', 3, 'baz' this will return records 1 & 2. I don't know how long this SQL Fiddle will persist, but here is an example: http://sqlfiddle.com/#!15/1d3b4/3 . Also see https://stackoverflow.com/a/7950920/101151
Your limit is returning less than 100 rows if those 100 rows starting at offset 100 contain records for which d evaluates to NULL. I don't know how to limit the subselect without including your limiting logic (your case statements) re-written to work inside the where clause.
WHERE ... AND (
t.classification='public' OR t.classification='protected'
OR t.id IN (SELECT rl.table_id ... rl.user_id=41026))
The way you write it will be different and it may be annoying to keep the CASE logic in sync with the WHERE limiting statements, but it would allow your limits to work only on matching data.

SQL Query takes to long to return data

Looking for a better way to write this query and my SQL skills aren't great, basic really so looking for any pointers to make this better. This is only the first two columns and the full report will have a further 10.
I'm taking a specific set of repair types and doing analysis on them with counts and calculations. The 1st is jobs brought forward to the current financial year and the second is total amount of jobs currently received.
SELECT
"Type",
(
SELECT
NVL (COUNT(jjo.jjobno), 0)
FROM
jjobh jjo
WHERE
jjo.jclcode = 'L'
AND jjo.jstatus <> '6'
AND jjo.year_rec <> (
SELECT
sub_code
FROM
code_table
WHERE
main_code = 'YEAR'
)
AND (
week_comp IS NULL
OR year_comp = (
SELECT
sub_code
FROM
code_table
WHERE
main_code = 'YEAR'
)
)
AND jjo.jrepair_type = "Type"
) AS "B/F",
(
SELECT
NVL (COUNT(jjo.jjobno), 0)
FROM
jjobh jjo
WHERE
jjo.jclcode = 'L'
AND jjo.jstatus <> '6'
AND jjo.year_rec = (
SELECT
sub_code
FROM
code_table
WHERE
main_code = 'YEAR'
)
AND jjo.jrepair_type = "Type"
) AS "Recvd"
FROM
(
SELECT
rep.repair_type_code AS "Type"
FROM
repair_type rep
WHERE
rep.client = 'L'
AND rep.work_centre = '004682'
ORDER BY
rep.repair_type_code
)
ORDER BY
"Type";
Your code is a mess. I suspect you want something like:
SELECT jjo.jrepair_type, count(*) as valbf
FROM (SELECT coalesce(COUNT(jjo.jjobno), 0)
FROM jjobh jjo cross join
(SELECT sub_code
FROM code_table
WHERE main_code = 'YEAR'
) sc
WHERE jjo.jclcode = 'L' AND
jjo.jstatus <> '6' AND
jjo.year_rec <> sc.sub_code AND
(week_comp IS NULL OR
year_comp = sc.sub_code
)
) jjo join
(SELECT rep.repair_type_code AS "Type"
FROM repair_type rep
WHERE rep.client = 'L' AND
rep.work_centre = '004682'
) rtc
on jjo.jrepair_type = rtc.repair_type_code
group by jjo.jrepair_type;
It looks like you want to join the "jjo" table to the "repair type code" table, producing information about each repair type. The order by in the subquery is useless.
My suggestion is to move the "jjo" table to the outer "from". You should also move the WHERE clauses to the outermost WHERE clause (which I didn't do). I haven't quite figured out the date logic, but this might get you on the right track.