问题
I've looked at quite a few examples and nothing fits quite like I need it to. I have a table that has item numbers in one column and image links in another column. The issue I have is I need to combine rows that have the same item number but need to move the data in the HTML_LINK column to multiple columns called imagelink1, imagelink2, imagelink3. The max amount of imagelink columns I will need is 5. I tried a pivot table which worked to combine the rows, but it creates a column the name of the image link and does not move them to 1 of 5 imagelink columns.
What I have now:
what I need:
回答1:
A crosstab seems the route to follow, but I couldn't get the subquery to work as suggested by Parfait - had to use DCount:
TRANSFORM
First(q1.[html_link]) AS html_link
SELECT
[item]
FROM
(SELECT
item,
html_link,
DCount("*", "mytable", "item = '" & item & "' and html_link <= '" & html_link & "'") AS Index
FROM
mytable) AS q1
GROUP BY
[item]
PIVOT
"ImageLink" & q1.[index];
To "clean" the link:
Left(Mid([html_link], InStrRev([html_link], "/") + 1), InStr(Mid([html_link], InStrRev([html_link], "/") + 1), ".") - 1) As Link
回答2:
With conditional aggregation:
select item,
max(iif(col = 1, html_link, null)) as imagelink1,
max(iif(col = 2, html_link, null)) as imagelink2,
max(iif(col = 3, html_link, null)) as imagelink3,
max(iif(col = 4, html_link, null)) as imagelink4,
max(iif(col = 5, html_link, null)) as imagelink5
from (
select t.*,
(select count(*) from tablename where item = t.item and html_link <= t.html_link) as col
from tablename as t
)
group by item
回答3:
With MS Access' crosstab query for more dynamic output up to its 255 column limit. However, in order to use subqueries you must specify columns in PIVOT...IN
clause which requires hard code scripting of all possible columns (i.e., max COUNT
):
TRANSFORM MAX(html_link) AS SumOfPrice
SELECT sub.item, COUNT(*) AS [Total]
FROM
(select t.item, t.image_link,
(select count(*) from mytable
where item = t.item
and html_link <= t.html_link) + 1 as col
from mytable as t) sub
GROUP BY sub.item
PIVOT 'imagelink' & col IN ('imagelink1', 'imagelink2', 'imagelink3', ...);
来源:https://stackoverflow.com/questions/60403841/access-sql-combining-multiple-rows-with-one-column-into-one-row-and-creating-mul