MySQL subquery returns more than one row - sql

I am executing this query:
SELECT
voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
COUNT((SELECT voterfile_voter.ID
FROM voterfile_voter
JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID)) AS Voters
FROM voterfile_precienct JOIN voterfile_county
WHERE voterfile_precienct.County_ID = voterfile_County.ID;
I am trying to make it return something like this:
County_Name Prec_ID Prec_Name Voters(Count of # of voters in that precienct)
However, I am getting the error:
#1242 - Subquery returns more than 1 row.
I have tried placing the COUNT statement in the subquery but I get an invalid syntax error.

If you get error:error no 1242 Subquery returns more than one row, try to put ANY before your subquery. Eg:
This query return error:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
This is good query:
SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2);

You can try it without the subquery, with a simple group by:
SELECT voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
count(voterfile_voter.ID)
FROM voterfile_county
JOIN voterfile_precienct
ON voterfile_precienct.County_ID = voterfile_County.ID
JOIN voterfile_household
ON voterfile_household.Precnum = voterfile_precienct.PREC_ID
JOIN voterfile_voter
ON voterfile_voter.House_ID = voterfile_household.ID
GROUP BY voterfile_county.Name,
voterfile_precienct.PREC_ID,
voterfile_precienct.Name
When you use GROUP BY, any column that you are not grouping on must have an aggregate clause (f.e. SUM or COUNT.) So in this case you have to group on county name, precienct.id and precient.name.

Try this
SELECT
voterfile_county.Name, voterfile_precienct.PREC_ID,
voterfile_precienct.Name,
(SELECT COUNT(voterfile_voter.ID)
FROM voterfile_voter JOIN voterfile_household
WHERE voterfile_voter.House_ID = voterfile_household.ID
AND voterfile_household.Precnum = voterfile_precienct.PREC_ID) as Voters
FROM voterfile_precienct JOIN voterfile_county
ON voterfile_precienct.County_ID = voterfile_County.ID

See the below example and modify your query accordingly.
select COUNT(ResultTPLAlias.id) from
(select id from Table_name where .... ) ResultTPLAlias;

Related

SQL Subquery Having COUNT(var) turns 0 to NULLs

I have written a SQL query with a subquery to include counts. When the count is 0, and I try to filter out the 0, it turns the 0's to NULLs and keeps the rows, and vice versa. The result is that I can't filter out the 0's, which was the purpose of including the counts.
SELECT distinct
a
,b
,
(SELECT
count(id)
FROM seq_stud
WHERE scs.SequenceID = seq_stud.SequenceID
and seq_stud.EndDate is null
HAVING count(id) <> 0
) As t1
FROM sp
INNER JOIN p on sp.ProgramID = p.ProgramID
...etc.
Does anyone know why this is happening and how I can filter out the 0 counts?
You don't filter in the SELECT clause. If you don't want rows that have no match in seq_stud, then use WHERE:
WHERE EXISTS (SELECT 1
FROM seq_stud ss
WHERE scs.SequenceID = ss.SequenceID and ss.EndDate is null
)
I would remove the HAVING statement altogether. You need to put that in the WHERE clause. Otherwise, it will return null, as you found.
SELECT distinct a, b,
(SELECT count(id)
FROM seq_stud
WHERE scs.SequenceID = seq_stud.SequenceID
and seq_stud.EndDate is null
) As t1
FROM sp
INNER JOIN p on sp.ProgramID = p.ProgramID
WHERE t1 > 0
I just figured this out. The Select subquery should be included as a WHERE statement
Using having count() in exists clause

Ms Access query to SQL Server - DistinctRow

