I'm facing an issue with the following problem.
A table I need to fill (let's say, Activities
), has 3 columns (let's say Act1, Act2, Act3
), where I need to place in order the last 3 activities the client has on that record.
I succeeded in creating the query that extracts the top 3 activities in decreasing order (this is a union of two different tables, as activities can be email or generic notes):
SELECT TOP 3 Concat(subject, ' | ', content, ' | ', creation) AS ActivityContent
FROM (SELECT TOP 3 'Email' AS Tipo,
a.regardingobjectid AS Regarding,
a."subject" AS "Subject",
NULL AS "Content",
a.createdon AS creation
FROM mydb.dbo.activities a
WHERE a.activitytypecode = 4202
UNION
SELECT TOP 3 'Note' AS Tipo,
ann.objectid AS Regarding,
ann."subject" AS "Subject",
ann.notetext AS "Content",
ann.createdon AS creation
FROM mydb.dbo.notes ann) AS Act
ORDER BY creation DESC
This is the result of my query:
I now need to report the result ActivityContent of the 3 rows (these are ALWAYS 3, or maybe less if no activity has been done), to the Act1, Act2, Act3
columns.
+-----------------------------------------------+-----------------------------------------------+----------------------------+--+
| Col1 | Col2 | Col3 | |
+-----------------------------------------------+-----------------------------------------------+----------------------------+--+
| 'Test Nota' | 'Test Descrizione' | Oct 30 ... | 'Test Nota' | 'Test Descrizione' | Oct 30 ... | d | | Oct 26 2018 9:23PM | |
+-----------------------------------------------+-----------------------------------------------+----------------------------+--+
I'll say I'm not really familiar with SQL procedures in general, but I got lost within the tons of function I found online:
From what I understand, PIVOT could be one of the suitable functions, but it seems to be it has to be used when you need to aggregate (count, sum) within a column, and that's not my request.
I also checked APPLY, CROSS APPLY and so on, but I really didn't get the point on which has to be used, and how to implement it.
Thanks in advance for any hint.