this will be the first question I’ve posted here so pardon any unintended lapses in board etiquette.
In my current project, I’ve taken a large, non-normalized table and broken it into four separate, normalized tables. My ultimate goal that I’m reaching out to this board for is to create a view which mimics the non-normalized table for backwards compatibility.
To provide a simplified snapshot of my scenario, the crux of what I’m trying to do lies in two tables:
ASSOC_ROLE ASSOCIATE
---------- ----------
assoc_id (fk) assoc_id (pk)
role_id (fk) last_name
org_nbr (fk)
So if I issue the following query…
SELECT Assoc_Role.org_nbr, Assoc_Role.assoc_id, Associate.last_name, Assoc_Role.role_id
FROM Assoc_Role INNER JOIN
Associate ON Assoc_Role.assoc_id = Associate.assoc_id
WHERE Assoc_Role.org_nbr = '1AA'
…I get the following result set
org_nbr assoc_id last_name role_id
------- -------- --------- -------
1AA 1447 Cooper 1
1AA 1448 Collins 3
1AA 1448 Collins 4
1AA 1448 Collins 5
1AA 1449 Lynch 6
Ultimately, the view I would like to construct would look something like this:
org_nbr role1_ID role1_name role2_ID role2_name role3_ID role3_name role4_ID role4_name role5_ID role5_name role6_ID role6_name
------- -------- ---------- -------- ---------- -------- ---------- -------- ---------- -------- ---------- -------- ----------
1AA 1447 Cooper NULL NULL 1448 Collins 1448 Collins 1448 Collins 1449 Lynch
My initial thought was to try to use the PIVOT command, but my understanding is that PIVOT requires some kind of aggregation, and that doesn’t fit my scenario. I’ve also played around with the CASE command in the SELECT clause, but it doesn’t flatten my result set down to one record.
Hopefully someone can shed some light on how I can accomplish this. Let me know if anyone needs more info. Thanks!
Scot
To get the basic numbered-role data, we might start with
BUT this will give us, for each
org_nbr, a separate row for eachrole_idthat has data! Which is not what we want – so we need toGROUP BY org_nbr. But then we need to eitherGROUP BYor aggregate over every column in theSELECTlist! The trick then is to come up with an aggregate function that will placate SQL Server and give us the results we want. In this case,MINwill do the job:Output:
Of course this will fall short should the maximum
role_idincrease…