Create SQL query with given Conditions - sql

I have an SQL query of the form
SELECT
SUM(some_col)
FROM
(some table name here)
WHERE
some_common_condition AND
some_condition1 AND
some_condition2 AND
column_A = 'X'
GROUP BY
column_A;
column_A has some values for which I currently run this query for. Now for each of the unique values of column_A there are some associated conditions.
For eg, if column_A has 3 unique values X,Y,Z, all three have some_common_condition and some specific conditions associated with it,i.e,
for X -> some_condition1 AND some_condition2
for Y -> some_condition3 AND some_condition4
for Z -> some_condition5 AND some_condition6
I want to club all these conditions and make 1 single SQL query,which gives me corresponding SUM(some_col) for all the values of column_A (i.e. X,Y,Z).
Now one obvious way is
SELECT *
FROM(SELECT SUM(some_col) AS val_X FROM (table) WHERE conditions_for_X UNION ALL
SELECT SUM(some_col) AS val_Y FROM (table) WHERE conditions_for_X UNION ALL
SELECT SUM(some_col) AS val_Z FROM (table) WHERE conditions_for_X -- UNION ALL a.s.o.
)
I want to know a solution which only hits the database once. Above query uses 3 select statements, hitting the DB three times, which is bad for scalability reasons.

Does this answer your question?
SELECT SUM(some_col) FROM ...
WHERE
(column_A = 'X' AND some_condition1 AND some_condition2) OR
(column_A = 'Y' AND some_condition3 AND some_condition4) OR
(column_A = 'Z' AND some_condition5 AND some_condition6)
GROUP BY column_A;

Related

Use a select query result in an other query

Could please someone explain, how to use a result from a SELECT (1st select result)
Then use that result (1st select result) on a second query VALUES clause
there is an example (on Microsoft SQL Server) :
--1st query, select all DB1.client.name
select Name from DB1.client
--the result of that query is : 1st select result VALUES : ana,boby, ..., micky
--2nd query, compare DB1.client.name (1st select result) with DB2.client.name
--and get back who doesn't exist on second table
select v.Name
from (values
**(There i want use the result of my first query)**
) as v(Name)
where not exists (select *
from DB2.client c
where c.Name = v.Name);
--the result is ana, ..., micky
"..." mean some other results
i want compare first and second database to retrieve values which aren't in both databases
If you can, I recommend sub-query :
select Name
from DB1.client
where Name not in not exists (select name from DB2.client)
If you want reuse a query (not the result), see #Thkas answer.
It isn't possible to reuse the result in SQL Server, because SQL Server release the memory when the result is read. The trick is to insert the query's result in a temporary table, then you read this temporary table as many times as necessary :
--Insert into temporary table
insert into #tmpResult
select Name from DB1.client
--First read
select Name from #tmpResult
--Second read from sub-query
select Name
from #tmpResult
where Name not in not exists (select name from DB2.client)
According to your sample code I understood something like this. You can add two tables and do with WHERE the check you want.
select a.Name,b.Name
from DB1.client,
DB2.client as b
where a.Name != b.Name;
Also if you want to take as a result set from the first query:
Here I created a subquery which takes the results from the first query. You can correct me for columns.
with temp as (
select Name
from DB1.client
)select a.Name,b.Name
from temp as a ,
DB2.client as b
where a.Name != b.Name;

hive scan and select in one query

I have a hive table, say emp_details(name, dept).
In this table, I need to check if any records exists with dept = ‘a’ then select those records. If no such record is found then only I will choose records with dept = ‘b’. The source data has either 'a' or 'b' as dept value and my result set will contain either 'a' or 'b' not both.
The problem is I am bound to use only one hive query for this issue.
Calculate a_exist flag and use it for filtering:
select name, dept
from
(select name,
dept,
(count(case when dept='a' then 1 end) over()>0) as a_exist
from test_a
)a
where (a_exist and dept='a') --only a if exists
or ((NOT a_exist)and dept='b') --return b if a not exists
;

SELECT VALUES in Teradata

I know that it's possible in other SQL flavors (T-SQL) to "select" provided data without a table. Like:
SELECT *
FROM (VALUES (1,2), (3,4)) tbl
How can I do this using Teradata?
Teradata has strange syntax for this:
select t.*
from (select * from (select 1 as a, 2 as b) x
union all
select * from (select 3 as a, 4 as b) x
) t;
I don't have access to a TD system to test, but you might be able to remove one of the nested SELECTs from the answer above:
select x.*
from (
select 1 as a, 2 as b
union all
select 3 as a, 4 as b
) x
If you need to generate some random rows, you can always do a SELECT from a system table, like sys_calendar.calendar:
SELECT 1, 2
FROM sys_calendar.calendar
SAMPLE 10;
Updated example:
SELECT TOP 1000 -- Limit to 1000 rows (you can use SAMPLE too)
ROW_NUMBER() OVER() MyNum, -- Sequential numbering
MyNum MOD 7, -- Modulo operator
RANDOM(1,1000), -- Random number between 1,1000
HASHROW(MyNum) -- Rowhash value of given column(s)
FROM sys_calendar.calendar; -- Use as table to source rows
A couple notes:
make sure you pick a system table that will always be present and have rows
if you need more rows than are available in the source table, do a UNION to get more rows
you can always easily create a one-column table and populate it to whatever number of rows you want by INSERT/SELECT into it:
CREATE DummyTable (c1 INT); -- Create table
INSERT INTO DummyTable(1); -- Seed table
INSERT INTO DummyTable SELECT * FROM DummyTable; -- Run this to duplicate rows as many times are you want
Then use this table to create whatever resultset you want, similar to the query above with sys_calendar.calendar.
I don't have a TD system to test so you might get syntax errors...but that should give you a basic idea.
I am a bit late to this thread, but recently got the same error.
I solved this by simply using
select distinct 1 as a, 2 as b from DBC.tables
union all
select distinct 3 as a, 4 as b from DBC.tables
Here, DBC.tables is a DB backend table with a few rows only. So, the query runs fast as well

