0

我试图返回用更易读的描述值替换记录 ID 的结果。通过 AS 更改列名非常简单,但我认为需要子查询来获取 ID 值(例如 PT1)并获取 Description 值作为替换。

例如,我有一个 table1 有一些列,如:

编号| 纸| 涂料 | 创建于 | 类型

1 | pid3 | cid5 | 某个日期| tid2 2 | pid2 | cid8 | 某个日期| tid3 3 | pid1 | cid1 | 某个日期| tid4

然后 table2 有父表中引用 id 的详细信息:

编号| 键 | 描述 |

1 | pid3 | 一些用户友好的描述| 1 | pid1 | 其他一些描述| 1 | pid2 | 别的东西|

表三和四类似

我尝试使用 JOIN 链接 Paper ID,但这没有返回任何值

选择 table1.Paper 作为“纸张名称”,table1.Coating,table1.CreatedOn,table1.Type,table2.description FROM table1 JOIN table2 ON table1.Paper = table2.fKey

我的实际查询如图所示,但表名已更改:

SELECT PD_ComboRun.RNId AS 'RUN #', PD_ComboRun.RNQty AS Quantity,
       PD_ComboRun.PTId, PD_ComboRun.PSId AS Size, PD_ComboRun.RNType AS 'Run Type',
       PD_ComboRun.PCId AS 'Press Coating', PD_ComboRun.UVFid AS 'UV Finish',
       PD_ComboRun.Notes AS 'Special Instructions', PD_ComboRun.CreatedOn AS 'Date Created', 
       SM_PaperType.PTCode AS Paper, SM_PaperType.PTId AS Expr1
FROM  PD_ComboRun 
LEFT JOIN SM_PaperType ON SM_PaperType.PTId = PD_ComboRun.PTId

有人可以为我指出实现这一目标的正确方向吗?谢谢!

4

2 回答 2

1

正如我认为你需要的那样,这非常有效。我对其进行了修改以使用您的表格和字段。

DECLARE @PD_ComboRun TABLE(RNId int,RNQty int,PTId varchar(10),
    PSId varchar(10),PCId varchar(10),UVFid varchar(10),createdOn smalldatetime, 
    RNType varchar(10),Notes varchar(MAX))
INSERT INTO @PD_ComboRun
SELECT 1,5,'pid3','psid1','cid5','uvid1',GETDATE(),'tid2',''
UNION ALL
SELECT 2,10,'pid2','psid2','cid8','uvid4',GETDATE(),'tid3','notes'
UNION ALL
SELECT 3,7,'pid1','psid1','cid1','uvid1',GETDATE(),'tid4',''

SELECT * FROM @PD_ComboRun

DECLARE @SM_PaperType TABLE(PTId varchar(10),PTCode varchar(50))
INSERT INTO @SM_PaperType
SELECT 'pid3','some user friendly description'
UNION ALL
SELECT 'pid2','some other description'
UNION ALL
SELECT 'pid1','something else'

SELECT * FROM @SM_PaperType

SELECT t1.RNId AS [Run #], t1.RNQty AS Quantity,
    t1.PTId,t1.PSId AS Size,t1.RNType AS [Run Type], 
    t1.PCId AS [Press Coating], t1.UVFid AS 'UV Finish', 
    t1.Notes AS 'Special Instructions',t1.createdOn AS 'Date Created',
    t2.PTCode AS Paper,t2.PTId AS Expr1
FROM @PD_ComboRun t1 INNER JOIN @SM_PaperType t2 ON t1.PTId=t2.PTId

结果

@表格1

1   5   pid3    psid1   cid5    uvid1   2012-05-31 17:45:00 tid2    
2   10  pid2    psid2   cid8    uvid4   2012-05-31 17:45:00 tid3    notes
3   7   pid1    psid1   cid1    uvid1   2012-05-31 17:45:00 tid4    

@table2

pid3    some user friendly description
pid2    some other description
pid1    something else

@组合 在此处输入图像描述

于 2012-05-31T23:31:53.283 回答
0
FROM  Table1 LEFT JOIN Table2 ON Table2.PTId = Table1.PCId

这看起来像确凿的证据,不应该是Table1.PTId吗?鉴于表 2 中的样本数据仅显示了 PTId 的值。也许您正在创建一个通用表,但如果是这种情况,则应重命名 Table2 中的“FK”,以免与 Table1 发生冲突。

于 2012-05-31T23:02:16.547 回答