Query Not returning exactly what I want - sql

I'm a little confused to why my query is not returning exactly what I expect. This is my query in SQL.
"SELECT \"users\".* FROM \"users\" INNER JOIN \"alerts\" ON \"alerts\".\"user_id\" = \"users\".\"id\" WHERE (bus_route = 'The 06:30 To Wexford' AND stop = 'Camolin' AND first_alert = '5' OR second_alert = '5' OR third_alert = '5')"
And this is what I have in Rails:
Alert.where("bus_route = '#{b}' AND stop = '#{s}' AND first_alert = '#{t}' OR second_alert = '#{t}' OR third_alert = '#{t}'")
The conditions I am aiming for here is to find an alert with the bus_route passed, stop passed and either the first, second or third alert can equal the time in minutes passed.
But what my query is doing is returning is an alert where as long as any of the alert fields equal the parameter passed and the bus_route and stop do not equal.
I am a big SQL and Rails query noob for the record and this is my first "complex" query.
Help would be appreciated thanks.

Add parentheses around the first_alert = '#{t}' OR second_alert = '#{t}' OR third_alert = '#{t}' section, OR has a lower priority than AND.

you can try to enclose the OR statements in a parenthesis
"SELECT \"users\".* FROM \"users\" INNER JOIN \"alerts\" ON \"alerts\".\"user_id\" = \"users\".\"id\" WHERE ((bus_route = 'The 06:30 To Wexford' AND stop = 'Camolin') AND (first_alert = '5' OR second_alert = '5' OR third_alert = '5'))"

Related

SQL CASE after in WHERE condition with single or multiple where results

I have the following code running in part of excel data query getting information from excel
`
DateTable.FiscalYear IN (?-1,?)
AND DateTable.Week = ?
AND ProductInformation.Brand = 'Drunk Elephant'
AND StoreInformation.Retailer IN CASE
WHEN ? = 'Boots' THEN ('Boots')
WHEN ? = 'Cult Beauty' THEN ('Cult Beauty')
WHEN ? = 'DTC' THEN ('DTC')
WHEN ? = 'Look Fantastic' THEN ('Look Fantastic')
WHEN ? = 'Space NK' THEN ('Space NK')
ELSE (SELECT
DISTINCT StoreInformation.Retailer
FROM
Sellout
INNER JOIN
ProductInformation
ON
Sellout.EAN = ProductInformation.EAN
INNER JOIN
StoreInformation
ON
sellout.StoreNumber = StoreInformation.StoreNumber
WHERE
ProductInformation.Brand = 'Drunk Elephant')
END
`
The ? are referencing cells in excel to bring back values. The code was running originally running fine with = CASE, but the I had to add in the final else clause, which brings back multiple results, so = no longer works. And putting the IN causes it to break, even if I remove the else and have just IN CASE.
Any ideas how to can run this case in the where clause, working if the result of the CASE is either a single value or a sub-query table?
Thanks in advance!
I have tried it with = CASE and without the ELSE, which work. Adding the ELSE brings back an error saying subquery brings back more then 1 value, which is why i tried with IN instead of =.
But having just IN without the ELSE also causes an error.

Convert MS Access Update Query to SQL Query

