Latest record and sum SQL - sql

I'm looking for solution for this problem.
Table:
i want this output (show latest tier based on maximum transaction id)

You can do :
select *, sum(select sum(t1.poin)
from table t1
where t1.member_id = t.member_id
) as poin,
sum(select sum(t1.freq)
from table t1
where t1.member_id = t.member_id
) as freq
from table t
where trans_id = (select t1.trans_id
from table t1
where t1.member_id = t.member_id
order by t1.trans_id desc
fetch first 1 rows only
);
Most DBMS has support fetch first 1 rows only method.
If, you are working with SQL Server, then you can directly express it as :
select t.member_id, tt.*
from (select *, row_number() over (partition by member_id order by trans_id desc) as seq
from table
) t cross apply (
select sum(t1.poin) as poin, sum(t1.freq) as freq
from table t1
where t1.member_id = t.member_id
) tt
where t.seq = 1;

Related

How to implement a LEFT OUTER JOIN CLAUSE after WITH AS?

Currently trying to figure out how to implement a SQL LEFT OUTER JOIN while using the SQL WITH AS clause. My code breaks down into 3 SELECT statements while using the same table, then using LEFT OUTER JOIN to merge another table on the id.
I need 3 SELECT statements before joining because I need a SELECT statement to grab the needed columns, ROW RANK the time, and set WHERE clause for the ROW RANK.
SELECT *
(
WITH employee AS
(
SELECT id, name, department, code, time, reporttime, scheduled_time
FROM table1 AS a
WHERE department = "END"
),
employe_v2 as
(
SELECT address
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY time desc, reporttime desc, scheduled_time desc) AS row_rank
FROM table1 AS b
)
SELECT *
FROM employee, employee_v2
WHERE row_rank = 1
) t1
LEFT OUTER JOIN
(
SELECT b.id, b.new_code, b.date
FROM table2 AS b
WHERE b.newcode != "A"
) t2
ON t1.id = t2.id
Group BY t1.id, t1.name, t1.department, t1.code, t1.time, t1.reporttime,
t1.scheduled_time, t1.row_rank, t2.id, t2.new_code, t2.date
How I could fix my code?
not sure if group by is needed, i see no aggregation whatsover
but if it's something you need , you can add at the end of final select and ofcourse you have to take care of columns/aggregation in select
nevertheless you can simplify your query as below :
with employee as (
select * from (
select id, name, department, code, time, reporttime, scheduled_time, address
,row_number() over (partition by id order by time desc, reporttime desc, scheduled_time desc) AS row_rank
from table1
) t where row_rank =1
)
select t1.*, b.id, b.new_code, b.date
from employee t1
left join table2 as t2
on t1.id = t2.id
where t2.newcode != "A"

Postgres: how to join closest value from the same table

I have a the following table
CREATE TABLE temp (
id SERIAL,
other_id INTEGER NOT NULL, -- some ForeignKey
date DATE NOT NULL
)
I want to join this table to itself by previous (closest) date item with the same other_id. Something like
SELECT count(*)
FROM temp AS t1
JOIN temp AS t2 ON (t2.other_id = t1.other_id AND t2.date < t1.date)
But t2.date must be closest to t1.date (not any lower date).
Is that possible at all?
You can use a query like the following:
WITH temp_rn AS (
SELECT id, other_id, date,
ROW_NUMBER() OVER (PARTITION BY other_id
ORDER BY date) AS rn
FROM temp
)
SELECT t1.*
FROM temp_rn AS t1
LEFT JOIN temp_rn AS t2 ON t1.other_id = t2.other_id AND t1.rn = t2.rn + 1
The query uses ROW_NUMBER in order to detect the 'previous' row: it is the one having the previous row number within the same other_id slice.
It's not entirely clear what you are after, but something like this might do it:
select count(*)
from temp as t1
join lateral (
select t.other_id, max(t.date)
from temp as t
where t.date < t1.date
and t.other_id = t1.other_id
group by t2.other_id
) as t2 on t2.other_id = t1.other_id;

Randomly Assign Records From One Table to Another

