How to use a variable as a select statement and then sum multiple values in a variable? - sql

I have multiple rows with the following columns:
col1
col2
col3
col4
I want to say if rows where col3 equals col2 of other rows where col1 equals 'a111', then sum col4 of the rows where col3 equals col2 of other rows where col1 equals 'a111', and then rename the sum column to "Total".
Example table with the four columns and four rows:
col1 col2 col3 col4
---- ---- ---- ----
a222 a333 4444
a111 a333
a555 a444 1111
a111 a444
I've tried the following but it does not work.
Declare
var1 = Select col2 from table1 where col1='a111';
var2 = Select col3 from table1 where col3=var1;
var3 = Select col4 from table1 where col3=var1;
Begin
If var2=var1
Then Select SUM(var3) As "Total";
End
Expected result is:
Total
5555
I do not have the strongest of knowledge in programming overall or Oracle. Please ask any questions and I will do my best to answer.

Your logic is convoluted and hard to follow without an example of the data you have and an example of the data you want.. but translating your pseudocode into sql gives:
Declare
var1 = Select col2 from table1 where col1='[table2.col2 value]';
Called "find" in my query
var2 = Select col3 from table1 where col3=var1;
var3 = Select col4 from table1 where col3=var1;
Achieved by joining the table back to the "find"
Begin
If var2=var1
Then Select SUM(var3) As "Total";
End
Achieved with a sum of var3 on only rows where var1=var2, in "ifpart"
SELECT SUM(var3) FROM
(
SELECT alsot1.col3 as var2, alsot1.col4 as var3
FROM
table1 alsot1
INNER JOIN
(
SELECT t1.col2 as var1
FROM table1 t1 INNER JOIN table2 t2 ON t1.col1 = t2.col2
) find
ON find.var1 = alsot1.col3
) ifpart
WHERE
var1 = var2
This could be simplified, but I present it like this because it matches your understanding of the problem. The query optimizer will rewrite it anyway when the time comes to run it so it only pays to start messing with how it's done if performance is poor
By the way, you clearly said that two tables join via a common named col2 but you then in your pseudocode said the tables join on col1=col2. I followed your pseudocode

This sounds like something that hierarchical queries could handle. E.g. something like:
WITH your_table AS (SELECT NULL col1, 'a222' col2, 'a333' col3, 4444 col4 FROM dual UNION ALL
SELECT 'a111' col1, 'a333' col2, NULL col3, NULL col4 FROM dual UNION ALL
SELECT NULL col1, 'a555' col2, 'a444' col3, 1111 col4 FROM dual UNION ALL
SELECT 'a111' col1, 'a444' col2, NULL col3, NULL col4 FROM dual UNION ALL
SELECT 'a666' col1, 'a888' col2, NULL col3, NULL col4 FROM dual UNION ALL
SELECT NULL col1, 'a777' col2, 'a888' col3, 7777 col4 FROM dual)
SELECT col1,
SUM(col4) col4_total
FROM (SELECT connect_by_root(col1) col1,
col4
FROM your_table
CONNECT BY col3 = PRIOR col2
START WITH col1 IS NOT NULL) -- start with col1 = 'a111')
GROUP BY col1;
COL1 COL4_TOTAL
---- ----------
a666 7777
a111 5555

Nevermind. I believe I've determined the answer myself. I over complicated what I wanted. Thank you anyway.
Answer:
Select Sum(col4) as "Total" from table1 where col3 in (Select col2 from table1 where col1='a111')

Related

How to create a select query with multiple columns querying a single column with multiple conditions

I want to get a list of results from my db2 database querying a table having multiple conditions on a same column. Here is an example scenario:
Table1:
col1, col2, col3, col4, col5
sample, user, adam, ggg, hdh
sample, source, online, urt, loe
random, user, henr, uuu, kkk
crew, user, mike, nhg, kik
crew, dummy, nothing, irr, wer
ment, maker, hts, ret, opp
I am trying to write a select query that will list me the details in the following manner:
col1, col2, col3, col4
sample, adam, online, ggg
random, henr, , uuu
crew, mike, nothing, irr
ment, , , ret
So when col2 has the value user I want the corresponding col3 value as one of the column to my select statement. And, when col2 has value in source or dummy, I want the corresponding col3 value as another column to my select statement. In this way, I can finally have a list with 4 columns which gets me the unique combination of details that I need.
I have a draft sql query of this kind. I am not sure how to refactor this to get two output columns querying a single column.
select col1 , col3 as col2, col3 as col3, col4 from Table1
where col2='user' or col2 in ('source','dummy')
If I do this, I am getting the output in this manner
col1, col2, col3, col4
sample, adam, adam, ggg
sample, online, online, ggg
random, henr, henr, uuu
crew, mike, mike, irr
crew, nothing, nothing, irr
I think you want this:
select col1,
max(case when col2 = 'user' then col3 end) as col2,
max(case when col2 in ('source', 'dummy') then col3 end) as col3,
max(col4) as col4
from t
group by col1;
I'm not sure why you've mentioned col5 in your input as it's not referred to in your output? It just muddies the water ;-)
Anyway, here's the SQL you need to get the results you're after based on the input/output example:
WITH
USER AS
( SELECT COL1
, COL3 AS COLA
, COL4 AS COLB
FROM TABLE1
WHERE COL2 = 'USER'
)
, SOURCE AS
( SELECT COL1
, COL2 AS COLC
, COL3 AS COLD
, COL4 AS COLE
FROM TABLE1
WHERE COL2 IN ( 'SOURCE'
, 'DUMMY'
)
)
SELECT U.COL1
, U.COLA AS COL2
, COALESCE(S.COLD,'') AS COL3
, COALESCE
( CASE
WHEN S.COLC = 'DUMMY'
THEN S.COLE
ELSE U.COLB
END
, U.COLB
) AS COL4
FROM USER U
LEFT OUTER JOIN SOURCE S
ON S.COL1 = U.COL1
WITH UR FOR FETCH ONLY;
may be you need to write select col1 , col3 as col2, col2 as col3, col4 from Table1... and then add respective conditions , as in your case. second and third columns in output are same because you are selecting col3 in both

