ITEMCODE
alternatecode
abcd | 1200 |
---|---|
1800 | |
贝尔 | |
11.05 | |
sled | 17.12 |
技术 | |
SELECT itemcode, price
FROM pricing
WHERE itemcode in ('abcd','xxxx','bark','home','sled','tech','bell')
|
|
abcd
DECLARE @DefaultCustomerLevel INT = 5
SELECT
I.item_or_pricecode,
COALESCE(PLookup.[uom_code], P.[uom_code]) AS [uom_code],
ISNULL(P.[price], 0) AS [price],
COALESCE(PLookup.[start_date], P.[start_date]) AS [start_date],
COALESCE(PLookup.[price], P.[price]) AS LevelResult
FROM
(VALUES ('22rgr45dhs'),('35rg4pcpab'),('37rgtf08ab'),('37RGDF10BS'),
('27MIETE11K')) I([item_or_pricecode])
outer apply
(
select top 1 p.* from
[P2S_DMSI].[Agility].[pricing] P where P.[start_cust_or_group] =
'7001364'
AND [cust_shipto_num] = '2'
AND P.[item_or_pricecode] = I.
[item_or_pricecode]
order by
CASE
WHEN p.[tran_type] = 'Quot' THEN 1
WHEN p.[default_level]>0 THEN 2
WHEN p.[default_level] = 0 and [tran_type] = '' THEN 3
END, p.start_date desc
) p
OUTER APPLY
(SELECT TOP 1 *
FROM [P2S_DMSI].[Agility].[pricing] P1
WHERE ISNULL(P.[tran_type], '') = ''
AND P1.[start_cust_or_group] = ''
AND P1.[item_or_pricecode] = I.[item_or_pricecode]
AND P1.[level_] = COALESCE(NULLIF(P.[default_level], 0),
@DefaultCustomerLevel)
ORDER BY P1.start_date DESC) PLookup;
启动与别名表以获取丢失的项目代码;我们使用左加入,因为我们希望结果即使没有匹配,也可以包含每个行的定价。匹配项目代码与替代方案。
现在我们将每一行都与其替代品匹配。
现在选择正确的项目代码。如果定义了备用_codes.itemcode,我们应该使用它,否则我们使用pricing.itemcode。使用xxxx | 10.00 |
---|---|
home | |
贝尔 | |
如果可能的话,我将如何将其整合到下面的查询中 | |
左将加入 | SELECT
*
FROM pricing p
LEFT JOIN alternate_codes ac
ON ac.alternate_code = p.itemcode
|
coalesce
选择第一个非零列。
SELECT
coalesce(ac.itemcode, p.itemcode) as itemcode,
price
FROM pricing p
LEFT JOIN alternate_codes ac
ON ac.alternate_code = p.itemcode
WHERE coalesce(ac.itemcode, p.itemcode) in ('abcd','xxxx','bark','home','sled','tech','bell')
有一种方法可以像ABCD = 1200一样在顶部声明它们?
表构建器声明数据。例如,
values ('abcd', '1200'), ('beef', '4321')
values
纳入查询的方法。
create temporary table alternate_codes (
itemcode text not null,
alternatecode text not null
);
insert into alternate_codes values ('abcd', '1200'), ('beef', '4321');
然后正常使用表。如果您要在一个查询中多次使用数据,这可能是最好的。
common表表达式(CTE)或
with
子句是另一个不错的选择。这就像一个用于查询的临时表。
with alternate_codes(itemcode, alternatecode) as (
values
('abcd', '1200'),
('beef', '4321')
)
SELECT
coalesce(ac.itemcode, p.itemcode) as itemcode,
price
FROM pricing p
LEFT JOIN alternate_codes ac
ON ac.alternate_code = p.itemcode
WHERE coalesce(ac.itemcode, p.itemcode) in ('abcd','xxxx','bark','home','sled','tech','bell')
对于一个查询,这是最有用的。
由于这些代码是要查询数据所必需的,因此最好是添加表并插入这些值,以便每个人都可以使用它们。甚至更好的是将您的项目代码修复查询转换为视图
,以便您可以将整个查询视为表。这将大大简化您的查询。