I am trying to test users for a condition, then select all events of the main table that match the condition. I feel like I am doing something wrong:
WITH users_table AS (
SELECT
user_name,
SUM (CASE WHEN ( ud.age > 20 ) THEN 1 ELSE 0 END) AS UserEvents
FROM users_data AS ud
GROUP BY user_name
)
SELECT users_table.user_name FROM users_table
WHERE users_table.UserEvents > 10
;
That is, I want to use the with clause to make a table of all the users above the age of 20, then of that table select only use users that has more than 10 events.
For some reason I keep getting the error:
ERROR: multiple WITH clauses not allowed. SQL state: 42601
But I don't understand why? Also, why "multiple" with clauses...? There's only one with clause.
Best wishes,
-R
When you are using multiple common table expressions, you can only use the WITH keyword once. So it should look like:
WITH first_cte AS (
SELECT ...
),
second_cte AS (
SELECT ...
)
Related
I'm trying to nest this query, but I am getting the error: invalid input syntax for type boolean: "%malfunction%".
select *
from (
select column_one, column_two
from table
group by column_one, column_two
) as new_table
where column_two like '%false%' or '%malfunction%' or '%accidental%' or '%mistaken%'
order by column_one
Column_two is not boolean but it's identifying it as one.
I feel like I'm missing something small, but I can't find it. Help!
You can use any(array[...]), example:
with test (col) as (
values
('pear'), ('banana'), ('apple')
)
select *
from test
where col like any(array['%ea%', '%ba%']);
col
--------
pear
banana
(2 rows)
Correct syntax is something like select col1, col2,
from table_name
where condition1 OR condition2 OR condition3 ...;
My database name is test, I have a table named HaveGoal.
I am querying this:
SELECT Rel.total
FROM (SELECT H.number, H.teamname, SUM(H.numberofgoals) AS total
FROM HaveGoal H GROUP BY H.number,H.teamname) AS Rel
WHERE Rel.total = (SELECT MAX(Rel.total) FROM Rel)
It gives:ERROR 1146 (42S02): Table 'test.Rel' doesn't exist
It seems that the last subselect cannot reference a nested query defined in the FROM clause.
In this case you have multiple solutions :
Duplicate the first subselect inside the second (and hope that performance will not be too poor)
Define a view to make the nested query available everywhere
As you are looking for the maximum, you could sort data and take only the first line
If you where not on MySQL, you could use the WITH statement
Duplicating will work in any situation :
SELECT Rel.total
FROM (
SELECT H.number, H.teamname, SUM(H.numberofgoals) AS total
FROM HaveGoal H
GROUP BY H.number,H.teamname
) AS Rel
WHERE Rel.total = (
SELECT MAX(Rel2.total)
FROM (
SELECT H.number, H.teamname, SUM(H.numberofgoals) AS total
FROM HaveGoal H
GROUP BY H.number,H.teamname
) AS Rel2
)
Taking the first line after sorting is much shorter, but the MAX is implied :
SELECT Rel.total
FROM (
SELECT H.number, H.teamname, SUM(H.numberofgoals) AS total
FROM HaveGoalTest H
GROUP BY H.number,H.teamname
) AS Rel
ORDER BY total DESC
LIMIT 1
If I try to UNION (or INTERSECT or EXCEPT) a common table expression I get a syntax error near the UNION. If instead of using the CTE I put the query into the union directly, everything works as expected.
I can work around this but for some more complicated queries using CTEs makes things much more readable. I also just don't like not knowing why something is failing.
As an example, the following query works:
SELECT *
FROM
(
SELECT oid, route_group
FROM runs, gpspoints
WHERE gpspoints.oid = runs.start_point_oid
UNION
SELECT oid, route_group
FROM runs, gpspoints
WHERE gpspoints.oid = runs.end_point_oid
) AS allpoints
;
But this one fails with:
ERROR: syntax error at or near "UNION"
LINE 20: UNION
WITH
startpoints AS
(
SELECT oid, route_group
FROM runs, gpspoints
WHERE gpspoints.oid = runs.start_point_oid
),
endpoints AS
(
SELECT oid, route_group
FROM runs, gpspoints
WHERE gpspoints.oid = runs.end_point_oid
)
SELECT *
FROM
(
startpoints
UNION
endpoints
) AS allpoints
;
The data being UNIONed together is identical but one query fails and the other does not.
I'm running PostgreSQL 9.3 on Windows 7.
The problem is because CTEs are not direct text-substitutions and a UNION b is invalid SELECT syntax. The SELECT keyword is a mandatory part of the parsing and the syntax error is raised before the CTEs are even taken into account.
This is why
SELECT * FROM a
UNION
SELECT * FROM b
works; the syntax is valid, and then the CTEs (represented by a and b) are then used at the table-position (via with_query_name).
At least in SQL Server, I can easily do this - create two CTE's, and do a SELECT from each, combined with a UNION:
WITH FirstNames AS
(
SELECT DISTINCT FirstName FROM Person
), LastNames AS
(
SELECT DISTINCT LastName FROM Person
)
SELECT * FROM FirstNames
UNION
SELECT * FROM LastNames
Not sure if this works in Postgres, too - give it a try!
Using ms-sql 2008 r2; am sure this is very straightforward. I am trying to identify where a unique value {ISIN} has been linked to more than 1 Identifier. An example output would be:
isin entity_id
XS0276697439 000BYT-E
XS0276697439 000BYV-E
This is actually an error and I want to look for other instances where there may be more than one entity_id linked to a unique ISIN.
This is my current working but it's obviously not correct:
select isin, entity_id from edm_security_entity_map
where isin is not null
--and isin = ('XS0276697439')
group by isin, entity_id
having COUNT(entity_id) > 1
order by isin asc
Thanks for your help.
Elliot,
I don't have a copy of SQL in front of me right now, so apologies if my syntax isn't spot on.
I'd start by finding the duplicates:
select
x.isin
,count(*)
from edm_security_entity_map as x
group by x.isin
having count(*) > 1
Then join that back to the full table to find where those duplicates come from:
;with DuplicateList as
(
select
x.isin
--,count(*) -- not used elsewhere
from edm_security_entity_map as x
group by x.isin
having count(*) > 1
)
select
map.isin
,map.entity_id
from edm_security_entity_map as map
inner join DuplicateList as dup
on dup.isin = map.isin;
HTH,
Michael
So you're saying that if isin-1 has a row for both entity-1 and entity-2 that's an error but isin-3, say, linked to entity-3 in two separe rows is OK? The ugly-but-readable solution to that is to pre-pend another CTE on the previous solution
;with UniqueValues as
(select distinct
y.isin
,y.entity_id
from edm_security_entity_map as y
)
,DuplicateList as
(
select
x.isin
--,count(*) -- not used elsewhere
from UniqueValues as x
group by x.isin
having count(*) > 1
)
select
map.isin
,map.entity_id
from edm_security_entity_map as map -- or from UniqueValues, depening on your objective.
inner join DuplicateList as dup
on dup.isin = map.isin;
There are better solutions with additional GROUP BY clauses in the final query. If this is going into production I'd be recommending that. Or if your table has a bajillion rows. If you just need to do some analysis the above should suffice, I hope.
Am developing a report using the SQL Server BI Development Studio, when I try to create a function to sum the counts for StudentID, I get an error "Aggregate functions cannot be nested inside other aggregate functions"
The following is the expression am using:-
=Sum(Count(Fields!StudentID.Value))
How can I perform such a calculation?
You can do it this way
;With CountIds AS
(
SELECT COUNT(Fields!StudentID.Value) AS CountOfId FROM Table ...
)
SELECT Sum(CountOfId)
FROM CountIds
The "With" gives you the COUNT with the conditions that you want. Then you SUM it.
But I'm not quite sure the query returns what you want.. (Because when I test the query, it gives me the same result that a COUNT on all the table..) I think want you want to know is "How many Count you have".
If so, I would do it that way instead.
;With CountId AS
(
SELECT COUNT(Fields!StudentID.Value) AS CountOfId FROM Table ...
)
SELECT TOP 1 ROW_NUMBER() OVER (ORDER BY CountOfId)
FROM CountIds
ORDER BY 1 DESC
Or simply:
;With CountId AS
(
SELECT COUNT(Fields!StudentID.Value) AS CountOfId FROM Table ...
)
SELECT COUNT(*) FROM CountIds