Oracle SQL - Join 2 table columns in 1 row

I have 2 SQL's and the result come fine. They are no relation between those 2 queries but I want to see all the rows in single column.
e.g.
Select col1,col2,sum(col3) as col3 from table a
select col4,col5 from table b
I would like the result to be
col1 col2 col3 col4 col5
If there is no equivalent row for either table a or table b replace with zeroes.
Could some one help me with this. thanks.
Since, you didn't provided any information like table structure or data inside each tables. You can cross join both tables.
select t.col1,t.col2,t.col3,t1.col1,t1.col2 from tab1 t,tab2 t1;
SQLFiddle
In both select statements add column based on rownum or row_number() and then full join results using this column:
select nvl(col1, 0) col1, nvl(col2, 0) col2, nvl(col3, 0) col3,
nvl(col4, 0) col4, nvl(col5, 0) col5
from
(select rownum rn, col1, col2, col3 from (
select col1, col2, sum(col3) col3 from tableA group by col1, col2)) a
full join (select rownum rn, col4, col5 from tableB) b using (rn)
SQLFiddle demo
I guess a UNION could be a pragmatic solution since the 2 queries are not related. They are just 2 data sets that should be retrieved in one statement:
Select col1,col2,sum(col3) as col3 from table a
UNION
select col4,col5, to_number(null) col6 from table b
Be aware of col6 in the example. SQL insists on retrieving an equal set of columns in a UNION statement. It is a good practice to retrieve columns with exactly the same datatype. Since the sum(col3) will yield a number datatype column, col6 should too.
The outcome of col4 and col5 will be shown in col1 and col2.

oracle sql query finding rows with multiple values in 3rd column matching columns 1 and 2

I have a dataset with about a million rows in and Oracle 11 db.
I'd like to find rows where col1 and col2 match but have different values in col3.
I'm not sure how to do this well though i can certainly write a query that never seems to finish:
select col1,col2,col3
from table tab1
where exists
(select 1
from table tab2
where tab1.col1 = tab2.col1
and tab1.col2 = tab2.col2
and tab1.col3 != tab2.col3);
I ran this and after an hour gave up waiting - I need to analyze the problems and present it to some people for figuring out how to move forward.
Thanks in any case,
Jeff
A query like this will indicate which rows having the same col1, col2 have differing values in col3:
SELECT col1, col2
FROM x
GROUP BY col1, col2
HAVING MIN(col3) <> MAX(col3)
To see how many of this col1, col2 pairs are affected:
SELECT COUNT(*)
FROM (SELECT col1, col2
FROM x
GROUP BY col1, col2
HAVING MIN(col3) <> MAX(col3)
)
You may also wish to know how many duplicates there are (ie having col1, col2, col3 the same:
SELECT col1, col2, col3
FROM x
GROUP BY col1, col2, col3
HAVING COUNT(*) > 1
Did you mean something like this?
select col1,col2,col3
from table tab1
where col1 = col2
and col1 <> col3

Join multiple rows give one distinct row

My SQL statement returns the following
SQLID Col1 Col2 Col3
14945 NULL NULL sdf
14945 NULL xyz NULL
14945 abc NULL NULL
where as I would like it to return
SQLID Col1 Col2 Col3
14945 abc xyz sdf
Please help.
The schema is such that I have a table which contains SQLID's. And a second table which contains SQLID's as the FK to first table and the col1, col2 and col3. Currently I am just doing a join on SQLId
Select
t1.SQLID, t2.Col1, t2.col2, t2.col3
from
Table1 t1
join
table2 t2 on t1.SQLId = t2.SQLid
EDIT: if Col1, Col2, Col3 are DATETIME datatype (as per following comment)
You can use;
SELECT SQLID, MAX(ISNULL(Col1,0)) AS Col1,
MAX(ISNULL(Col2,0)) AS Col2, MAX(ISNULL(Col3,0)) AS Col3
FROM YourTable
GROUP By SQLID

Select a dummy column with a dummy value in SQL?

I have a table with the following
Table1
col1 col2
------------
1 A
2 B
3 C
0 D
Result
col1 col2 col3
------------------
0 D ABC
I am not sure how to go about writing the query , col1 and col2 can be selected by this
select col1, col2 from Table1 where col1 = 0;
How should I go about adding a col3 with value ABC.
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
If you meant just ABC as simple value, answer above is the one that works fine.
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
Something like this may work:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though