ACCESS/SQL Combining multiple rows with one column into one row and creating multiple columns

半城伤御伤魂 提交于 2021-02-02 03:46:30

问题


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:

current table

what I need:

table 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!