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
Related
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 12 days ago.
Improve this question
I can't seem to get the Replace & Left functions to work together to remove the dash '-' without errors and I need both to achieve what I am trying to do.
SELECT DISTINCT
Subscriber_Id, REPLACE(LEFT(Subscriber_Id, 3), Subscriber_Id, '-') AS ContractID
FROM
EDW_ODS.dbo.ODS_LABCORP_LABS
WHERE
ContractId IS NULL
I also tried this but get a new column and when I try nesting them together I just errors.
SELECT DISTINCT
Subscriber_Id,
LEFT(Subscriber_ID, 3), REPLACE(Subscriber_ID, '-', '') AS ContractID
FROM
EDW_ODS.dbo.ODS_LABCORP_LABS
WHERE
ContractId IS NULL
If you want to just get the stuff after the first "-" you can do something like:
select stuff(Subscriber_Id, 1, 3, '') AS ContractIDVersion1
, RIGHT(Subscriber_Id, LEN(Subscriber_Id) - 3) AS ContractIDWithRight
, REPLACE(Subscriber_id, LEFT(Subscriber_Id, 3), '') AS ContractIDByReplace
, CASE WHEN CharIndex('-', Subscriber_id) > 0 THEN SUBSTRING(Subscriber_id, CharIndex('-', Subscriber_id) + 1, LEN(Subscriber_id)) ELSE Subscriber_id END AS ContractIDByCharIndex
FROM
EDW_ODS.dbo.ODS_LABCORP_LABS
WHERE
ContractId IS NULL
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.
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 4 years ago.
Improve this question
I have the following data
I would like to compute for the beginning and ending inventory. The formula is Beginning Inventory + Purchases = Ending Inventory. The results should be this:
Is it possible using a T-SQL query?
Set up sample data as follows:
CREATE TABLE #Inventory (
ReportingDate date NOT NULL,
Purchases int NOT NULL
);
GO
INSERT INTO #Inventory (ReportingDate,Purchases)
VALUES
('20181101',77000),
('20181102',100000),
('20181108',0),
('20181109',0),
('20181201',164000),
('20181208',0),
('20181215',0);
GO
Try the following for SQL Server 2008 and earlier:
WITH Pre2012Inv AS (
SELECT *,
(SELECT SUM(Purchases) FROM #Inventory iv WHERE iv.ReportingDate <= i.ReportingDate) AS EndingInventory,
ROW_NUMBER() OVER(ORDER BY ReportingDate ASC) AS RowNum
FROM #Inventory i
)
SELECT p.ReportingDate,
ISNULL(p1.EndingInventory,0) AS BeginningInventory,
p.Purchases,
p.EndingInventory
FROM Pre2012Inv p
LEFT JOIN Pre2012Inv p1 ON p1.RowNum = p.RowNum-1;
Try the following for SQL Server 2012 and later:
WITH Inv AS (
SELECT *,
SUM(Purchases) OVER (ORDER BY ReportingDate ASC ROWS UNBOUNDED PRECEDING) AS EndingInventory
FROM #Inventory
)
SELECT ReportingDate,
LAG(EndingInventory,1,0) OVER (ORDER BY ReportingDate ASC) AS BeginningInventory,
Purchases,
EndingInventory
FROM Inv;
I'm trying to do a query on SQL but I'm stuck!
I have two tables:
Table 1: Question
Table 2: Answer
For each question I can have one or more answers from different users but each user can comment one time.
When a user answers a question, he must choose one status to his answer:
1) Agree, 2) Disagree or 3) Discuss
So, the "Question" table has all the questions like this:
Id Question
1 q1
2 q2
3 q3
..and the "Answer" table has all the answers from the users, plus the FK from the "Question" table and a column with the status chosen by the user.
Id Answer IdQuestion Status
1 a1 1 1
2 a2 1 3
3 a3 2 2
4 a4 2 2
5 a5 3 1
What I need: I need to select all the questions AND I need to count all the questions that has different aswer's status.
Example:
Question 1 has two answers and the two answers has different status. I need to count or put a number just to know that this question has answers with diffent status.
Question 2 has two answers but all the answers has the same status. I don't need to count that.. or maybe put other number to differentiate from the questions that has answers with diffent status.
And the Questions that has only one answer I just select it normally.
Correct me if I'm wrong, but it sounds like you're just after a distinct Status count from the Answers table. So based on a question (regardless of answers) you want to count how many different Status values are present for each question:
CREATE TABLE #Question
(
[Id] INT ,
[Question] VARCHAR(2)
);
INSERT INTO #Question
( Id, Question )
VALUES ( 1, 'q1' ),
( 2, 'q2' ),
( 3, 'q3' ),
( 4, 'q4' )
CREATE TABLE #Answer
(
[Id] INT ,
[Answer] VARCHAR(2) ,
[IdQuestion] INT ,
[Status] INT
);
INSERT INTO #Answer
( [Id], [Answer], [IdQuestion], [Status] )
VALUES ( 1, 'a1', 1, 1 ),
( 2, 'a2', 1, 3 ),
( 3, 'a3', 2, 2 ),
( 4, 'a4', 2, 2 ),
( 5, 'a5', 3, 1 );
SELECT q.id ,
COUNT(DISTINCT Status) DistinctStatusCount
FROM #Question q
LEFT JOIN #Answer a ON q.Id = a.IdQuestion
GROUP BY q.Id
DROP TABLE #Answer
DROP TABLE #Question
Output
IdQuestion DistinctStatusCount
1 2
2 1
3 1
4 0
If you're only interested with questions that have at least one answer you can simply refer to the Answers table:
SELECT IdQuestion ,
COUNT(DISTINCT Status) DistinctStatusCount
FROM #Answer
GROUP BY IdQuestion
try this:
select q.id,
question,
case when min(status) <> max(status) then
1
else
0
end as hasDifferentStatuses
from questions q
inner join answers a on(q.id = a.IdQuestion)
group by q.id, question
I must be missing something as this seems pretty straight forward... The only reason I included the join is a question may not have any answers and you asked for all questions to be returned. Otherwise this could be a query just on the answer table.
SELECT Q.id, count(Distinct A.status)
FROM Question Q
LEFT JOIN Answer A
on Q.ID = A.IdQuestion
Group by Q.IdQuestion
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