Firebird SQL challenge - return one row that has the data when select returned two rows

I have a quite unique need to make select always return one row
My SQL:
select * from table1 Where (table1.pk = :p1) or (table1.fk1 = :p1)
The above SQL always has two cases for return:
1- my Select return two records:
The only different is one of the records has data while the other has only the ID filled with data while the rest of its fields are null. I need in this case to return only the one that has data in other fields.
2- my Select return one record
In this case the record returned has only the ID field filled with data while the rest of the fields are null however this is what I want and no need for any further processing.
Please advise if is it possible to do that in one plain Select SQL. I can not use stored procedure.
You can use the first clause of the select statement to get only 1 row.
Given your specific conditions, you can order the result set descending by the rest of the fields to be sure the null row is selected only in case there's no data row (null goes first in firebird 2.5, but AFAIK this changed somewhere in the last versions, so check your specific version before applying this).
Your final query will look like this:
select first 1 *
from table1
where (table1.pk = :p1)
or (table1.fk1 = :p1)
order by somecolumn;
somecolumn being the most relevant of the other fields that can contain null values.
you can test this with this statements:
--two rows, one with ID and values and the other with ID and null
with q1 as (
select 1 id, 'data' othercolumn
from rdb$database
union
select 2 id, null othercolumn
from rdb$database
)
select first 1 *
from q1
order by othercolumn nulls last;
--versus:
--onw row with ID and null
with q1 as (
select 2 id, null othercolumn
from rdb$database
)
select first 1 *
from q1
order by othercolumn nulls last;

I am trying to return a certain values in each row which depend on whether different values in that row are already in a different table

I'm still a n00b at SQL and am running into a snag. What I have is an initial selection of certain IDs into a temp table based upon certain conditions:
SELECT DISTINCT ID
INTO #TEMPTABLE
FROM ICC
WHERE ICC_Code = 1 AND ICC_State = 'CA'
Later in the query I SELECT a different and much longer listing of IDs along with other data from other tables. That SELECT is about 20 columns wide and is my result set. What I would like to be able to do is add an extra column to that result set with each value of that column either TRUE or FALSE. If the ID in the row is in #TEMPTABLE the value of the additional column should read TRUE. If not, FALSE. This way the added column will ready TRUE or FALSE on each row, depending on if the ID in each row is in #TEMPTABLE.
The second SELECT would be something like:
SELECT ID,
ColumnA,
ColumnB,
...
NEWCOLUMN
FROM ...
NEWCOLUMN's value for each row would depend on whether the ID in that row returned is in #TEMPTABLE.
Does anyone have any advice here?
Thank you,
Matt
If you left join to the #TEMPTABLE you'll get a NULL where the ID's don't exist
SELECT ID,
ColumnA,
ColumnB,
...
T.ID IS NOT NULL AS NEWCOLUMN -- Gives 1 or 0 or True/false as a bit
FROM ... X
LEFT JOIN #TEMPTABLE T
ON T.ID = X.ID -- DEFINE how the two rows can be related unquiley
You need to LEFT JOIN your results query to #TEMPTABLE ON ID, this will give you the ID if there is one and NULL if there isn't, if you want 1 or 0 this would do it (For SQL Server) ISNULL(#TEMPTABLE.ID,0)<>0.
A few notes on coding for performance:
By definition an ID column is unique so the DISTINCT is redundant and causes unnecisary processing (unless it is an ID from another table)
Why would you store this to a temporary table rather than just using it in the query directly?
You could use a union and a subquery.
Select . . . . , 'TRUE'
From . . .
Where ID in
(Select id FROM #temptable)
UNION
SELECT . . . , 'FALSE'
FROM . . .
WHERE ID NOT in
(Select id FROM #temptable)
So the top part, SELECT ... FROM ... WHERE ID IN (Subquery), does a SELECT if the ID is in your temptable.
The bottom part does a SELECT if the ID is not in the temptable.
The UNION operator joins the two results nicely, since both SELECT statements will return the same number of columns.
To expand on what someone else was saying with Union, just do something like so
SELECT id, TRUE AS myColumn FROM `table1`
UNION
SELECT id, FALSE AS myColumn FROM `table2`