我是Sql的新手。我有两个表,如果基于第一个表中的字段的条件错误,我需要从第二个表中获取数据:
第一张表
(SELECT branch, division, position_code, emp_code,
div_brand, div_brand_targets_t2
FROM sas_provBrand_targets
) TRGT
然后我需要根据Select
的值从第二个表格中制作TRGT.div_brand
,如下所示:
IF TRGT.div_brand IN ('Other', 'HPC1', 'HPC2')
THEN
{
Brand = null
Category = null
Subcategory = null
}
ELSE
{
(SELECT DISTINCT BRAND, REP_BRAND, category, rep_category,
sub_category, SUB_CATEGORY_DESCRIPTION
FROM masterdata.dbo.inventory_item
WHERE sub_category = TRGT.div_brand
) BRNDNAME
}
最后,我需要在前端显示以下数据
SELECT DISTINCT TRGT.branch BRANCH, TRGT.division DIVISION, TRGT.POSITION_CODE POSITION,
TRGT.emp_code SALESMAN, BRNDNAME.brand + ' - ' + BRNDNAME.rep_brand BRAND, BRNDNAME.category + ' - ' + BRNDNAME.rep_category CATEGORY, BRNDNAME.sub_category + ' - ' + BRNDNAME.SUB_CATEGORY_DESCRIPTION SUBCATEGORY, TRGT.div_brand_targets_t2 BRANDT2
表结构(请注意,它们是联合关系表) sas_provBrand_targets表
yr: numeric(4, 0)
mnth: numeric(2, 0)
branch: char(4)
division: char(4)
position_code: numeric(3, 0)
emp_code: char(5)
div_brand: varchar(25)
div_brand_targets_t2: numeric(15, 2)
masterdata.dbo.inventory_item
division: char(6)
brand: char(5)
rep_brand: varchar(40)
category: char(6)
rep_category: varchar(40)
sub_category: char(8)
SUB_CATEGORY_DESCRIPTION: varchar(20)
答案 0 :(得分:0)
首先,当谈到SQL思考集理论时,不是逐行操作。 实现您想要的结果集的技巧是加入所有内容。
SELECT CASE WHEN TRGT.div_brand IN ('Other', 'HPC1', 'HPC2') THEN NULL ELSE BRNDNAME.BRAND END AS BRAND
FROM sas_provBrand_targets TRGT
LEFT/INNER>?? JOIN
(SELECT DISTINCT BRAND, REP_BRAND, category, rep_category,
sub_category, SUB_CATEGORY_DESCRIPTION
FROM masterdata.dbo.inventory_item
WHERE
) BRNDNAME ON sub_category = TRGT.div_brand
为每个列重复case语句,并将所需的列/格式添加到主选择
中