SQL Select statement - base results upon the value of an alias within statement - sql

I am trying to write a Select statement (comprised of around 20 different joined aliases) that will only return results if the value of one of the aliases created within the same statement equals a certain value.
I'm very green with SQL at this point and therefore don't really know how to phrase this dilemma properly to find the answer elsewhere.
Current code for element being assigned an alias of "cmp_freq":
ISNULL((SELECT GroupValue FROM ClientGroup WHERE ClientKey = c.ClientKey AND GroupCode = 'CMP-FREQ'),'PLEASE UPDATE FIELD') AS cmp_freq
Essentially, I only want results returned for the entire statement where the value of cmp_freq is "30". Is there any way to reference this alias in the where clause of the statement as a whole in order to accomplish this?

There are several ways to accomplish your goal. One way would be to wrap your query in a SELECT and use a WHERE clause, like so:
SELECT i.cmp_freq
FROM (
/* Your existing query */
SELECT
ISNULL((SELECT GroupValue FROM ClientGroup WHERE ClientKey = c.ClientKey AND GroupCode = 'CMP-FREQ'),'PLEASE UPDATE FIELD') AS cmp_freq
FROM MyTable c
) i
WHERE i.cmp_freq = 30
It's difficult to offer other options as there is not enough information in your question.

Related

SQL Query to get all the data from tables when there is no parameter

