SQLite Join Tables With Different Primary Key Values - database

I have two tables in SQLITE one table FastData records data at a high rate while the other table SlowData records data at a lower rate. FastData and SlowData share a primary key (PK) that represents time of data capture. As such the two tables could look like:
Fast Data Slow Data
Pk Value1 Pk Value2
2 1 1 1
3 2 4 2
5 3 7 3
6 4
7 5
9 6
I would like to create a Select statement that joins these two tables filling in the SlowData with the previous captured data.
Join Data
Pk Value1 Value2
2 1 1
3 2 1
5 3 2
6 4 2
7 5 3
9 6 3

You may try the following approach which uses row_number to determine the most recent entry as it relates to Pk as the ideal entry for Value2 after performing a left join.
SELECT
Pk,
Value1,
Value2
FROM (
SELECT
f.Pk,
f.Value1,
s.Value2,
ROW_NUMBER() OVER (
PARTITION BY f.Pk, f.Value1
ORDER BY s.Pk DESC
) rn
FROM
fast_data f
LEFT JOIN
slow_data s ON f.Pk >= s.Pk
) t
WHERE rn=1;
Pk
Value1
Value2
2
1
1
3
2
1
5
3
2
6
4
2
7
5
3
9
6
3
View working demo on DB Fiddle

You need a LEFT join of the tables and FIRST_VALUE() window function to pick Value2:
SELECT DISTINCT f.Pk, f.Value1,
FIRST_VALUE(s.Value2) OVER (PARTITION BY f.Pk ORDER BY s.Pk DESC) Value2
FROM FastData f LEFT JOIN SlowData s
ON s.Pk <= f.Pk;
See the demo.

Related

List combination in where clause

Here is the scenerio, I have a input data and a table table1
Input Data Table1
Customer Id Campaign ID CustomerId CampaignID
1 1 4 2
1 2 6 3
2 3 1 1
1 3 5 5
4 2 9 8
4 4
5 5
I want to query table1 such that it return only those values from the where clause which are not present in table1. So the result will be as below
Result
Customer Id Campaign ID
1 2
2 3
1 3
4 4
5 5
So the query should be something like
select CustomerId, CampaignID from Table1
where Customer Id in (Input data for customer id) and CampaignId in (Input data for campaign id)
. I know this query is not right, but can someone please help.
Is there a way to filter the values given in where clause based on if they are present in table1?
P.S. table1 primary key (CustomerId, CampaignID)
This will work as for your scenario. But it wont show last result record 5,5 since it does not fulfill your need.
select * from input where (cust_id, camp_id) not in (select cust_id, camp_id from table1)

How best to populate a subordinate numeric key [duplicate]

This question already has answers here:
Database scheme, autoincrement
(2 answers)
Closed 3 years ago.
I have two tables: Items and Defects.
Each defect relates to one (and only one) item.
The PK for Items is an identity column (ItemID), which appears as a FK column in Defects, to relate the two tables.
The PK for Defects is an identity column (DefectID).
However there is also a subordinate numeric key in Defects called RefNo, which must be populated by a sequential number per ItemID, thus:
Defects
DefectID ItemID RefNo
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 3 1
7 4 1
8 3 2
9 1 4
What's the best way to populate the Ref column?
Currently the code I inherited accomplishes this in the front end which is obviously A Bad Idea.
I am starting to code an insert trigger (SQL Server 2008-R2) but wonder about atomicity and the need to potentially update more than one row when the trigger is called - and the likelihood of simultaneous inserts by different users to try and insert the same RefNo.
[Edit]
I'm maintaining an existing database and removing the RefNo column and repacing it with a value calculated on the fly is not an option.
You can use ROW_NUMBER as below to generate your refno-
WITH your_table(DefectID,ItemID,RefNo)
AS
(
SELECT 1,1,1 UNION ALL
SELECT 2,1,2 UNION ALL
SELECT 3,1,3 UNION ALL
SELECT 4,2,1 UNION ALL
SELECT 5,2,2 UNION ALL
SELECT 6,3,1 UNION ALL
SELECT 7,4,1 UNION ALL
SELECT 8,3,2 UNION ALL
SELECT 9,1,4
)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY DefectID) AS RefNo_new
FROM your_table
order by 2,1
Output-
DefectID ItemID RefNo RefNo_new
1 1 1 1
2 1 2 2
3 1 3 3
9 1 4 4
4 2 1 1
5 2 2 2
6 3 1 1
8 3 2 2
7 4 1 1

How to select the value from the table based on category_id USING SQL SERVER

