如何将列连接到T-SQL中的选定查询

时间:2017-10-18 13:04:29

标签: sql-server tsql

我有以下视图,我需要在字符表中添加characterName列作为参考 ,不用 更改查询结果的结构。请帮忙。

        CREATE VIEW vwTopStackedItems
    AS
        SELECT TOP 20 MAX(inventorySlot.quantity) AS 'Top Stacked', item.itemName AS 'Item Name'
        FROM inventorySlot
        JOIN item
        ON inventorySlot.itemID = item.itemID
        JOIN character
        ON inventorySlot.characterID = character.characterID
        WHERE quantity > 1
        GROUP BY itemName
        ORDER BY MAX(quantity) DESC             
    GO


SELECT * FROM vwTopStackedItems
GO

2 个答案:

答案 0 :(得分:0)

您可以使用函数CONCAT()来连接这两个值。有关详细信息:https://docs.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql

CREATE VIEW vwTopStackedItems
    AS
        SELECT TOP 20 MAX(inventorySlot.quantity) AS 'Top Stacked', CONCAT(item.itemName, '-', character.characterName)  AS 'Item Name'
        FROM inventorySlot
        JOIN item
        ON inventorySlot.itemID = item.itemID
        JOIN character
        ON inventorySlot.characterID = character.characterID
        WHERE quantity > 1
        GROUP BY CONCAT(item.itemName, '-', character.characterName)
        ORDER BY MAX(quantity) DESC             
    GO


SELECT * FROM vwTopStackedItems
GO

答案 1 :(得分:0)

由于itemName是此视图的关键,因此您需要另一个视图:

CREATE VIEW vwTopStackedItemsWCharacter
    AS
        SELECT itemName, characterName 
        FROM inventorySlot
        JOIN item
        ON inventorySlot.itemID = item.itemID
        JOIN character
        ON inventorySlot.characterID = character.characterID
        GROUP BY itemName, characterName

第二个视图将带来角色名称,因此您将相应地加入。通过这种方式,您可以在vwTopStackedItems

上获得信息而无需任何更改