I am trying to get the whole data when there are no filters selected. I have made an array that contains the selections. In case there are no selections then there will be just '' , i.e. no characters but not null.
SELECT * FROM Skills WHERE person IN ('Technology', 'Drilling');
For example - In this query it will return all required - filtered data. So my array contains Technology and Drilling. In case there is nothing selected by the user as a filter then the query would look like:
SELECT * FROM Skills WHERE person IN ('');
In this case the table is returning nothing in SQL Server. I want it to return everything from the table without any filters.
I would really like to get some help here and maybe some resources that might help me achieve the required thing.
The array is being filled in javascript.
It seems really strange to have a column called person compared to values like "Drilling". But you would do something like:
SELECT *
FROM Skills
WHERE person IN (<whatever>) OR <whatever> = '';
Often NULL is used to mean everything, so that would be:
WHERE person IN (<whatever>) OR <whatever> IS NULL;
And "whatever" might be a delimited string, so this might look like:
WHERE person IN (SELECT s.value FROM string_split(#params) s) OR
#params IS NULL;

Comparing the row with other row within same query

I have a question about the SQL Query.
Basically, I would like to get a sample value from the testCategory = compareTestCat and testType = compTestType.
I am not really sure if we can compare the first row with the fourth row within the same query.
Is there any way that I can do this?
Try SELF JOIN to compare values within the same table.
Try the Following:
SELECT A.*
FROM YourTable A
JOIN YourTable B ON A.testCategory = B.compareTestCat and A.testType = B.compTestType
A and B are the different alias names for the same table.
Based on the very sparse information you provided, this looks like what you need:
SELECT *
FROM
TestTable
WHERE
testCategory = compareTestCat
AND testType = compTestType;
UPDATE
If you are interested in comparing different rows in the same table with each other, then you will need to go with a self join on the table. Examples of solutions for this have already been provided by others.

How to use case statement to declare a local variable for a subsequent subquery?

Is it possible to declare a local variable depending on the case and then fire a common subquery?
Pseudo code:
SELECT
CASE
WHEN TABLE.TYPE = 'STUDENT' variable = "UNIVERSITY"
WHEN TABLE.TYPE = 'EMPLOYEE' variable = "EMPLOYER"
(Some big query here it has a common joins / groupings but the variable changes)
END AS NAME
FROM TABLE
Looking for a SQL Server solution.
Scenario is like this - I have a query that lists some member information . Now I need to get some addendum data to an existing query - I mean result set won't change . I can actually join but then I have to filter out many things - Does that make sense ? Imagine I was display all the members in the table and someone asks me to show the univeristy name or the employer name . And the biggest problem is a member can have more than one university he attended - same for employer . Isn't joins really bad on performance in this case ? Since there are many one to many stuff . Also please note I finally display only 10 records as part of pagination so I thought I should do a case statement .
DECLARE #variable varchar(10)
SELECT #variable =
CASE
WHEN t.TYPE = 'STUDENT' THEN 'UNIVERSITY'
WHEN t.TYPE = 'EMPLOYEE' THEN 'EMPLOYER'
ELSE 'Undefined'
END
FROM TableName t
MSDN - SELECT #local_variable
If the SELECT statement returns more than one value, the variable is
assigned the last value returned.

SQL Server where column in where clause is null

Let's say that we have a table named Data with Id and Weather columns. Other columns in that table are not important to this problem. The Weather column can be null.
I want to display all rows where Weather fits a condition, but if there is a null value in weather then display null value.
My SQL so far:
SELECT *
FROM Data d
WHERE (d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%' OR d.Weather IS NULL)
My results are wrong, because that statement also shows values where Weather is null if condition is not correct (let's say that users mistyped wrong).
I found similar topic, but there I do not find appropriate answer.
SQL WHERE clause not returning rows when field has NULL value
Please help me out.
Your query is correct for the general task of treating NULLs as a match. If you wish to suppress NULLs when there are no other results, you can add an AND EXISTS ... condition to your query, like this:
SELECT *
FROM Data d
WHERE d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'
OR (d.Weather IS NULL AND EXISTS (SELECT * FROM Data dd WHERE dd.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'))
The additional condition ensures that NULLs are treated as matches only if other matching records exist.
You can also use a common table expression to avoid duplicating the query, like this:
WITH cte (id, weather) AS
(
SELECT *
FROM Data d
WHERE d.Weather LIKE '%'+COALESCE(NULLIF('',''),'sunny')+'%'
)
SELECT * FROM cte
UNION ALL
SELECT * FROM Data WHERE weather is NULL AND EXISTS (SELECT * FROM cte)
statement show also values where Wether is null if condition is not correct (let say that users typed wrong sunny).
This suggests that the constant 'sunny' is coming from end-user's input. If that is the case, you need to parameterize your query to avoid SQL injection attacks.

What is the difference between the IN operator and = operator in SQL?

I am just learning SQL, and I'm wondering what the difference is between the following lines:
WHERE s.parent IN (SELECT l.parent .....)
versus
WHERE s.parent = (SELECT l.parent .....)
IN
will not generate an error if you have multiple results on the subquery. Allows to have more than one value in the result returned by the subquery.
=
will generate an error if you have more than one result on the subquery.
SQLFiddle Demo (IN vs =)
when you are using 'IN' it can compare multiple values....like
select * from tablename where student_name in('mari','sruthi','takudu')
but when you are using '=' you can't compare multiple values
select * from tablenamewhere student_name = 'sruthi'
i hope this is the right answer
The "IN" clause is also much much much much slower. If you have many results in the select portion of
IN (SELECT l.parent .....),
it will be extremely inefficient as it actually generates a separate select sql statement for each and every result within the select statement ... so if you return 'Cat', 'Dog', 'Cow'
it will essentially create a sql statement for each result... if you have 200 results... you get the full sql statement 200 times...takes forever... (This was as of a few years ago... maybe imporved by now... but it was horribly slow on big result sets.)
Much more efficient to do an inner join such as:
Select id, parent
from table1 as T
inner join (Select parent from table2) as T2 on T.parent = T2.parent
For future visitors.
Basically in case of equals (just remember that here we are talking like where a.name = b.name), each cell value from table 1 will be compared one by one to each cell value of all the rows from table 2, if it matches then that row will be selected (here that row will be selected means that row from table 1 and table 2) for the overall result set otherwise will not be selected.
Now, in case of IN, complete result set on the right side of the IN will be used for comparison, so its like each value from table 1 will be checked on whether this cell value is present in the complete result set of the IN, if it is present then that value will be shown for all the rows of the IN’s result set, so let say IN result set has 20 rows, so that cell value from table 1 will be present in overall result set 20 times (i.e. that particular cell value will have 20 rows).
For more clarity see below screen shot, notice below that how complete result set from the right of the IN (and NOT IN) is considered in the overall result set; whole emphasis is on the fact that in case comparison using =, matching row from second table is selected, while in case of IN complete result from the second table is selected.
In can match a value with more than one values, in other words it checks if a value is in the list of values so for e.g.
x in ('a', 'b', 'x') will return true result as x is in the the list of values
while = expects only one value, its as simple as
x = y returns false
and
x = x returns true
The general rule of thumb is:
The = expects a single value to compare with. Like this:
WHERE s.parent = 'father_name'
IN is extremely useful in scenarios where = cannot work i.e. scenarios where you need the comparison with multiple values.
WHERE s.parent IN ('father_name', 'mother_name', 'brother_name', 'sister_name')
Hope this is useful!!!
IN
This helps when a subquery returns more than one result.
=
This operator cannot handle more than one result.
Like in this example:
SQL>
Select LOC from dept where DEPTNO = (select DEPTNO from emp where
JOB='MANAGER');
Gives ERROR ORA-01427: single-row subquery returns more than one row
Instead use
SQL>
Select LOC from dept where DEPTNO in (select DEPTNO from emp
where JOB='MANAGER');
1) Sometimes = also used as comparison operator in case of joins which IN doesn't.
2) You can pass multiple values in the IN block which you can't do with =. For example,
SELECT * FROM [Products] where ProductID IN((select max(ProductID) from Products),
(select min(ProductID) from Products))
would work and provide you expected number of rows.However,
SELECT * FROM [Products] where ProductID = (select max(ProductID) from Products)
and ProductID =(select min(ProductID) from Products)
will provide you 'no result'. That means, in case subquery supposed to return multiple number of rows , in that case '=' isn't useful.