How to select the value from the table based on category_id?
I have a table like this. Please help me.
Table A
ID Name category_id
-------------------
1 A 1
2 A 1
3 B 1
4 C 2
5 C 2
6 D 2
7 E 3
8 E 3
9 F 3
How to get the below mentioned output from table A?
ID Name category_id
--------------------
1 A 1
2 A 1
4 C 2
5 C 2
7 E 3
8 E 3
Give a row number for each row based on group by category_id and sort by ascending order of ID. Then select the rows having row number 1 and 2.
Query
;with cte as (
select [rn] = row_number() over(
partition by [category_id]
order by [ID]
), *
from [your_table_name]
)
select [ID], [Name], [category_id]
from cte
where [rn] < 3;
Kindly run this query It really help You Out.
SELECT tbl.id,tbl.name, tbl.category_id FROM TableA as tbl WHERE
tbl.name IN(SELECT tbl2.name FROM TableA tbl2 GROUP BY tbl2.name HAVING Count(tbl2.name)> 1)
Code select all category_id from TableA which has Name entries more then one. If there is single entry of any name group by category_id then such data will be excluded. In above example questioner want to eliminate those records that have single Name entity like wise category_id 1 has name entries A and B among which A has two entries and B has single entry so he want to eliminate B from result set.

Using Recursive CTE with GroupBy

I am new to the recursive CTE concept and a problem at hand, I got a tiny feeling that the problem can be solved by using recursive CTE. Let me know what you guys think.
Two tables:
Table one is a self referencing Location table with ID, ParentID, Level and Description.
Table two is an asset table which records individual assets and has a foreign key to Location table ID field.
Table1:
ID Description ParentID Level
1 Site1 NULL 1
2 Site2 NULL 1
3 Building1 1 2
4 Building2 1 2
5 Floor1 3 3
6 Floor2 3 3
7 Floor3 4 3
8 Place1 5 4
9 Place2 7 4
Table2:
ID Description Quantity LocationID
1 Desk 3 8
2 Lamp 1 8
3 PC 10 9
I would like to create a stored procedure with a input parameter of #Level and returns all the Location records at that level and the number of assets within the location (including sub levels).
For example, if #Level = 3, the stored procedure should return:
ID Description AssetCount
5 Floor1 4
6 Floor2 0
7 Floor3 10
If #Level = 2, the stored procedure should return:
ID Description AssetCount
3 Building1 4
4 Building2 10
If the problem is not clear, please let me know.
Well, nothing special here, just a recursive CTE joined with the other table, and the results are what you expected:
declare #level int = 3
;with CTE as (
select id as origid, id, Description, parentid
from table1 where level = #level
union all
select CTE.origid, t1.id, CTE.Description, t1.parentid
from CTE join table1 t1 on
CTE.id = t1.parentid
)
select origid, CTE.description, isnull(sum(t2.Quantity),0) as Quantity
from CTE left outer join table2 t2 on CTE.id = t2.locationid
group by origid, CTE.description
SQL Fiddle

Copying SQL database and fixing foreign keys

I am making an application which optimizes routes (kind of like a VRP). The user must be able to copy all input data, and make changes to this data. This way, they are able to find out what the impact is on the optimization.
Therefore I chose to let them be able to copy all input data, and have sort of like a version management of the data.
I want to copy the following tables:
TableOne
ID UUID WEIGHT CODE
1 abc 15 AB
2 abd 5 AC
TableTwo
ID UUID SIZE TABLE1_FK
1 abe 1 1
2 abf 3 2
The resulting tables (after copying):
TableOne
ID UUID WEIGHT CODE
1 abc 15 AB
2 abd 5 AC
3 abg 15 AB
4 abh 5 AC
TableTwo
ID UUID SIZE TABLE1_FK
1 abe 1 1
2 abf 3 2
3 abi 1 1
4 abj 3 2
Up to this point, I can manage. But now when I want to update the foreign keys of TableTwo to point to the copied lines in TableOne, I get stuck.
I want to do something like:
UPDATE TableOne
SET TABLE1_FK =
(SELECT t.ID
FROM TableOne t
WHERE t.WEIGHT = (SELECT t.WEIGHT
FROM TableOne t1
WHERE ...)
)
And this is where I get stuck.
The wanted result is:
TableTwo
ID UUID SIZE TABLE1_FK
1 abe 1 1
2 abf 3 2
3 abi 1 3
4 abj 3 4
Any suggestions?
After you insert in the first table , select it's ##IDENTITY and use it to insert
in the second table as foreign key.

Resources