如何将ID值打印为自定义文本值?

时间:2017-11-08 14:38:29

标签: sql tsql

如何在打印选择结果时将数字ID值更改为单词?

SELECT sku_price, sku_name, sku_group_id

得到:

99.99    iPhone    9

最后我想将sku_group_id(" 9")改为文本值,ex"手机"

我希望仅在打印选择时看到文本值(仅用于更好的视图),而不会对数据库产生任何影响。

2 个答案:

答案 0 :(得分:2)

一种选择是使用CASE表达式:

SELECT
    sku_price,
    sku_name,
    CASE WHEN sku_group_id = 9 THEN 'cellphones'
         WHEN sku_group_id = 8 THEN 'laptops'
         ... ELSE 'default' END AS sku_group_label
FROM yourTable;

为了获得更好的长期解决方案,您可以维护一个表格,将sku_group_id值映射到文本描述,然后加入此表,例如

WITH cte AS (
    SELECT 9 AS sku_group_id, 'cellphones' AS sku_group_label UNION ALL
    SELECT 8, 'laptops'
    ...
)

SELECT
    t1.sku_price,
    t1.sku_name,
    COALESCE(t2.sku_group_label, 'default') AS sku_group_label
FROM yourTable t1
LEFT JOIN cte t2
    ON t1.sku_group_id = t2.sku_group_id;

答案 1 :(得分:0)

假设您有一个sku_group表,因为您的列名为sku_group_id并使用以下示例表结构(在此处做出假设)

Sku group table 
    +-------------+----------+
    |Sku_Group_ID |GroupName |
    +-------------+----------+
    | 9           |Cellphones|
    | 10          | Tablets  |
    +-------------+----------+

然后一个简单的连接就可以成为你的目标

Select Sku.Sku_Price,
Sku.Sku_Name,
Group.GroupName
FROM Sku_Table As Sku
Inner JOIN Sku_Group As Group
ON Sku.Sku_Group_ID = Group.Sku_Group_ID