I am joining two tables: breeds + breed_characteristics (bc)
But I'm getting the following error:
PG::UndefinedColumn: ERROR: column "val" does not exist LINE 11
I'm not sure what's wrong, here is my SQL:
SELECT
breeds.*,
CASE bc.user_val
WHEN NULL THEN bc.value
ELSE (bc.value + (bc.user_val/2))/2
END AS val
FROM
breed_characteristics bc
INNER JOIN breeds ON breeds.id = bc.breed_id
WHERE bc.characteristic_id = 45
AND val BETWEEN 4 AND 5
ORDER BY val DESC
(Executing this query on Postgres through Active Record)
You can't use expression alias val in where clause like that.
It's because there is an order in which SQL is executed specified in the SQL standard. Here, the WHERE clause is evaluated before SELECT and hence, the WHERE clause is not aware of the alias you created in the SELECT. The ORDER BY comes after the SELECT and hence can utilize aliases.
Just replace the alias with the actual case expression like this:
SELECT
breeds.*,
CASE bc.user_val
WHEN NULL THEN bc.value
ELSE (bc.value + (bc.user_val/2))/2
END AS val
FROM
breed_characteristics bc
INNER JOIN breeds ON breeds.id = bc.breed_id
WHERE bc.characteristic_id = 45
AND CASE WHEN bc.user_val is NULL THEN bc.value
ELSE (bc.value + (bc.user_val/2))/2
END BETWEEN 4 AND 5
ORDER BY val DESC
However, you can use alias in order by clause.
One option to avoid restating the CASE expression in multiple places is to use a subquery:
SELECT *
FROM
(
SELECT b.*,
bc.characteristic_id,
CASE WHEN bc.user_val IS NULL THEN bc.value
ELSE (bc.value + (bc.user_val / 2)) / 2
END AS val
FROM breed_characteristics bc
INNER JOIN breeds b
ON breeds.id = bc.breed_id
) t
WHERE t.characteristic_id = 45 AND
t.val BETWEEN 4 AND 5
ORDER BY t.val DESC
Related
Here I have two tables as student_information and exmaination_marks.
examination_marks table have 3 columns for three subjects and include their marks.
I want to select the roll_number and name of the student from the student_information table where sum of the three subject's marks in examination_marks table is less than 100.
Both table has roll_number as primary key.
Here is the query I wrote.
select
si.roll_number,
si.name
from
student_information as si
left outer join examination_marks as em on
si.roll_number = em.roll_number
where
sum(em.subject_one + em.subject_two + em.subject_three) < 100;
But I got an error saying "ERROR 1111 (HY000) at line 1: Invalid use of group function"
Can any one help me with this?
sum(em.subject_one + em.subject_two + em.subject_three)< 100
this is the problem . Try these
Where (SELECT subject_one + subject_two + subject_three FROM examination_marks WHERE em.roll_number = si.roll_number) < 100
SUM is an "aggregate function" which can only be used inside a query which has a GROUP BY clause.
To get the sum of values within the same row you need to use the + operator. If the columns are NULL-able then you'll also need to use COALESCE (or ISNULL) to prevent NULL values invalidating your entire expression.
Like so:
SELECT
si.roll_number,
si.name,
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) AS sum_marks
FROM
student_information AS si
LEFT OUTER JOIN examination_marks AS em ON
si.roll_number = em.roll_number
WHERE
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) < 100;
(If you're wondering why the COALESCE( em.subje... expression is repeated in the SELECT and WHERE clauses, that's because SQL is horribly designed by (obscene profanities) is an unnecessarily verbose language).
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)
)
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.
If I run my query like this:
select
Sys.1,Sys.2,Sys.3,
DDD.a,DDD.b,DDD.c,
Gen.x,Gen.y,Gen.z
from sys_table Sys
join ddd_table DDD on (Sys.3=DDD.a)
join gen_table Gen on (DDD.a=Gen.x)
where
Sys.1 = 'string'
AND Sys.2 = 1
AND Sys.3 = 1
GROUP BY a
I get an error 'Ambiguous column name 'a'.
If I specify the table like here:
select
Sys.1,Sys.2,Sys.3,
DDD.a,DDD.b,DDD.c,
Gen.x,Gen.y,Gen.z
from sys_table Sys
join ddd_table DDD on (Sys.3=DDD.a)
join gen_table Gen on (DDD.a=Gen.x)
where
Sys.1 = 'string'
AND Sys.2 = 1
AND Sys.3 = 1
GROUP BY DDD.a
I get the error: Column 'sys_table.1' is invalid in the select list because it is not contained either an aggregate function or the GROUP BY clause.
What am I missing?
Sam yi is correct. The group by must be by all columns that are not part of an aggregate. Some engines allow this loosely to just grab the first instance of the column from whatever table if it is not an aggregate or part of the group by. Since you don't even have any aggregates, you can just apply a "max()" against each one, and if the values are never changing and would be the same across the board, should be no impact.
Also, having column names as just a number (I didnt even think was allowed), is IMO a very bad thing to deal with, but believe this is only because you are hiding actual content in relation to the REAL problem you are encountering.
select
DDD.a,
max( Sys.1 ) as `1`,
max( Sys.2 ) as `2`,
max( Sys.3 ) as `3`,
max( DDD.b ) as b,
max( DDD.c ) as c,
max( Gen.x ) as x,
max( Gen.y ) as y,
max( Gen.z ) as z
from
sys_table Sys
join ddd_table DDD on (Sys.3 = DDD.a)
join gen_table Gen on (DDD.a = Gen.x)
where
Sys.1 = 'string'
AND Sys.2 = 1
AND Sys.3 = 1
GROUP BY
DDD.a
The first error appears probably because the field name "a" exists in more than one tables. In the second query you need to group with all the fields you are selecting (actually you don't need to group at all, there's no meaning to group to all your fields since you don't use an aggregate function).
Hence, your select will be:
select
Sys.1,Sys.2,Sys.3,DDD.a,DDD.b,DDD.c,Gen.x,Gen.y,Gen.z
from
sys_table Sys
join ddd_table DDD on (Sys.3=DDD.a)
join gen_table Gen on (DDD.a=Gen.x)
where
Sys.1 = 'string' AND Sys.2 = 1 AND Sys.3 = 1
I would like to use the IN clause, but with the convert function.
Basically, I have a table (A) with the column of type int.
But in the other table (B) I Have values which are of type varchar.
Essentially, what I am looking for something like this
select *
from B
where myB_Column IN (select myA_Columng from A)
However, I am not sure if the int from table A, would map / convert / evaluate properly for the varchar in B.
I am using SQL Server 2008.
You can use CASE statement in where clause like this and CAST only if its Integer.
else 0 or NULL depending on your requirements.
SELECT *
FROM B
WHERE CASE ISNUMERIC(myB_Column) WHEN 1 THEN CAST(myB_Column AS INT) ELSE 0 END
IN (SELECT myA_Columng FROM A)
ISNUMERIC will be 1 (true) for Decimal values as-well so ideally you should implement your own IsInteger UDF .To do that look at this question
T-sql - determine if value is integer
Option #1
Select * from B where myB_Column IN
(
Select Cast(myA_Columng As Int) from A Where ISNUMERIC(myA_Columng) = 1
)
Option #2
Select B.* from B
Inner Join
(
Select Cast(myA_Columng As Int) As myA_Columng from A
Where ISNUMERIC(myA_Columng) = 1
) T
On T.myA_Columng = B.myB_Column
Option #3
Select B.* from B
Left Join
(
Select Cast(myA_Columng As Int) As myA_Columng from A
Where ISNUMERIC(myA_Columng) = 1
) T
On T.myA_Columng = B.myB_Column
I will opt third one. Reason is below mentioned.
Disadvantages of IN Predicate
Suppose I have two list objects.
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
Using Contains, it will search for each List-1 item in List-2 that means iteration will happen 49 times !!!
You can also use exists caluse,
select *
from B
where EXISTS (select 1 from A WHERE CAST(myA_Column AS VARCHAR) = myB_Column)
You can use below query :
select B.*
from B
inner join (Select distinct MyA_Columng from A) AS X ON B.MyB_Column = CAST(x.MyA_Columng as NVARCHAR(50))
Try it by using CAST()
SELECT *
FROM B
WHERE CAST(myB_Column AS INT(11)) IN (
SELECT myA_Columng
FROM A
)