mysql contradictory queries to run simultaneously - mysql

I'm having problem working around the logic on how to build a particular query.
What I have is a form that narrows housing listings down by things like number of bedrooms, sq ft, etc.
My issue is writing a query that includes both city and zip code parameters along with the details of the house.
For example:
SELECT * FROM my_houses
WHERE
BEDROOMS >= 3
AND
SQFT >= 1500
AND
CITY IN ('Gotham', 'Metropolis', 'Central')
VS
SELECT * FROM my_houses
WHERE
BEDROOMS >= 3
AND
SQFT >= 1500
AND
CITY IN ('Gotham', 'Metropolis', 'Central')
OR
ZIP IN ('65656', '65432', '63254')
Now, as I understand it, when I use OR it doesn't put the other paraments against ZIP, so it will show all entries with those ZIP values, regardless of number of bedrooms. Also that cities and ZIP's are a little mutually exclusive, so there would be a conflict with something meeting a CITY value but not a ZIP and thus would be excluded. But, if I can separate them out, that shouldn't matter.
Is there a way to get around this without writing two sub queries?

logically group your OR with parenthesis... something like...
WHERE
BEDROOMS >= 3
AND
SQFT >= 1500
AND
( CITY IN (Gotham, Metropolis, Central)
OR
ZIP IN (65656, 65432, 63254) )
However, your city and ZIP values would be expected within quotes such as
CITY IN ( 'Gotham', 'Metropolis', 'Central')
ZIP IN ('65656', '65432', '63254' )

Use parens to group your or clause. That way, if either one is true, it will satisfy the AND
SELECT * FROM my_houses
WHERE
BEDROOMS >= 3
AND
SQFT >= 1500
AND
(
CITY IN (Gotham, Metropolis, Central)
OR
ZIP IN (65656, 65432, 63254)
)

You may be missing the brackets :)
SELECT * FROM my_houses
WHERE
BEDROOMS >= 3
AND
SQFT >= 1500
AND (
CITY IN (Gotham, Metropolis, Central)
OR
ZIP IN (65656, 65432, 63254)
)

Related

What are the MySQL queries for the following tasks? Are my solutions and line of thinking correct so far? Thank you very much

This is my very first question on Quora. Thanks for any recommendations , solutions and remarks. I was not provided with many specifics and data, this is a assignments where one must use his or her imagination to fill in particular data and variables. What counts is the correct logic, approach and covering possibilities. Your help is highly appreciated! Thank you!
Country and Continent table
Required Visual Result for Question 3
Questions:
Write a query that would select all countries with GDP of more than 1 000 000 000 USD
Write a query that would return all countries in Europe (specifically) with GDP of more than 1 000 000 000 USD
Write a query that lists all continents with GDP per continent (as the sum of the GDP of all countries). Each country belong to one continent only.
For what result should look like - please resort to "Required Visual Result for Question 3" image.
My Solutions:
select * from countries where GDP > 1000000000
select * from countries where continent_id = 2 and GDP>1000000000;
select sum(GDP) from countries where continent_id = 4;
However, here in 3) I can only have the GDP sum displayed, and do not know how to have the continent's name on the left side as well. Please, if possible, assist with having the continent's name displayed and then right next to it and on the right handside - the relevant GDP sum.
Welcome!
Your image shows the tables as country and continent but your queries refer to countries? So which is it please?
On the basis your image is correct but the queries are wrong then number 3 would be as below:
With no 3 your currently only going to get the some for the continent with the ID of 4.
select sum(GDP) from country where continent_id = 4;
So what you want to do is remove the WHERE and the GROUP BY continent_id to give you 1 result per continent.
select sum(GDP) from country where 1 GROUP BY continent_id
No to get the continent name included in your results you can use the JOIN syntax.
In this instance you want all your records from country and just the records from continent that match your join condition which will be the continent_id from country and the id from the continent table.
SELECT
`continent`.`name`, sum(`GDP`)
FROM `country`
LEFT JOIN `continent`
ON `country`.`continent_id` = `continent`.`id`
GROUP BY `continent_id`
ORDER BY `continent`.`name` ASC;
That should give you the results 1 per continent as required.
I've specified the table names as its clearer how to target specific columns from each table.

