How Select top row from child table [closed] - sql-server

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i have two tables and i want to select top row from child table?
there are relation by two tables by id.
what can i do please help me????

SELECT TOP ... with an appropriate where clause and/or join should do what you're looking for; there are lots of questions and answers about its use here on SO.
Example:
CREATE TABLE a (pid int, tstamp datetime)
go
CREATE TABLE b (fid int, foo varchar(254))
go
INSERT INTO a (pid, tstamp) VALUES (1, '2010-01-12')
INSERT INTO a (pid, tstamp) VALUES (2, '2010-01-02')
INSERT INTO a (pid, tstamp) VALUES (3, '2010-01-01')
INSERT INTO a (pid, tstamp) VALUES (4, '2010-01-24')
INSERT INTO b (fid, foo) VALUES (1, 'one')
INSERT INTO b (fid, foo) VALUES (2, 'two')
INSERT INTO b (fid, foo) VALUES (3, 'three')
go
SELECT TOP 2 b.foo
FROM a
INNER JOIN b ON a.pid = b.fid
ORDER BY a.tstamp
Returns two rows:
'three'
'two'

Not enough details and seeing more of what you've tried would help with building a better answer, but if a is the parent table and b the child...
SELECT TOP 1 b.*
FROM b
JOIN a ON (a.ID = b.ID)
WHERE a.ID = someParentID
AND b.SomeField = "someChildCriteria"
ORDER BY b.ID DESC -- or by whatever field needs to be topmost

Related

SQL Server : I'm trying to get this table working, [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
How do I turn the top dataset into the bottom dataset, so that I can add it to another joined table?
I was trying Cross joins and Pivots but nothing seemed to work.
Please search before asking. Simple pivot examples are already on this site numerous times. Here's another simple example using PIVOT:
CREATE TABLE animals (
ID int
, ChildID int
, [Name] nvarchar(50)
, Age int
);
INSERT INTO animals (ID, ChildID, [Name], Age)
VALUES (1, 654, 'Cat', 1)
, (2, 654, 'Dog', 2)
, (5, 655, 'Cat', 4)
, (6, 655, 'Dog', 3)
;
SELECT ChildID
, PivotTable.[Cat]
, PivotTable.[Dog]
FROM (
SELECT ChildID, [Name], Age
From animals
) as sourceTable
PIVOT (
SUM([Age])
FOR [Name] IN ([Cat],[Dog])
) as pivotTable
ORDER BY ChildID
;
ChildID
Cat
Dog
654
1
2
655
4
3
fiddle

How to get max row in a table with 3 columns [duplicate]

This question already has answers here:
Get top 1 row of each group
(19 answers)
Closed 7 months ago.
I'm running Microsoft SQL Server 2014 - 12.0.4213.0 (X64).
(Apologies - I'm a newbie and I know I'm running an old version)
I have the following table:
ID
Name
Time
1
Finished
2022-07-13 17:09:48.0000000
1
Start
2022-07-13 17:00:48.0000000
2
Clean
2022-07-13 15:09:48.0000000
2
Waiting
2022-07-13 17:34:48.0000000
2
Clean
2022-07-13 12:09:48.0000000
3
Start
2022-07-12 18:09:48.0000000
3
Middle
2022-07-12 14:09:48.0000000
3
Middle
2022-06-13 17:09:48.0000000
I want to return a group that will show the max time for each ID number, but also return the Name value of that max row.
I can do a
SELECT
ID, MAX(Time)
FROM
...
WHERE
...
GROUP BY
(ID)
but I need to pull in the Name column as well. I just want one row per ID returning the max time for that ID, and the Name associated with that Time & ID number
Any help would be great thank you
This kind of thing has been asked and answered so many times, but finding the right search term can be challenging. Here is how you can tackle this with your sample data.
declare #Something table
(
ID int
, Name varchar(20)
, Time datetime2
)
insert #Something values
(1, 'Finished', '2022-07-13 17:09:48.0000000')
, (1, 'Start', '2022-07-13 17:00:48.0000000')
, (2, 'Clean', '2022-07-13 15:09:48.0000000')
, (2, 'Waiting', '2022-07-13 17:34:48.0000000')
, (2, 'Clean', '2022-07-13 12:09:48.0000000')
, (3, 'Start', '2022-07-12 18:09:48.0000000')
, (3, 'Middle', '2022-07-12 14:09:48.0000000')
, (3, 'Middle', '2022-06-13 17:09:48.0000000')
select ID
, Name
, Time
from
(
select *
, RowNum = ROW_NUMBER()over(partition by s.ID order by s.Time desc)
from #Something s
) x
where x.RowNum = 1
Just another option (a nudge less performant)
Select Top 1 with ties *
From YourTable
Order By row_number() over (partition by ID order by Time desc)
This can also work
select * from table
where time in (select max(time) from table group by id )
But other's answers seem more efficient.
I have not tested this, if it's wrong then will delete the answer.

