SQL-Sum Values until reach a specific value in another column - sql

I have the following 2 table:
Col1|Col2|Col3
Val1 T1
Val2 T2
Col1|Col2|Col3|Col4
Val1 test 1
Val1 test 2
Val1 T1 3
Val2 test 1
Val2 T2 2
I need to update the values for Col3 of Table 1 with the summation of Col3 of table 2 until Col2 of Table 2 reaches the value from Col2 of Table 1. So, Table 1 should look like this:
Col1|Col2|Col3
Val1 T1 6
Val2 T2 3
So, it adds up 1+2+3 = 6 for T1 and 1+2 = 3 for T2.
Basically, the Col1 for both tables will be the key. I am using MSSQL2008 server. I tried to do this with Cursor but no luck so far.
Please note, the order by column in Table2 is a Date column (Column4). It is ordered by Desc.

You can get this by GROUP BY:
CREATE TABLE #Table1(Col1 VARCHAR(10),Col2 VARCHAR(10),Col3 INT)
CREATE TABLE #Table2(Col1 VARCHAR(10),Col2 VARCHAR(10),Col3 INT,Col4 DATETIME)
INSERT INTO #Table1 VALUES('Val1','T1',0)
INSERT INTO #Table1 VALUES('Val2','T2',0)
INSERT INTO #Table2 VALUES('Val1','test',1,GETDATE())
INSERT INTO #Table2 VALUES('Val1','test',2,GETDATE()-1)
INSERT INTO #Table2 VALUES('Val1','T1',3,GETDATE()-2)
INSERT INTO #Table2 VALUES('Val1','test',4,GETDATE()-3)
INSERT INTO #Table2 VALUES('Val2','test',1,GETDATE())
INSERT INTO #Table2 VALUES('Val2','T2',2,GETDATE()-1)
UPDATE T1
SET T1.Col3 = T2.SummationValue
FROM #Table1 T1
JOIN (
SELECT T2.Col1,T2.Col2,SUM(T2.Col3) OVER(PARTITION BY T2.Col1 ORDER BY Col4 DESC)SummationValue
FROM #Table2 T2
JOIN #Table1 T1 ON T2.Col1 = T1.Col1
)T2
ON T1.Col1 = T2.Col1 AND T1.Col2 = T2.Col2
SELECT * FROM #Table1
DROP TABLE #Table1
DROP TABLE #Table2
OutPut:
Col1 Col2 Col3
Val1 T1 6
Val2 T2 3
SQL Fiddle

This is a bit tricky. You can get the cutoff point using a correlated subquery:
update t1
set col3 = t2.sum_col3
from t1 join
(select t2.col1, sum(t2.col3) as sum_col3
from t2
where t2.t4 >= (select tt2.t4
from t2 tt2 join
t1 tt1
on tt2.col1 = tt1.col1 and
tt2.col2 = tt1.col2
)
group by t2.col1
) t2
on t2.col1 = t1.col1;
Alternatively, you can use window functions (but not a cumulative sum):
update t1
set col3 = t2.sum_col3
from t1 join
(select t2.col1,
sum(t2.col3) as sum_col3
from (select t2.col1,
min(case when tt2.col1 = tt1.col2 then tt2.col4 end) over (partition by tt2.col1) as col4_match
from t2 tt2 join
t1 tt1
on tt2.col1 = tt1.col1
) t2
where col4 >= col4_match
group by t2.col1
) t2
on t2.col1 = t1.col1

Related

inserting into a table records from another table with a condition

Let's say I have two tables t1 and t2.
t1 has two integer cols col1 (primary) and col2
t2 has two cols a foreign key of t1.col1 and t2.col2
I want to do the following
Retrieve only the records where t1.col2 is unique OR if t1.col2 is duplicate only those if t2.col2 is not null.
Insert the above records into another summary table, let's say t3
This is what I tried:
insert into t3 (col1,col2)
select col1, col2
from t1
where t.col1 in (select A.col1 from t1 as A
group by 1
having count(*) > 1
union
select col1, col2
from t1, t2
where t.col1 in (select A.col1 from t1 as A
group by 1
having count(*) > 1
and t2.col2 is not null;
While the 'union qry' works on its own, the insert is not happening.
Any ideas or any other efficient way to achieve this please
You can select the records you want using:
select t1.*
from (select t1.*, count(*) over (partition by col2) as cnt
from t1
) t1
where cnt = 1 or
exists (select 1 from t2.col1 = t1.col1 and t2.col2 is null);
The rest is just an insert.

How to spread a table into another one

We have a legacy table
create table table1 (col1 int);
insert into table1 values(1);
insert into table1 values(2);
insert into table1 values(3);
SELECT * FROM table1;
1
2
3
now it gets a new column
alter table table1 add column col2 int;
alter table table1 ADD CONSTRAINT unique1 UNIQUE (col2);
SELECT * FROM table1;
1;null
2;null
3;null
then we have another table
create table table2 (col1 int);
insert into table2 values(7);
insert into table2 values(8);
insert into table2 values(9);
SELECT * FROM table2;
7
8
9
now we want to spread the values of table 2 into table1.col2
UPDATE table1 up
SET col2 = (SELECT col1
FROM table2 t2
WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.col2=t2.col1)
LIMIT 1);
but the update statement does not see the already updated rows
ERROR: duplicate key value violates unique constraint "unique1"
Any ideas how to do that? It would be ok, if table1 remains with some rows col2=null if table2 has less rows than table1
This seems much easier with a join:
with t2 as (
select t2.*, row_number() over (order by col1) as seqnum
from table2 t2
)
update table1 t1
set col2 = t2.col1
from t2
where t1.col1 = t2.seqnum;
If col1 in table1 is not strictly sequential, you can still do this:
with t2 as (
select t2.*, row_number() over (order by col1) as seqnum
from table2 t2
),
t1 as (
select t1.*, row_number() over (order by col1) as seqnum
from table1 t1
)
update table1 toupdate
set col2 = t2.col1
from t1 join
t2
on t1.seqnum = t2.seqnum
where toupdate.col1 = t1.col1;
i think i found a solution
WITH rownumbers AS (
SELECT col1, row_number() over (partition by 1 ORDER BY col1) FROM table1
)
UPDATE table1 up SET col2 =
(SELECT col1 FROM table2 t2 WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.col2=t2.col1)
LIMIT 1 OFFSET (
SELECT row_number-1 FROM rownumbers WHERE col1=up.col1
)
)
any cons about it?

