我有一个返回某些特定数据的查询:
SELECT sub.*
FROM (
Select item_id, field_id, attr_val from [CONTRACT_ATTR] where item_id in (select item_id from [CONTRACT_ATTR] where field_id = 326 and attr_val = 'Y')
) sub
WHERE field_id = 234 or field_id = 413
值A750与制造商表上的item_pk相关联。我想从MFR表中恢复item_name,并将其添加为每个关联的item_id的行。例如,16后将有3行。 MRF中的item_name将位于attr_val列。
我现在最接近的是这是拉入item_name但是在错误的行上,并且正在删除我需要的其他字段。
SELECT sub.*, m.item_name
FROM (
Select item_id, field_id, attr_val from [CONTRACT_ATTR] where item_id in (select item_id from [CONTRACT_ATTR] where field_id = 326 and attr_val = 'Y')
) sub
JOIN MFR m
ON m.item_pk = sub.attr_val and field_id = 234
我做错了什么以及如何解决?
编辑:
CREATE TABLE [dbo].[CONTRACT_ATTR](
[ITEM_ID] [int] NOT NULL,
[FIELD_ID] [int] NOT NULL,
[ATTR_VAL] [varchar](500) NOT NULL,
[UPD_DTT] [datetime] NOT NULL,
[UPD_USR] [varchar](500) NOT NULL,
CONSTRAINT [PK_CONTRACT_ATTR] PRIMARY KEY CLUSTERED
(
[ITEM_ID] ASC,
[FIELD_ID] ASC,
[ATTR_VAL] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
CREATE TABLE [dbo].[MFR](
[ITEM_ID] [int] IDENTITY(1,1) NOT NULL,
[ITEM_NAME] [varchar](500) NOT NULL,
[ADD_DTT] [datetime] NOT NULL,
[ADD_USR] [varchar](500) NOT NULL,
[UPD_DTT] [datetime] NOT NULL,
[UPD_USR] [varchar](500) NOT NULL,
[ACTIVE_IND] [char](1) NULL,
[ITEM_PK] [varchar](500) NULL,
CONSTRAINT [PK_MFR] PRIMARY KEY CLUSTERED
(
[ITEM_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
答案 0 :(得分:1)
您可以使用outer apply()
获取制造商名称,然后可选择使用max() over()
窗口函数为每item_id
返回{@ 1}},即使field_id
不是234
1}}。
select
c.item_id
, c.field_id
, c.attr_val
, m.item_name /* includes nulls when c.field_id is not 234 */
, max(m.item_name) over (partition by c.item_id) as mfr_name
from [CONTRACT_ATTR] c
outer apply (
select top 1 i.item_name
from MFR i
where i.item_pk = c.attr_val
and c.field_id = 234
) m
where c.item_id in (
select item_id
from [CONTRACT_ATTR]
where field_id = 326
and attr_val = 'Y'
)