我在查询时尝试清理sql表中的产品列。我的(假示例)查询如下所示:
select
Id
, Name
, ProductName
, CASE
WHEN ProductName IN ('macbook', 'dell', 'air', 'hp') THEN 'Laptop'
WHEN ProductName IN ('ipod', 'walkman', 'headset') THEN 'Music_Device'
WHEN ProductName IN ('mop', 'broom', 'sponge') THEN 'Household Utilities'
WHEN ProductName IN ('bike', 'bike_2', 'bike_3') THEN 'Bicycle'
WHEN ProductName IN ('tesla', 'ford', 'prius') THEN 'Car'
ELSE null
END AS Prod_Group
, CASE
WHEN Prod_Group IN ('Laptop', 'Music_Device') THEN 'Electronics'
WHEN Prod_Group IN ('Bicycle', 'Car') THEN 'Transportation'
WHEN Prod_Group IN ('Household Utilities') THEN 'Utilities'
ELSE null
END AS Line_of_Business
from prod_database
有没有办法引用别名列?在声明并将Laptop
更改为Electronics
等时,我是否必须重复我的整个案例?我来自R并学习SQL,所以这对我来说有点新鲜。
答案 0 :(得分:2)
在Sql Server中,我们可以使用Cross Apply
SELECT Id,
NAME,
ProductName,
cs.Prod_Group,
CASE
WHEN cs.Prod_Group IN ( 'Laptop', 'Music_Device' ) THEN 'Electronics'
WHEN cs.Prod_Group IN ( 'Bicycle', 'Car' ) THEN 'Transportation'
WHEN cs.Prod_Group IN ( 'Household Utilities' ) THEN 'Utilities'
ELSE NULL
END AS Line_of_Business
FROM prod_database
CROSS apply (SELECT CASE
WHEN ProductName IN ( 'macbook', 'dell', 'air', 'hp' ) THEN 'Laptop'
WHEN ProductName IN ( 'ipod', 'walkman', 'headset' ) THEN 'Music_Device'
WHEN ProductName IN ( 'mop', 'broom', 'sponge' ) THEN 'Household Utilities'
WHEN ProductName IN ( 'bike', 'bike_2', 'bike_3' ) THEN 'Bicycle'
WHEN ProductName IN ( 'tesla', 'ford', 'prius' ) THEN 'Car'
ELSE NULL
END) cs (Prod_Group)
答案 1 :(得分:0)
你可以参考我想的CTE ......
WITH CTE
AS
(
SELECT CASE WHEN 1>0 THEN 'A' END AS derivedCol
)
SELECT CASE WHEN derivedCol < 'B' THEN 'Pos1' ELSE 'Other' END
FROM CTE
答案 2 :(得分:0)
--could use a real table here
declare @prodTypes as table
(ProductName varchar(50),
ProductGroup varchar(50),
Line_of_Business varchar(50));
insert into @prodTypes
values ('macbook', 'Laptop', 'Electronics'),
('dell', 'Laptop', 'Electronics'),
('hp', 'Laptop', 'Electronics'),
('ipod', 'Music_Device', 'Electronics')
-- etc.
-- the results you want:
select
p.Id
, p.Name
, p.ProductName
, pt.ProductGroup
, pt.Line_of_Business
from prod_database p
left join @prodTypes pt
on p.ProductName = pt.ProductName
-- to double check your settings you can do:
select Line_of_business, ProductGroup, ProductName
from @prodTypes
order by Line_of_business, ProductGroup, ProductName