February 19, 2022 at 1:07 pm
Hi,
As I'm developing for client that require show all information in same row to ID. For example the first image
It is list of Animal with ID 101 to 104 which it count number of animal per year. which I have SQL already which is not a problem.
Now I need this just same ID and animal. but the new column with recent year with number.
How do I solve this query?
February 19, 2022 at 1:36 pm
This is easily achieved with a cross-tab query
CREATE TABLE #Animal (ID int, Animal varchar(20), Number int, [Year] int);
INSERT INTO #Animal ( ID, Animal, Number, [Year] )
VALUES ( 101, 'Rabbit', 1, 2020 )
, ( 101, 'Rabbit', 5, 2017 )
, ( 101, 'Rabbit', 3, 2016 )
, ( 101, 'Rabbit', 5, 2015 )
----------------------------
, ( 102, 'Bear', 7, 2019 )
, ( 102, 'Bear', 2, 2018 )
, ( 102, 'Bear', 1, 2016 )
, ( 102, 'Bear', 5, 2015 )
----------------------------
, ( 103, 'Lion', 5, 2019 )
, ( 103, 'Lion', 8, 2017 )
, ( 103, 'Lion', 6, 2016 )
, ( 103, 'Lion', 2, 2015 )
----------------------------
, ( 104, 'Kangaroo', 3, 2020 )
, ( 104, 'Kangaroo', 2, 2018 )
, ( 104, 'Kangaroo', 5, 2017 )
, ( 104, 'Kangaroo', 7, 2016 );
WITH cteData AS (
SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.Year DESC)
FROM #Animal AS a
)
SELECT d.ID, d.Animal
, Recent1 = MAX(CASE WHEN rn = 1 THEN CAST(d.Number as varchar(10)) + ' (' + CAST(d.[Year] as varchar(10)) + ')' ELSE NULL END)
, Recent2 = MAX(CASE WHEN rn = 2 THEN CAST(d.Number as varchar(10)) + ' (' + CAST(d.[Year] as varchar(10)) + ')' ELSE NULL END)
, Recent3 = MAX(CASE WHEN rn = 3 THEN CAST(d.Number as varchar(10)) + ' (' + CAST(d.[Year] as varchar(10)) + ')' ELSE NULL END)
, Recent4 = MAX(CASE WHEN rn = 4 THEN CAST(d.Number as varchar(10)) + ' (' + CAST(d.[Year] as varchar(10)) + ')' ELSE NULL END)
FROM cteData AS d
WHERE rn <= 4
GROUP BY d.ID, d.Animal
ORDER BY d.ID;
February 21, 2022 at 8:39 am
Thank you very much! it is useful 🙂
February 21, 2022 at 9:30 am
Please see the following article if you want to know more about CROSSTAB queries and how they work.
https://www.sqlservercentral.com/articles/cross-tabs-and-pivots-part-1-converting-rows-to-columns-1
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply