How to select newest record from two tables using SQL?
"select * from Table1,Table2 WHERE Date=(SELECT MAX(Date) FROM Table1,Table2)"
----------- -------------
| table1 | | table2 |
----------- -------------
----------- -------------
| title | | title |
----------- -------------
| text | | text |
----------- -------------
| date | | date |
----------- -------------
This will do it:
SELECT TOP 1 * FROM
(
SELECT * FROM Table_1
UNION ALL
SELECT * FROM Table_2
)
AS ALL_RECORDS
ORDER BY Date DESC
Try something like:
with tmp(title, text, date) as
(
select title, text, date from table1
union
select title, text, date from table2
)
select top 1 * from tmp
order by date desc
This should solve your problem.
SELECT * FTOM Table1, Tble2... creates a cross join (cartesian product of two sets of records) so ther will be multiple records with the same date. You have to specify more criteria to get only one record, and probably use some join.
If you want to choose one record from two tables, where for example Table1 has the newer record than Table2, I think it will be good idea to use union, e.g.
SELECT col1, col2, col3, col4, ..., coln max(Date) FROM (
SELECT * FROM Table1 UNION
SELECT * FROM Table2
) GROUP BY col1, col2, col3, col4, ..., coln
ORDER BY Date;
Related
Below are my table structures. I want to keep only one row inside TABLE2 for maximum date and hour.
TABLE1 :
--------------------------------------
col1 | col2 | col3 | date | hour |
--------------------------------------
TABLE2 :
-----------------
date | hour |
-----------------
Condition :
Insert into TABLE2 from TABLE1 only when there is no data in TABLE2.
Description :
Extract the max(date) and for that max date extract the max(hour) from TABLE1.
And the only condition here is insert the above data into TABLE2 only when there is no row in TABLE2.
How can I achieve this in Snowflake SQL ?
I would do this as:
insert into table2 (date, hour)
select mydate, hour
from table1
where not exists (select 1 from table2)
order by mydate desc, hour desc
limit 1;
You can use a strategy like this:
insert into table2
with rowcount as (select count(1) cnt from table2)
select mydate, hour from table1
join rowcount
where rowcount.cnt = 0
order by mydate desc, hour desc
limit 1;
I have a select query that returns 30+ fields and I found out that there are some double records that differ to exactly one field. The problem look like:
select t1.field1, t2.field2
from table1 t1, table2 t2
where t1.primary_key = t2.primary_key
group by t1.field1, t2.field2;
(don't mind the join, it is cross checked and it works fine)
+----+-------+----------+
| id | field1| field2 |
+----+-------+----------+
| 1 |(null) | 20 |
| 2 |SValue | 20 |
In the first the field is null and in the second the field contains a string. I completely want to remove the null record.
I tried to select max(t1.field1) and select nvl(t1.field1) but nothing changed.
I also tried to select max(t1.field1) over (partition by t2.field2) but the result was (despite the group by) exactly the same record twice, like:
+----+-------+----------+
| id | field1| field2 |
+----+-------+----------+
| 1 |SValue | 20 |
| 2 |SValue | 20 |
Any suggestion? Thanks in advance
select
field1, field2
from (
select
field2,
field1,
rank () over (partition by field2 order by field1 desc nulls last) as fld1_rank,
coalesce (field1, max (field1) over (partition by field2 order by field1 desc nulls last)) as field1_find,
count (*) over (partition by field2) as entries_with_field2
from (
with
t1 as (
select 't1f1a' as field1, 'pk1' as primary_key from dual
union all select to_char(null) as field1, '1' as primary_key from dual
union all select 'SValue' as field1, '2' as primary_key from dual
),
t2 as (
select 1111 as field2, 'pk1' as primary_key from dual
union all select 20 as field2, '1' as primary_key from dual
union all select 20 as field2, '2' as primary_key from dual
)
select *
from
t1 join t2 using (primary_key)
) baseresult
group by
field1, field2
) ranked
where
field1 is not null or
entries_with_field2 = 1
;
I want to get a record having null if the id has only one record and select not null value when the id has more than one record
Below is example sample.
Id Field1 Field2
1 Null 34
1 Yes 52
2 Null 56
3 No 46
and output
Id Field1 Field2
1 Yes 52
2 Null 56
3 No 46
How it can be done using sql query?
Use the below query for 2008+ versions of sql server.
;with cte_1
As
( select *, count(1) over (partition by id order by id) Cnt
From YourTable)
Select Id,Field1,Field2
From Cte_1
Where Field1 is null and Cnt=1
UNION
Select Id,Field1,Field2
From YourTable
Where field1 is not null
Sample output :
Use the below query for 2005 version.
SELECT t.Id,Field1,Field2
FROM #T t
JOIN (select ID, count(ID) CntId
From #t
GROUP BY ID
HAVING COUNT(ID)=1)t1 on t.ID=t1.ID
WHERE t.Field1 is null
UNION
SELECT Id,Field1,Field2
FROM #T
WHERE Field1 is NOT NULL
ORDER BY ID
Sample output :
It sounds like you can only have one or two rows per group and one of them must have the null. Using those assumptions you can get away with a simple query.
select
Id,
min(Field1) as Field1,
coalesce(min(case when Field1 is not null then Field2 end), min(Field2)) as Field2
from T
group by Id
It also makes a minor assumption that Field2 isn't nullable. Actually it's a little more subtle than that but there's a workaround if you need it.
A solution using exists and a subquery is another option:
select * from T t1
where Field is not null or not exists (
select 1 from T t2
where t2.Id = t1.Id and t2.Field is not null
)
Use this code:
Select Distinct ID,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field1,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field2
From Table1 as Tbl1
Result:
ID Field1 Field2
----------- ---------- -----------
1 Yes 52
2 NULL 56
3 No 46
(3 row(s) affected)
Also below code get same result:
Select Distinct ID,
(Select Top 1 Field1 From Table1 Where ID=Tbl1.ID Order By Field1 Desc) as Field1,
(Select Top 1 Field2 From Table1 Where ID=Tbl1.ID Order BY field1 Desc) as Field2
From Table1 as Tbl1
Suppose we have a query
SELECT * FROM my_table ORDER BY id
which results in
id | title
-----------
1 | 'ABC'
2 | 'DEF'
3 | 'GHI'
How could I modify given select statement to have each row duplicated in the result set like this:
id | title
-----------
1 | 'ABC'
1 | 'ABC'
2 | 'DEF'
2 | 'DEF'
3 | 'GHI'
3 | 'GHI'
Try this...
SELECT * FROM my_table
UNION ALL
SELECT * FROM my_table
ORDER BY id
You can use union all, but I like using cross join:
select *
from MyTable cross join
(select 1 from dual union all select 2 from dual) n
order by id;
The reason I like the cross join is in the case where MyTable is really some complicated subquery. Although the query optimizer might evaluate it only once, you can't really depend on that fact. So the performance should be better in this case.
You could cross join to a row generator, the numeric value indicates how many duplicates per original you want.
select *
from my_table
cross join
(select null
from dual
connect by level <= 2)
order by id
I'm using this query to find duplicate values in a table:
select col1,
count(col1)
from table1
group by col1
having count (col1) > 1
order by 2 desc;
But also I want to add another column from the same table, like this:
select col1,
col2,
count(col1)
from table1
group by col1
having count (col1) > 1
order by 2 desc;
I get an ORA-00979 error with that second query
How can I add another column in my search?
Your query should be
SELECT * FROM (
select col1,
col2,
count(col1) over (partition by col1) col1_cnt
from table1
)
WHERE col1_cnt > 1
order by 2 desc;
Presumably you want to get col2 for each duplicate of col1 that turns up. You can't really do that in a single query^. Instead, what you need to do is get your list of duplicates, then use that to retrieve any other associated values:
select col1, col2
from table1
where col1 in (select col1
from table1
group by col1
having count (col1) > 1)
order by col2 desc
^ Okay, you can, by using analytic functions, as #rs. demonstrated. For this scenario, I suspect that the nested query will be more efficient, but both should give you the same results.
Based on comments, it seems like you're not clear on why you can't just add the second column. Assume you have sample data that looks like this:
Col1 | Col2
-----+-----
1 | A
1 | B
2 | C
2 | D
3 | E
If you run
select Col1, count(*) as cnt
from table1
group by Col1
having count(*) > 1
then your results will be:
Col1 | Cnt
-----+-----
1 | 2
2 | 2
You can't just add Col2 to this query without adding it to the group by clause because the database will have no way of knowing which value you actually want (i.e. for Col1=1 should the DB return 'A' or 'B'?). If you add Col2 to the group by clause, you get the following:
select Col1, Col2, count(*) as cnt
from table1
group by Col1, Col2
having count(*) > 1
Col1 | Col2 | Cnt
-----+------+----
[no results]
This is because the count is for each combination of Col1 and Col2 (each of which are unique).
Finally, by using either a nested query (as in my answer) or an analytic function (as in #rs.'s answer), you'll get the following result (query changed slightly to return the count):
select t1.col1, t1.col2, cnt
from table1 t1
join (select col1, count(*) as cnt
from table1
group by col1
having count (col1) > 1) t2
on table1.col1 = t2.col1
Col1 | Col2 | Cnt
-----+------+----
1 | A | 2
1 | B | 2
2 | C | 2
2 | D | 2
You should list all selected columns in the group by clause as well.
select col1,
col2,
count(col1)
from table1
group by col1, col2
having count (col1) > 1
order by 2 desc;
Cause of Error
You tried to execute an SQL SELECT statement that included a GROUP BY
function (ie: SQL MIN Function, SQL MAX Function, SQL SUM Function,
SQL COUNT Function) and an expression in the SELECT list that was not
in the SQL GROUP BY clause.
select col1,
col2,
count(col1)
from table1
group by col1,col2
having count (col1) > 1
order by 2 desc;