I have a table with travel details. Details are getting saved in distributed manner. I need to merge the rows based on Source and Destination. My Source is A and Final Destination is D, I need to merge all the 3 rows into 1 with sum of time and distance.
Table1:Trip details
CarID
Source
Destination
Distance
Time
1
A
B
10
1
1
B
C
20
2
1
C
D
30
3
Table2: TravelPlan
CarID
Source
Destination
1
A
D
Output Needed:
Table 3:
CarID
Source
Destination
Distance
Time
1
A
D
60
6
I tried using Concatenate but not able to do based on conditions. Not sure how to combine rows of one table based on values of another.
your Data
DECLARE #TripDetails TABLE (
CarID INT NOT NULL
,Source VARCHAR(20) NOT NULL
,Destination VARCHAR(20) NOT NULL
,Distance INT NOT NULL
,Time INT NOT NULL
);
INSERT INTO #TripDetails
(CarID,Source,Destination,Distance,Time)
VALUES
(1,'A','B',10,1),
(1,'B','C',20,2),
(1,'C','D',30,3);
DECLARE #TravelPlan TABLE (
CarID INT NOT NULL
,Source VARCHAR(20) NOT NULL
,Destination VARCHAR(20) NOT NULL
);
INSERT INTO #TravelPlan
(CarID,Source,Destination) VALUES
(1,'A','D');
what you need are Subquery and join and SUM. your query
SELECT TP.carID,
TP.Source,
TP.Destination,
TD.Distance,
TD.Time
FROM (select carID,
Sum(Distance) Distance,
Sum(Time) Time
FROM #TripDetails
GROUP BY carID) TD
JOIN #TravelPlan TP
ON TD.carID = TP.carID
Fiddle
Related
Expecting duplicate row with different output in the last column.
Here's my Stored Procedure query
SELECT
Name = SELECT ......
Mobile = SELECT .....
Title = SELECT .....
Developer = (SELECT Description FROM ParameterDeveloper WHERE Id IN (SELECT WorkId FROM Company WHERE Id = Records.ApplicationId)
FROM Records
Here's my Records Table
ApplicationId
Name
100
Sky
300
Sam
400
Luke
Here's my ParameterDeveloper Table
Id
Description
100
Oracle
100
Ibm
200
Salesforce
Here's my Company Table
Id
WorkId
100
100
200
200
300
300
Expected result -
Name
Developer
Sky
Oracle
Sky
Ibm
My Error is:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
your data
CREATE TABLE Records (
ApplicationId INTEGER NOT NULL
,Name VARCHAR(100) NOT NULL
);
INSERT INTO Records
(ApplicationId,Name) VALUES
(100,'Sky'),
(300,'Sam'),
(400,'Luke');
CREATE TABLE ParameterDeveloper (
Id INTEGER NOT NULL
,Description VARCHAR(100) NOT NULL
);
INSERT INTO ParameterDeveloper
(Id,Description) VALUES
(100,'Oracle'),
(100,'Ibm'),
(200,'Salesforce');
CREATE TABLE Company (
Id INTEGER NOT NULL
,WorkId INTEGER NOT NULL
);
INSERT INTO Company
(Id,WorkId) VALUES
(100,100),
(200,200),
(300,300);
your query
select Name,Description
from Records R
JOIN Company C
ON C.Id=R.ApplicationId
JOIN ParameterDeveloper P
ON P.Id=R.ApplicationId
dbfiddle
id
parentid
amount
79648627
79648626
1
79648626
null
2
Current Table, I want to match the parentid with the id and in case they match get the same value of the amount where the parentid is null, in other words desired result:
id
parentid
amount
79648627
79648626
2
79648626
null
2
If there is only one level of hierarchy then you can use subquery to get your result.
create table testtable(id int, parentid int, amount int);
insert into testtable values(79648627, 79648626, 1);
insert into testtable values(79648626, null, 2);
Query:
select id,parentid,
(case when parentid is not null then (select amount from testtable tt where tt.id=t.parentid) else amount end )amount
from testtable t
Output:
id
parentid
amount
79648627
79648626
2
79648626
null
2
db<fiddle here
Trying to compare between two columns and check if there are no records that exist with the reversal between those two columns. Other Words looking for instances where 1-> 3 exists but 3->1 does not exist. If 1->2 and 2->1 exists we will still consider 1 to be part of the results.
Table = Betweens
start_id | end_id
1 | 2
2 | 1
1 | 3
1 would be added since it is a start to an end with no opposite present of 3,1. Though it did not get added until the 3rd entry since 1 and 2 had an opposite.
So, eventually it will just return names where the reversal does not exist.
I then want to join another table where the number from the previous problem has its name installed on it.
Table = Names
id | name
1 | Mars
2 | Earth
3 | Jupiter
So results will just be the names of those that don't have an opposite.
You can use a not exists condition:
select t1.start_id, t1.end_id
from the_table t1
where not exists (select *
from the_table t2
where t2.end_id = t1.start_id
and t2.start_id = t1.end_id);
I'm not sure about your data volume, so with your ask, below query will supply desired result for you in Sql Server.
create table TableBetweens
(start_id INT,
end_id INT
)
INSERT INTO TableBetweens VALUES(1,2)
INSERT INTO TableBetweens VALUES(2,1)
INSERT INTO TableBetweens VALUES(1,3)
create table TableNames
(id INT,
NAME VARCHAR(50)
)
INSERT INTO TableNames VALUES(1,'Mars')
INSERT INTO TableNames VALUES(2,'Earth')
INSERT INTO TableNames VALUES(3,'Jupiter')
SELECT *
FROM TableNames c
WHERE c.id IN (
SELECT nameid1.nameid
FROM (SELECT a.start_id, a.end_id
FROM TableBetweens a
LEFT JOIN TableBetweens b
ON CONCAT(a.start_id,a.end_id) = CONCAT(b.end_id,b.start_id)
WHERE b.end_id IS NULL
AND b.start_id IS NULL) filterData
UNPIVOT
(
nameid
FOR id IN (filterData.start_id,filterData.end_id)
) AS nameid1
)
I have a table called Node with 4 columns in which the data are populated for all the fields except Lat and Long
TABLE(
ID int not null
Column2 int not null
Column3 int not null
Column4 int not null
LAT float
LONG float
)
I have another table called "test" with 3 columns with date populated
TABLE
(
ID,
LAT
LONG
)
If ID from test matches with Id from node the corresponding lat an long values from test should be inserted into Node.
I tried some thing like this but it give
INSERT INTO tblNode(x,y)
SELECT tpn.Longitude,tpn.Latitude FROM dbo.Node n
JOIN test tpn
ON tpn.NodeID = n.NodeID
Error
Cannot insert the value NULL into column 'ID', table
Can Some one help me with this query.
If you were creating new records, you would include the ID
INSERT INTO tblNode(nodeID,x,y)
SELECT tpn.nodeID, tpn.Longitude,tpn.Latitude FROM dbo.Node n
JOIN test tpn
ON tpn.NodeID = n.NodeID
However, looking at your question closely you don't want to INSERT. You want to UPDATE
UPDATE n
SET Lat = tpn.Longitude, Lon = tpn.Latitude
FROM Node n
JOIN test tpn ON tpn.NodeID = n.NodeID
I have an interesting SQL problem that I need help with.
Here is the sample dataset:
Warehouse DateStamp TimeStamp ItemNumber ID
A 8/1/2009 10001 abc 1
B 8/1/2009 10002 abc 1
A 8/3/2009 12144 qrs 5
C 8/3/2009 12143 qrs 5
D 8/5/2009 6754 xyz 6
B 8/5/2009 6755 xyz 6
This dataset represents inventory transfers between two warehouses. There are two records that represent each transfer, and these two transfer records always have the same ItemNumber, DateStamp, and ID. The TimeStamp values for the two transfer records always have a difference of 1, where the smaller TimeStamp represents the source warehouse record and the larger TimeStamp represents the destination warehouse record.
Using the sample dataset above, here is the query result set that I need:
Warehouse_Source Warehouse_Destination ItemNumber DateStamp
A B abc 8/1/2009
C A qrs 8/3/2009
D B xyz 8/5/2009
I can write code to produce the desired result set, but I was wondering if this record combination was possible through SQL. I am using SQL Server 2005 as my underlying database. I also need to add a WHERE clause to the SQL, so that for example, I could search on Warehouse_Source = A. And no, I can't change the data model ;).
Any advice is greatly appreciated!
Regards,
Mark
SELECT source.Warehouse as Warehouse_Source
, dest.Warehouse as Warehouse_Destination
, source.ItemNumber
, source.DateStamp
FROM table source
JOIN table dest ON source.ID = dest.ID
AND source.ItemNumber = dest.ItemNumber
AND source.DateStamp = dest.DateStamp
AND source.TimeStamp = dest.TimeStamp + 1
Mark,
Here is how you can do this with row_number and PIVOT. With a clustered index or primary key on the columns as I suggest, it will use a straight-line query plan with no Sort operation, thus be particularly efficient.
create table T(
Warehouse char,
DateStamp datetime,
TimeStamp int,
ItemNumber varchar(10),
ID int,
primary key(ItemNumber,DateStamp,ID,TimeStamp)
);
insert into T values ('A','20090801','10001','abc','1');
insert into T values ('B','20090801','10002','abc','1');
insert into T values ('A','20090803','12144','qrs','5');
insert into T values ('C','20090803','12143','qrs','5');
insert into T values ('D','20090805','6754','xyz','6');
insert into T values ('B','20090805','6755','xyz','6');
with Tpaired(Warehouse,DateStamp,TimeStamp,ItemNumber,ID,rk) as (
select
Warehouse,DateStamp,TimeStamp,ItemNumber,ID,
row_number() over (
partition by ItemNumber,DateStamp,ID
order by TimeStamp
)
from T
)
select
max([1]) as Warehouse_Source,
max([2]) as Warehouse_Destination,
ItemNumber,
DateStamp
from Tpaired
pivot (
max(Warehouse) for rk in ([1],[2])
) as P
group by ItemNumber, DateStamp, ID;
go
drop table T;