I have several tables that I need to gather certain information from and roll the data into a single row. I am currently trying to accomplish this with a Union, but for some reason, the data is returning in several rows, and not the roll-up I am wanting, so that all of the information is on a single row, with the column data. Here is my current script, and how the data is showing:
SELECT a.ID, a.LOC, a.DATE, a.DESC as Description, a.Item1 as Available, b.Item2 as LA Available, b.Items3 as SA Available FROM Products a, Products2 bWHERE a.ID=b.IDUNIONSELECT NULL, NULL, NULL, NULL, NULL, b.Item2 as LA Available, b.Items3 as SA Available FROM Products a, Products2 bWHERE a.ID=b.IDGROUP BY a.ID, a.LOC, a.DATE, a.DESC, a.Item1, b.Item2, b.Items3ORDER BY ID;
put your original scripts into "with cte as" and amend the field names accordingly.
PortletPaul
Please note that the core of what you need to solve the Item1,Item2 and Item3 columns is to use aggregate functions such as MAX() for the Item1,Item2 and Item3 columns and a GROUP BY clause.
BUT
Your image reveals that you would NOT get to a single row. The second column "loc" has 3 different values, and that will lead to 3 rows.
How do you propose to deal with that second column?
e.g. just ignore it? Take the maximum? take the minimum? concatenate into a comma separated string?
SELECT a.ID, a.LOC, a.DATE, a.DESC as Description, sum(a.Item1) as Available, sum(b.Item2) as LAAvailable, sum(b.Items3) as SAAvailable FROM Products a, Products2 b
WHERE a.ID=b.ID
GROUP BY a.ID, a.LOC, a.DATE, a.DESC
UNION
SELECT NULL, NULL, NULL, NULL, NULL, sum(b.Item2) as LAAvailable, sum(b.Items3)
as SAAvailable FROM Products a, Products2 b
WHERE a.ID=b.ID
ORDER BY ID;
aj85
ASKER
Hello Mark,
Your advice solved my problem! :) Thank you very much, and also thank you to everyone else that offered their advice, as well. I simply could not get this to work as required. Again, thanks everyone.
Open in new window
put your original scripts into "with cte as" and amend the field names accordingly.