I have an MS Access Query:
'''UPDATE MyFloridaNetDataDump INNER JOIN RepoVoipAcsNonRecurring ON
'''MyFloridaNetDataDump.service_modified = RepoVoipAcsNonRecurring.Validation
'''SET RepoVoipAcsNonRecurring.Invoice = MyFloridaNetDataDump.Invoice_modified,
'''RepoVoipAcsNonRecurring.Amount = '''Round(MyFloridaNetDataDump.billable_charge*RepoVoipAcsNonRecurring.Percentage,2),
'''RepoVoipAcsNonRecurring.Billing Cycle = MyFloridaNetDataDump.bill_cycle;
I need to convert it to SQL, which I'm using in a .net application.
I have been able to convert most of the query, but when I try to perform the multiplication I get errors depending on what I leave in. Meaning if I take the ROUND function out it doesn't like the * multiplication. If I remove the multiplication line, the query runs.
'''UPDATE MyFloridaNetDataDump
'''SET MyFloridaNetDataDump.InvoiceModified = RepoVoipAcsNonRecurring.Invoice,
'''MyFloridaNetDataDump.BillableCharge * RepoVoipAcsNonRecurring.Percentage = '''RepoVoipAcsNonRecurring.Amount,
'''MyFloridaNetDataDump.BillCycle = RepoVoipAcsNonRecurring.BillingCycle
'''FROM RepoVoipAcsNonRecurring
'''WHERE MyFloridaNetDataDump.ServiceModified = RepoVoipAcsNonRecurring.Validation
I think you inverse all of your set columns
I would suggest you to do like this
UPDATE r
SET
Invoice = m.InvoiceModified,
Amount = Round(m.billablecharge*r.Percentage,2),
[BillingCycle] = m.billCycle
FROM
MyFloridaNetDataDump m
INNER JOIN RepoVoipAcsNonRecurring r ON m.serviceModified = r.Validation

sql select with one value of two where

This is the only place that I get all answer ;)
I want to select :
SELECT
RTRIM(LTRIM(il.Num_bloc)) AS Bloc,
RTRIM(LTRIM(il.num_colis)) AS Colis,
cd.transporteur AS Coursier,
cd.origine AS Origine,
cd.destination AS Destinataire,
cd.adresse AS [Adresse Destinataire],
cd.poids AS Poids,
il.Signataire, il.num_cin AS CIN, il.date_livraison AS [Date Livraison]
FROM
dbo.cd
INNER JOIN
dbo.il ON cd.bloc = il.Num_bloc AND dbo.cd.colis = dbo.il.num_colis
WHERE
(il.Num_bloc = RTRIM(LTRIM(#ParamBloc)))
AND (il.num_colis = RTRIM(LTRIM(#ParamColis)))
In the way of getting result if the user put ether #ParamBloc or #ParamColis
Try using IsNull() function.
A simple query would go like this
Select * from yourTable
Where
Num_bloc = ISNULL(#ParamBloc, Num_block) AND
num_colis = ISNULL(#ParamColis, num_colis)
The second parameter would make the expression to true if the #parameter Bloc or Colis is null. This query would be useful for all 4 possible combination of these two parameter.

SQL - Trouble with simple select query

I'm having some trouble figuring out why the SQL query below isn't working ... when members_only is set to 0, it's still showing them...
SELECT *
FROM reports
WHERE story = "1"
OR barebones = "1"
AND members_only = "1"
It depends on your data, but you may not be aware that AND has higher precedence in SQL than OR, so your query really evaluates to this:
SELECT *
FROM reports
WHERE story = '1'
OR (barebones = '1' AND members_only = '1')
Consider using different brackets per the other answers to explicitly declare your intentions
Use brackets to distinguish your clarify the WHERE-condition.
SELECT *
FROM reports
WHERE (story = '1' OR barebones = '1')
AND members_only = '1'
I would say because it reads the query as:
WHERE (story = '1') OR (barebones = '1' AND members_only = '1')
since story = '1', the condition is satisfied
OR clauses can be tricky - you often need to explicitly tell the query where it belongs. I assume, you want this:
WHERE (story = '1' OR barebones = '1') AND members_only = '1'
Missing parenthesis?
Did you want to do something like this:
SELECT *
FROM reports
WHERE (story = "1" OR barebones = "1") AND members_only = "1"
You are missing parenthesis.
The following code will work, assuming members_only HAS to be "1", but only story or barebones has to be "1".
SELECT *
FROM reports
WHERE
(story = "1" OR barebones = "1")
AND members_only = "1"
You should read up on TSQL Operator Precedence
In your original code, assume the following:
store = 1
barebones = 1
*members_only* = 0
Due to Operator Precedence, barebones and *members_only* is evaluated first, and evaluates to false.
Following this, the result of the first boolean evaluation (false) (also known as The Right Side) is compared to (story = "1") (also known as The Left Side).
The Right Side evaluates to false, but The Left Side evaluates to true.
Since the final boolean compression uses the OR operator, the end result is a TRUE, thus that record is indeed returned, no matter the value of either barebones or *members_only*, since The Left Side always evaluates to True.

Return a List of typed object via CreateSQLQuery in NHibernate

Been trying to get the following query working for a few hours now and am running out of ideas. Can anyone spot where I'm going wrong. Any pointers much appreciated.
CalEvents = (List<CalEvent>)session.CreateSQLQuery(#"
SELECT *
FROM dbo.tb_calendar_calEvents
INNER JOIN dbo.tb_calEvents
ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id)
WHERE dbo.tb_calendar_calEvents.calendarID = 'theCalID'"
)
.AddEntity(typeof(CalEvent))
.SetInt64("theCalID", cal.id);
Error:
Kanpeki.NUnit.CalUserTest.Should_return_logged_in_user:
System.ArgumentException : Parameter theCalID does not exist as a
named parameter in [SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN
dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID =
dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID =
'theCalID']
"SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID = 'theCalID'"
should be
"SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID = :theCalID"
= 'theCalID' should be written as = :theCalId; :theCalId is how you use named parameters even in Native SQL Queries.
You should remove the query.ExecuteUpdate() call.
Doing the query.List() is enough to issue the query on the session and return the result set.