I have two tables.
T1
id,date,item,channel
T2
id,date,item,channel
In T2 the id and date columns are NULL. I want to randomly assign an id and date from T1 to each row in T2. Also, T2 is much smaller than T1.
Any ideas how to do this? I'm on Teradata 13.
I was originally thinking something like this:
sel count(*) from t2 ;
--507
select *
from (sel a.*, RANDOM(1,507) as r1 from t1) a
inner join (sel b.*, RANDOM(1,507) as r1 from t2) b
on a.r1 = b.r1
The problem is I'll need to automatically assign the count of t2 as the upper bound of random.
Assign a ROW_NUMBER based on a RANDOM sort and join on that:
select *
from
(
select dt.*, row_number() over (order by t1.r) as rn
from
(
select t1.*, RANDOM(1,1000000) as r from t1
) as dt
) as a
join
(
select dt.*, row_number() over (order by t1.r) as rn
from
(
select t2.*, RANDOM(1,1000000) as r from t2
) as dt
) as b
on a.rn = b.rn

tsql: alternative to select subquery in join

this is my table layout simplified:
table1: pID (pkey), data
table2: rowID (pkey), pID (fkey), data, date
I want to select some rows from table1 joining one row from table2 per pID for the most recent date for that pID.
I currently do this with the following query:
SELECT * FROM table1 as a
LEFT JOIN table2 AS b ON b.rowID = (SELECT TOP(1) rowID FROM table2 WHERE pID = a.pID ORDER BY date DESC)
This way of working is slow, probabaly because it has to do a subquery on each row of table 1. Is there a way to improve performance on this or do it another way?
You can try something on these lines, use the subquery to get the latest based on the date field (grouping by the pID), then join that with the first table, this way the subquery would not have not have to be executed for each row of Table1 and will result in better performance:
Select *
FROM Table1 a
INNER JOIN
(
SELECT pID, Max(Date) FROM Table2
GROUP BY pID
) b
ON a.pID = b.pID
I have provided the sample SQL for one column using the group by, in case you need additional columns, add them to the GROUP BY clause. Hope this helps.
use the below code, and note that i added the order by Date desc to get the most resent data
select *
from table1 a
inner join table2 b on a.pID=b.pID
where b.rowID in(select top(1) from table2 t where t.pID=a.pID order by Date desc)
I am using the code below in a similar scenaro (I transcripted it to your example)
SELECT b.*
FROM table1 AS a
left outer join (
SELECT a.*
FROM table2 a
inner join (
SELECT a.pID, max(date) as date
FROM table2
WHERE date <= <max_date>
group by pID
) b ON a.pID = b.pID AND a.date = b.date
) b ON a.pID = b.pID
) b on a.pID = b.pID
The only problem with this aproach is that you have to make sure the date's don't reapet for the pID's
You can do this with the row_number() function and a subquery:
SELECT t1.*
FROM table1 t1 LEFT JOIN
(select t2.*, row_number() over (partition by pId order by rowId desc) as seqnum
from table2 t2
) t2
on t1.pId = t2.pId and t2.seqnum = 1;
Use the ROW_NUMBER() function to get a column saying which id of each row in table 2 is the first (As partitioned by the pID, and ordered by the rowDate descending)
Example:
WITH cte AS
(
SELECT
rowID AS t2RowId,
ROW_NUMBER OVER (PARTITION BY pID ORDER BY rowDate DESC) AS rowNum
FROM table2 t2
) -- gets the t2RowIds + a column which says which is the latest for each pID
SELECT t1.*, t2.*
FROM table1 t1
LEFT JOIN
(
table2 t2
JOIN cte ON t2.rowID = cte.t2RowId AND cte.rowNum = 1
) ON t1.pID = t2.pID
This is guaranteed to only return 1 item from table2 per pID, even if multiple items have the same date. You should of course ensure that the date column is indexed in table 2 for quick performance (ideally an index that also covers the PrimaryID of table2)

How to Select master table data and select referance table top one data sql query

i need an sql query which should return the master table entry and its child table entry (the latest one entry only). I used inner join for this. But i its not working fine.
Can anyone give a give me a proper query for this
Thanks in advance
In SQLServer2005+ use option with OUTER APPLY operator
SELECT *
FROM master t1 OUTER APPLY (
SELECT TOP 1 t2.Col1, t2.Col2 ...
FROM child t2
WHERE t1.Id = t2.Id
ORDER BY t2.CreatedDate DESC
) o
OR option with CTE and ROW_NUMBER() ranking function
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY t1.Id ORDER BY t2.CreatedDate DESC) AS rn
FROM master t1 JOIN child t2 ON t1.Id = t2.Id
)
SELECT *
FROM cte
WHERE rn = 1
Try this,
SELECT ID, DATE
(
SELECT M.ID, C.DATE, ROW_NUMBER() OVER(PARTITION BY M.ID ORDER BY C.DATE DESC) RN
FROM MASTER M
JOIN CHILD C
ON C.ID = M.ID
) A
WHERE RN = 1