Search code examples
sqlsql-serverssms-2014

Doing Query for with 3 tables and cant get the output how I want it


There is 3 Tables

  • ITEM

    itemID PK
    
  • INVENTORY

    quantity
    charID FK
    itemID FK
    
  • CHARACTERS

    charID PK
    charName
    

.

ITEM 1---many INVENTORY 8----1 CHARACTER

I want to find the top 10 most stacked items that is stacked in the characters inventory and in who has this item stacked in their inventory. So in the end it will be something like itemID 1 has 4 stacks and these charID has the item, itemID 2 has 3 stacks and these charID has the item. In a table.

This is where I am currently at after trying to do this for a while

SELECT COUNT(INVENTORY.itemID) as Stacks, ITEM.itemID, CHARACTERS.charName
FROM INVENTORY
INNER JOIN ITEM
        ON INVENTORY.itemID = ITEM.itemID
INNER JOIN CHARACTERS
        ON INVENTORY.charID = CHARACTERS.charID
WHERE INVENTORY.quantity>1
GROUP BY ITEM.itemID, CHARACTERS.charName
ORDER BY  Stacks DESC
GO

I am instead of getting like data in a single row it splits it up into a bunch of rows for each character. for an example the table headers is

Stacks | ITEMID | charName    
1      | 1      | Char1    
1      | 1      | Char2

but what I want is

Stacks | ITEMID | charName    
2      | 1      | Char1,Char2

Any help is welcome Thanks :). If my format of my question is not up to par please leave a comment of how I can improve.


Solution

  • Sql Demo

    SELECT [ITEMID], 
           LEFT(column_names , LEN(column_names )-1) AS column_names, 
           SUM([Stacks]) total_stacks  -- or COUNT() not sure which you need
    FROM Table1 AS extern
    CROSS APPLY
    (
        SELECT [charName] + ','
        FROM Table1 intern
        WHERE intern.[ITEMID] = extern.[ITEMID]
        FOR XML PATH('')
    ) pre_trimmed (column_names)
    GROUP BY [ITEMID], column_names;
    

    NOTE: I expand your case so include different [itemID]

    OUTPUT

    enter image description here