How to get the following join query

How to get the following join
input:
table1: table2:
col1 Col1 col2 col3
A A 1 2
B B 4 5
C
output:
col1 col2 col3
A 1 2
B 4 5
c - -
SELECT t1.col1, t2.col2, t2.col3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.col1=t2.col1
;
You can do this using full outer join:
select coalesce(t1.col1, t2.col1), t2.col2, t2.col3
from table1 t1 full outer join
table2 t2
on t1.col1 = t2.col1;
This returns all rows from both tables, even those that don't match (it is a left and right outer join at the same time).
You can also do this using union all and aggregation:
select col1, max(col2) as col2, max(col3) as col3
from ((select col1, NULL as col2, NULL as col3
from table1
) union all
(select col1, col2, col3
from table2
)
) t
group by col1;
select t1.col1, t2.col2, t2.col3
from table1 t1
left outer join table2 t2
on t1.col1 = t2.col1
Maybe something like this if you wan't the '-'
SELECT t1.col1, coalesce(t2.col2,'-') as col2, coalesce(t2.col3,'-') as col3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.col1=t2.col1
See my sqlfiddle
create table table1(
col1 char(1)
);
insert into table1 values('A');
insert into table1 values('B');
insert into table1 values('C');
create table table2(
col1 char(1),
col2 int,
col3 int
);
insert into table2 values('A',1,2);
insert into table2 values('B',4,5);
select
t1.col1,
coalesce(t2.col2,'-'),
coalesce(t2.col3,'-')
from
table1 t1
left join table2 t2 on t1.col1=t2.col1
;
http://sqlfiddle.com/#!2/bc768/2
You need to do an outer join
SELECT *
FROM table1 t1,
table2 t2
WHERE t1.col1 = t2.col1(+)

Using the names of columns stored within fields to retrieve data from a different table

I was wondering if there exists code to accomplish the following in SQL-Server 2008?
Table 1:
id column name
-------------------
1 col1
2 col2
3 col3
4 col2
Table 2:
col1 col2 col3
--------------------
a b c
Result Table:
id data
--------------------
1 a
2 b
3 c
4 b
Thanks in advance, I really have no idea how to do this.
You can use UNPIVOT table2 to access the data from the columns:
select t1.id, t2.value
from table1 t1
left join
(
select value, col
from table2
unpivot
(
value
for col in (col1, col2, col3)
) u
) t2
on t1.name = t2.col
see SQL Fiddle with Demo
Or you can use a UNION ALL to access the data in table2:
select t1.id, t2.value
from table1 t1
left join
(
select col1 value, 'col1' col
from table2
union all
select col2 value, 'col2' col
from table2
union all
select col3 value, 'col3' col
from table2
) t2
on t1.name = t2.col
see SQL Fiddle with Demo
I dont see how you do it withou a column connection them:
Table1:
ID
ColumnName
Table2:
Table1ID
Letter
Select table1.id, table2.Letter
from table1
inner join table2 on table1.ID = table2.Table1ID
You can do this with a case statement and cross join:
select t1.id,
(case when t1.columnname = 'col1' then t2.col1
when t1.columnname = 'col2' then t2.col2
when t1.columnname = 'col3' then t2.col3
end) as data
from table1 t1 cross join
table2 t2

How to check duplicate value

I have two tables:
Table Tab1 ( Col1, Col2 )
Table Tab2 ( Col1, Col2 )
I want to check in the table Tab2 Col2 is there any same value with the table Tab1 in column Col2.
How to do that?
Using EXISTS
SELECT t2.col2
FROM TABLE2 t2
WHERE EXISTS (SELECT NULL
FROM TABLE1 t1
WHERE t1.col2 = t2.col2)
Using IN
SELECT t2.col2
FROM TABLE2 t2
WHERE t2.col2 IN (SELECT t1.col2
FROM TABLE1 t1)
Using JOIN:
SELECT DISTINCT t2.col2
FROM TABLE2 t2
JOIN TABLE1 t1 ON t1.col2 = t2.col2