What would the syntax be to convert this MS Access query to run in SQL Server as it doesn't have a DistinctRow keyword
UPDATE DISTINCTROW [MyTable]
INNER JOIN [AnotherTable] ON ([MyTable].J5BINB = [AnotherTable].GKBINB)
AND ([MyTable].J5BHNB = [AnotherTable].GKBHNB)
AND ([MyTable].J5BDCD = [AnotherTable].GKBDCD)
SET [AnotherTable].TessereCorso = [MyTable].[J5F7NR];
DISTINCTROW [MyTable] removes duplicate MyTable entries from the results. Example:
select distinctrow items
items.item_number, items.name
from items
join orders on orders.item_id = items.id;
In spite of the join getting you the same item_number and name multiple times when there is more than one order for it, DISTINCTROW reduces this to one row per item. So the whole join is merely for assuring that you only select items for which exist at least one order. You don't find DISTINCTROW in any other DBMS as far as I know. Probably because it is not needed. When checking for existence, we use EXISTS of course (or IN for that matter).
You are joining MyTable and AnotherTable and expect for some reason to get the same MyTable record multifold for one AnotherTable record, so you use DISTINCTROW to only get it once. Your query would (hopefully) fail if you got two different MyTable records for one AnotherTable record.
What the update does is:
update anothertable
set tesserecorso = (select top 1 j5f7nr from mytable where mytable.j5binb = anothertable.gkbinb and ...)
where exists (select * from mytable where mytable.j5binb = anothertable.gkbinb and ...)
But this uses about the same subquery twice. So we'd want to update from a query instead.
The easiest way to get one result record per <some columns> in a standard SQL query is to aggregate data:
select *
from anothertable a
join
(
select j5binb, j5bhnb, j5bdcd, max(j5f7nr) as j5f7nr
from mytable
group by j5binb, j5bhnb, j5bdcd
) m on m.j5binb = a.gkbinb and m.j5bhnb = a.gkbhnb and m.j5bdcd = a.gkbdcd;
How to write an updateble query is different from one DBMS to another. Here is the final update statement for SQL-Server:
update a
set a.tesserecorso = m.j5f7nr
from anothertable a
join
(
select j5binb, j5bhnb, j5bdcd, max(j5f7nr) as j5f7nr
from mytable
group by j5binb, j5bhnb, j5bdcd
) m on m.j5binb = a.gkbinb and m.j5bhnb = a.gkbhnb and m.j5bdcd = a.gkbdcd;
The DISTINCTROW predicate in MS Access SQL removes duplicates across all fields of a table in join statements and not just the selected fields of query (which DISTINCT in practically all SQL dialects do). So consider selecting all fields in a derived table with DISTINCT predicate:
UPDATE [AnotherTable]
SET [AnotherTable].TessereCorso = main.[J5F7NR]
FROM
(SELECT DISTINCT m.* FROM [MyTable] m) As main
INNER JOIN [AnotherTable]
ON (main.J5BINB = [AnotherTable].GKBINB)
AND (main.J5BHNB = [AnotherTable].GKBHNB)
AND (main.J5BDCD = [AnotherTable].GKBDCD)
Another variant of the query.. (Too lazy to get the original tables).
But like the query above updates 35 rows =, so does this one
UPDATE [Albi-Anagrafe-Associati]
SET
[Albi-Anagrafe-Associati].CRegDitte = [055- Registri ditte].[CRegDitte],
[Albi-Anagrafe-Associati].NIscrTribunale = [055- Registri ditte].[NIscrTribunale],
[Albi-Anagrafe-Associati].NRegImprese = [055- Registri ditte].[NRegImprese]
FROM [055- Registri ditte]
WHERE EXISTS(
SELECT *
FROM [055- Registri ditte]-- [Albi-Anagrafe-Associati]
WHERE ([055- Registri ditte].GIBINB = [Albi-Anagrafe-Associati].GKBINB)
AND ([055- Registri ditte].GIBHNB = [Albi-Anagrafe-Associati].GKBHNB)
AND ([055- Registri ditte].GIBDCD = [Albi-Anagrafe-Associati].GKBDCD))
Update [AnotherTable]
Set [AnotherTable].TessereCorso = MyTable.[J5F7NR]
From [AnotherTable]
Inner Join
(
Select Distinct [J5BINB],[5BHNB],[J5BDCD]
,(Select Top 1 [J5F7NR] From MyTable) as [J5F7NR]
,[J5BHNB]
From MyTable
)as MyTable
On (MyTable.J5BINB = [AnotherTable].GKBINB)
AND (MyTable.J5BHNB = [AnotherTable].GKBHNB)
AND (MyTable.J5BDCD = [AnotherTable].GKBDCD)