How to add/merge two tables on primary key? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm a total SQL newbie. I have two tables. Each table has a primary key column (ID) and several other columns with integer values.
For example:
Now I want to merge both tables into one table - in a way that all apples, bananas and tomatoes are added per ID.
For example:
How does the SQL statement looks like for this task?
INSERT INTO NEWTABLE (ID, Apples, Bananas, Tomatoes)
SELECT ISNULL(a.Id, b.Id) as [Id],
ISNULL(a.Apples,0) + ISNULL(b.Apples,0) AS [Apples],
ISNULL(a.Bananas,0) + ISNULL(b.Bananas,0) AS [Bananas],
ISNULL(a.Tomatoes,0) + ISNULL(b.Tomatoes,0) AS [Tomatoes]
FROM Table1 AS a
FULL OUTER JOIN Table2 AS b on b.Id = a.Id
I think this will solve your issue. Just a INSERT and a SELECT combined.
Have no time to test it, but I would use a UNION and a GROUP BY:
SELECT ID,
SUM(APPLES) AS APPLES,
SUM(BANANAS) AS BANANAS,
SUM(TOMATOES) AS TOMATOES
FROM
(SELECT * FROM TABLEA
UNION ALL
SELECT * FROM TABLEB ) AS ALL
GROUP BY ID
If it works, this first creates a table with all entries and then combines the ones with the same ID. Anyone feel free to edit if there are problems.
Didn't see you want a third table, you don't need the column aliases then:
INSERT INTO
TABLEC
VALUES
(ID, APPLES, BANANAS, TOMATOES)
SELECT ID,
SUM(APPLES),
SUM(BANANAS),
SUM(TOMATOES)
FROM
(SELECT * FROM TABLEA
UNION ALL
SELECT * FROM TABLEB) AS ALL
GROUP BY ID
If that doesn't work, you can do one of the JOIN answers, but would change it to TABLEA JOIN TABLEB USING(ID).
The best approach is to use a full outer join, otherwise you may miss some id's. In your example, with left join you will miss id=4, while with right join you will miss id= 2.
Also be carefull with the ID, you want to take it from Table1 if exists, id from Table2 otherwise
So the best solution i think is something like this:
INSERT INTO Table3 (ID, Apples, Bananas, Tomatoes)
SELECT coalesce (a.Id, b.Id)
coalesce(a.Apples, 0) + coalesce(b.Apples, 0) AS Apples,
coalesce(a.Bananas, 0) + coalesce(b.Bananas, 0) AS Bananas,
coalesce(a.Tomatoes, 0) + coalesce(b.Tomatoes, 0) AS Tomatoes,
FROM Table1 a
FULL OUTER JOIN Table2 b on b.Id = a.Id
Try this
insert into tableC (ID, Apples, Bananas, Tomatoes)
select tableA.ID,
ISNULL(tableA.Apples,0) + ISNULL(tableB.Apples,0) as Apples,
ISNULL(tableA.Bananas,0) + ISNULL(tableB.Bananas,0) as Bananas,
ISNULL(tableA.Tomatoes,0) + ISNULL(tableB.Tomatoes,0) as Tomatoes
from tableA left join tableB
on tableA.ID = tableB.ID;

How do I join two tables on a common column name where 1 table has multiple rows of text I need to concatinate?

I'm trying to return one row result on a.OrderNumber = b.OrderNumber where table b has multiple lines of service comments. Will I need to concatenate the comments into one field result to prevent multiple rows and how do I do that? Here is what I have.
SELECT a.OrderNumber,
b.Comment,
b.Comment,
b.DATE
FROM Orders a
LEFT JOIN Comments b ON a.OrderNumber = b.OrderNumber
I'm looking for:
OrderNumber Comment
1200 01-01-13 Repair made, 01-02-13 Billed Customer
What I get is:
OrderNumber Comment Date
1200 Repair made 01-01-13
1200 Billed Customer 01-02-13
Here's the result I currently have:
Since the OP seemed to have difficulty with the provided code sample I have updated the answer to include the full code result seeing as how the question now includes enough information to make an approximation of the underlying schema.
Incidentally, try not to use reserved words as column names.
CREATE TABLE Orders (OrderNumber INT);
GO
CREATE TABLE Comments (OrderNumber INT, Comment VARCHAR(255), CommentDate DATETIME);
GO
INSERT INTO Orders VALUES (1),(2);
INSERT INTO Comments VALUES
(1, 'Stuff', GETDATE()),
(1, 'Other Stuff', GETDATE()),
(2, 'More stuff', GETDATE())
;WITH cteOrderComment AS (
SELECT a.OrderNumber
,STUFF((
SELECT CONVERT(VARCHAR, C.CommentDate, 10) + ' ' + Comment + ', '
FROM Comments C
WHERE C.OrderNumber = A.OrderNumber
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR (MAX)')
,1,0,'') [Comments]
FROM Orders a
GROUP BY a.OrderNumber
)
SELECT T.OrderNumber, LEFT(T.Comments, LEN(T.Comments) - 1) [Comments]
FROM cteOrderComment T
GO
DROP TABLE Orders
DROP TABLE Comments

Select distinct id from a table with multiple inputs [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a PersonId with me in the People table.
Now i have assigned positions to these Person based on a table named PositionId and PersonId.
The structure of this table is as follows :-
CorporateTeam
PersonId PositionId
1 1
2 2
2 3
So a person with PersonId 2 has multiple positions.
Now I have another table for Skills which is based on PositionId
So i want to retrieve multiple and distinct skills for a particular person based on PersonId.
create table Person (
PersonId int
)
create table Position (
PersionId int,
PositionId int
)
create table Skill (
PositionId int,
SkillId int
)
GO
insert into Person values (1), (2)
insert into Position values (1, 1), (2, 2), (2, 3)
insert into Skill values (2, 1), (2, 2), (3, 3)
GO
select distinct s.SkillId
from Person p
inner join Position pos on p.PersonId = pos.PersionId
inner join Skill s on pos.PositionId = s.PositionId
where p.PersonId = 2

Resources