SSRS Row Group with non-aggregated measure column

I'm not finding any other questions exactly like mine, so it's time to ask.
I have an SSRS 2016 report. It's got a regional hierarchy (State, City, Location). And it's got one measure column that is a calculation performed in the stored procedure. Due to the nature of the calculation, the value of the calculation for a city must be performed independently in the stored procedure. It's not a simple aggregation of the Locations in the City, so it cannot simply be aggregated in the report. I need the report to expand and contract on the regional hierarchy columns, and to pull the measure values straight from the dataset with aggregating.
In other words
I have a dataset like this:
State City Location Measure
FL NULL NULL 25
FL Miami NULL 12
FL Miami Walmart 52
FL Miami Kmart 3
FL Orlando NULL 33
FL Orlando Sears 4
I need for the report to have collapsible rowgroups at the State and City levels, with Location being the "detail" level row group. But I need the value of Measure to be 12 for Miami, and not some aggregation of 2 & 3 (Walmart and Kmart).
I figure the approach must be either:
Use traditional row groups and do some kind of programming in the expression of the measure column for the two upper-level row groups, or
Don't put row groups on the tablix and do conditional formatting of the rows and some kind of programming in the toggle properties.
But in both cases, I'm not seeing anything I can do that SSRS will actually allow for the "some kind of programming" bit.
Is there a solution?
If you must do it in the report, I think you could use a table a FILTER out the NULL city and location values. When you need them you could do a Lookup to get the value from the dataset. This will lookup the Measure value for a City where the IIF will act as a filter for the NULL value - if there is a location the City will have an X0 added and won't match the Lookup City.
=Lookup(Fields!City.Value, Fields!City.Value & IIF(ISNOTHINGFields!Location.Value), "", "x0"), Fields!Measure.Value, "Dataset1")
If you can put your current results in a temp table, a better way would be to add the totals as seperate fields in the query.
SELECT 'FL' AS State, NULL AS City , NULL as Location, 25 as Measure
INTO #TABLE
UNION
SELECT 'FL' AS State, 'Miami' AS City , NULL AS Location, 12 as Measure
UNION
SELECT 'FL' AS State, 'Miami' AS City , 'Walmart' as Location, 52 as Measure
UNION
SELECT 'FL' AS State, 'Miami' AS City , 'Kmart' as Location, 3 as Measure
UNION
SELECT 'FL' AS State, 'Orlando' AS City , null as Location, 33 as Measure
UNION
SELECT 'FL' AS State, 'Orlando' AS City , 'Sears' as Location, 4 as Measure
--DROP TABLE #TABLE
SELECT T.*, T_S.Measure AS STATE_MEASURE, T_C.Measure AS CITY_MEASURE
FROM #TABLE T
LEFT JOIN #TABLE T_S ON T.State = T_S.State AND T_S.City IS NULL
LEFT JOIN #TABLE T_C ON T.State = T_C.State AND T_C.City = T.City AND T_C.Location IS NULL
WHERE T.City IS NOT NULL AND T.Location IS NOT NULL
This will let you just have the recordsd you need with the additional comlumns for the summary data.
Group on state and city and don't use SUM() for your Measure column
Your layout could be like the one below

How to find average difference in mysql?