error is Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I got an error
Column 'Employee.EmpID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SQL code:
with cte(stu_id,term_cd, spcl_cd ) as
(
Select
zt.[STU_ID], zt.TERM_CD, zt.SPCL_CD
From
SR0TZT(nolock) zt
Inner Join
(Select
STU_ID, MIN(TERM_SEQ_NUM) MinPoint, SPCL_CD
From SR0TZT
Group By STU_ID) tbl1 On zt.STU_ID = tbl1.STU_ID
Where
tbl1.MinPoint = zt.TERM_SEQ_NUM
and zt.STU_ID = '202716354'
and tbl1.SPCL_CD = zt.SPCL_CD
)
SELECT
zt.[STU_ID], zt.[TERM_CD], zt.[SPCL_CD],
zt.[SPCL_STRT_TERM], zt.TERM_SEQ_NUM, t.term_id
FROM
SR0TZT zt
JOIN
cte ON zt.STU_ID = cte.stu_id
WHERE
zt.STU_ID = '202716354'
Condition is:
For each unique combination of TZT.STU_ID and TZT.SPCL_CD where TZT.COLL_CD = '', display the TZT.TERM_CD with the minimum TZT.TERM_SEQ_NUM.
For UID 202716354, based on the above rule, the value of this column is incorrect for both specialization codes.
Not sure I understand why you are getting an error for 'Employee.EmpID' as it doesn't appear in your query.
At first look I can see that the following part of your SQL code (the derived table 'tbl1')...
Select STU_ID,MIN(TERM_SEQ_NUM) MinPoint,SPCL_CD From SR0TZT Group By STU_ID
..is incorrect and would cause a similar error because SPCL_CD isn't used in an aggregate function (such as MIN) or in the GROUP BY. You should change it to:-
Select STU_ID,MIN(TERM_SEQ_NUM) MinPoint,SPCL_CD From SR0TZT Group By STU_ID, SPCL_CD
And that should solve your problem.
Your problem is in this below script:
Select STU_ID,MIN(TERM_SEQ_NUM) MinPoint,SPCL_CD From SR0TZT Group By STU_ID
It should be:
Select STU_ID,MIN(TERM_SEQ_NUM) MinPoint,SPCL_CD From SR0TZT Group By STU_ID, SPCL_CD
Every column that you put in select, you should put them too in group by.

UsingCoaslesce function with distinct

I'm trying to fetch some data from a relational database and order it based on the payed_at column. In case payed_at is null, I want he updated_at column to be used instead. My query so far is bellow:
SELECT DISTINCT "orders".*
FROM "orders" INNER JOIN "order_items" ON "order_items"."order_id" = "orders"."id"
WHERE (orders.state = 'payed') AND (physical = true) AND (kind = 'output')
ORDER BY coalesce(orders.payed_at, orders.updated_at) DESC
LIMIT 200 OFFSET 0
I'm getting the following error from Postgres:
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
It might be a problem with DISTINCT in the query, because when I remove DISTINCT word I get no error.
I'm using the coalesce function.
I'm stuck with this error.
The error states that when using SELECT DISTINCT and ordering by an expression, you must include the expression in the SELECT list. Your expression is the COALESCE.
SELECT DISTINCT coalesce(orders.payed_at, orders.updated_at),...
FROM "orders"
INNER JOIN "order_items" ON "order_items"."order_id" = "orders"."id"
WHERE (orders.STATE = 'payed')
AND (physical = true)
AND (kind = 'output')
ORDER BY coalesce(orders.payed_at, orders.updated_at) DESC LIMIT 200 OFFSET 0

Error #1349: View's select cluse contains a subquery in the from clause

Here is my code:
SELECT CAST.first_name,
CAST.last_name,
AWARDED.castID,
COUNT(*) AwardsWon
FROM AWARDED,
ROLE,
CAST
WHERE ROLE.role = "Director"
AND ROLE.castID = AWARDED.castID
AND ROLE.movieID = AWARDED.movieID
AND AWARDED.castID = CAST.castID
GROUP BY castID
HAVING COUNT(*) =
(SELECT MAX(cnt) FROM
(SELECT COUNT(*) cnt FROM AWARDED GROUP BY CastID
) z
)
When I try and create a view from this code I get an error of the form: #1349 view's select contains a subquery in the from clause. Are there any ways that this can be worked around?
The statement says...
• The SELECT statement cannot contain a subquery in the FROM clause.
Your workaround would be to create a view for each of your subqueries.
Then access those views from within your view
If I am not wrong you are using MySQL. Not sure but your said query can be transformed as below. give it a try.
SELECT `CAST`.first_name,
`CAST`.last_name,
AWARDED.castID,
COUNT(AWARDED.castID) AwardsWon
FROM AWARDED
JOIN ROLE
ON ROLE.movieID = AWARDED.movieID
AND ROLE.castID = AWARDED.castID
JOIN `CAST`
ON AWARDED.castID = `CAST`.castID
WHERE ROLE.role = 'Director'
GROUP BY AWARDED.castID,`CAST`.first_name,`CAST`.last_name
HAVING COUNT(*) = MAX(AwardsWon);