这是我检索数据的方式
select myPlan from myTable
这是结果,
myPlan
=====================
True , False , True
False , True , False
False , True , True
在每一行中,我有三个以逗号分隔的布尔值 第一个布尔值代表早餐,第二个是午餐,最后一个是晚餐。
我只想将结果替换为
myPlan
=====================
BreakFast , Dinner
Lunch
Lunch , Dinner
我可以仅使用sql query
进行此替换吗?
我正在使用SQL server 2008 R2
!
答案 0 :(得分:4)
由于你只有3个布尔值,你可以使用case语句来获得所有8种可能性。
SELECT
(CASE
WHEN myPlan = 'True , True , True'
THEN 'Breakfast, Lunch, Dinner'
WHEN myPlan = 'True , True , False'
THEN 'Breakfast, Lunch'
WHEN myPlan = 'True , False , False'
THEN 'Breakfast'
WHEN myPlan = 'True , False , True'
THEN 'Breakfast, Dinner'
WHEN myPlan = 'False , False , True'
THEN 'Dinner'
WHEN myPlan = 'False , True , True'
THEN 'Lunch, Dinner'
WHEN myPlan = 'False , True , False'
THEN 'Lunch'
ELSE ''
END) myPlan
FROM myTable
答案 1 :(得分:1)
您可以按如下方式使用字符串函数。
DECLARE @TEMP AS TABLE(MyPlan VARCHAR(100))
INSERT INTO @TEMP(MyPlan) VALUES ('True , False , True')
INSERT INTO @TEMP(MyPlan) VALUES ('False , True , False')
INSERT INTO @TEMP(MyPlan) VALUES ('False , True , True')
SELECT
CASE
WHEN RTRIM(SUBSTRING(MyPlan,1,5)) = 'TRUE' THEN 'BREAKFAST'
ELSE ''
END
+CASE
WHEN RTRIM(SUBSTRING(MyPlan,9,5)) = 'TRUE' THEN ',LUNCH'
ELSE ''
END
+CASE
WHEN RTRIM(SUBSTRING(MyPlan,17,5)) = 'TRUE' THEN ',DINNER'
ELSE ''
END
FROM @TEMP
答案 2 :(得分:1)
更短的解决方案:
select
decode(substr(myPlan,0,1),'T','Breakfast',null) || decode(substr(myPlan,0,1),'T',' , ',null) ||
decode(substr(myPlan,9,1),'T','Lunch',null) || decode(substr(myPlan,9,1),'T',' , ',null) ||
decode(substr(myPlan,17,1),'T','Dinner',null)
from mytable;