Consider a table employee storing the details of the employee.
ssn : social security number of the employee
address : storing the address of the employee
Looking at the address field in the employee table, you would notice that all the employees reside in "Fondren, Houston, TX". Consider the integer in the address field as house number. Consider the distance between the two houses as the difference in the house numbers, so the distance between house number 2 and 38 is 36 units. Write a query to determine the average distance between the house of the employee with ssn = '123456789' and the other employees' houses. Print the answer to two decimal places. Make sure that the answer is formatted with a comma like x,xxx.xx .
Can someone please help me solving this problem?
I do not want to use a SQL function.
The query I have made is:
SELECT
avg(
abs(CAST(address AS UNSIGNED) -
SELECT CAST(address AS UNSIGNED) from test.test where ssn = 1234)
) as average from test.test;
Assuming you don't want to include the distance from the employee's house to their own house, you need to compute the average excluding that. One way to do that is by CROSS JOINing a table of the numbers of employee houses not including the employee of interest, and a table of the number of the employee of interest's house. You can then compute the SUM of the absolute differences and divide that by the row count to get the average. You can then use FORMAT to get the output in the desired format:
SELECT FORMAT(SUM(ABS(oth - emp)) / COUNT(oth), 2) AS average
FROM (
SELECT CAST(address AS SIGNED) AS oth
FROM test
WHERE ssn != '123456789'
) t
CROSS JOIN (
SELECT CAST(address AS SIGNED) AS emp
FROM test
WHERE ssn = '123456789'
) t2
Demo on SQLFiddle
SELECT format (avg(abs(substring_index(address, ' ', 1)-(SELECT
substring_index(address, ' ', 1)
FROM employee
WHERE ssn = '123456789'
))), 2)
FROM employee
WHERE ssn != '123456789';

How do I Understand correlated queries?

I just started an sql exercise-style tutorial BUT I still haven't grasped the concept of correlated queries.
name, area and continent are fields on a table.
The query is to Find the largest country (by area) in each continent, show the continent, the name and the area.
The draft work so far:
SELECT continent, name, population FROM world x
WHERE area >= ALL
(SELECT area FROM world y
WHERE y.continent=x.continent
AND population>0)
Tried reading up on it on a few other blogs.
need to understand the logic behind correlated queries.
I assume the query you posted work. You just need clarification of what it does.
SELECT continent, name, population
FROM world x
WHERE area >= ALL (
SELECT area FROM world y
WHERE y.continent=x.continent
AND population>0
)
The query translates to
"Get the continent, name, and population of a country where area is bigger than or equal to all other countries in the same continent".
The WHERE clause in the inner query is to link the 2 queries (in this case countries in the same continent). Without the WHERE, it will get the country with the largest are in the world.
You can think of a correlated subquery as a looping mechanism. This is not necessarily how it is implemented, but it describes what it does.
Consider data such as:
row continent area population
1 a 100 19
2 a 200 10
3 a 300 20
4 b 15 2000
The outer query loops through each row. Then it looks at all matching rows. So, it takes record 1:
row continent area population
1 a 100 19
It then runs the subquery:
(SELECT w2.area
FROM world w2
WHERE w2.continent = w.continent AND
w2.population > 0
)
And substitutes in the values from the outer table:
(SELECT w2.area
FROM world w2
WHERE w2.continent = 'a' AND
w2.population > 0
)
This returns the set (100, 200, 300).
Then it applies the condition:
where w1.area >= all (100, 200, 300)
(This isn't really valid SQL but it conveys the idea.)
Well, we know that w1.area = 100, so this condition is false.
The process is then repeated for each of the rows. For the "a" continent, the only row that meets the condition is the third one -- the one with the largest area.

Query specific fields in 3 tables-PHPMyAdmin

I have four tables (university, statistics, address, records)
University table has the following: (UName, Web Address, ID, (serves as PK)
Statistics: UniversityID, Division, 2012RankPosition,2011 RankPosition,2010 RankPosition,2009 RankPosition
Address: UniversityID, City, State, Zip code
Records: IDUniversity, Wins, Losses, Draw
I want to find all division 2 schools in New York and have their zip codes displayed as well. Can someone help me with this please? I am stuck.
Also, I want to find all division 2 schools that ranked in the top 10 for the past 4 seasons.
If someone has any input i would greatly appreciate it.
First query try this... but i dont know if division 2 = new york...
Select *
FROM University
JOIN Address on University.id = Address.UniversityID
JOIN Statistics on University.id = Statistics.UniversityID
WHERE Statistics.Division = 2
Second query depends on how you have stored the ranking ... if its just number 1 - best , 2,3 etc are worser
Select *
FROM University
JOIN Statistics on University.id = Statistics.UniversityID
WHERE Statistics.Division = 2
AND 2012RankPosition <= 10
AND 2011RankPosition <= 10
AND 2010RankPosition <= 10
AND 2009RankPosition <= 10
Hope that helps