我试图在T-SQL中创建条件列,例如if语句,但我不想打印字符串,而是希望它从数据集中的另一列中提取数据。
SELECT
CASE
WHEN NameDay = 'Sunday'
THEN [sales]
ELSE [SunAdj]
END AS AdjustedDays
FROM
Table
如果[sales]
列中的日期为“星期日”,我基本上希望它从NameDay
列中提取数据,否则从[SunAdj]
中提取数据。我可以使用它填充字符串,而不填充其他列的数据。这可能吗?如果可以,怎么办?任何帮助将非常感激。
Product category Sales SunAdj NameDay
--------------------------------------------------
Meat 1000 3500 Sunday
Fish 1000 3500 Wednesday
Bakery 1000 3500 Friday
我想要另一列AdjustedDays
,第一行显示1000,其他行显示3500。
答案 0 :(得分:0)
这是问题数据的快速CTE设置:
SELECT MAX(DOC) AS DOC, 'D' AS LNTY
FROM TABLE_1
WHERE LNTY = 'D'
UNION ALL
SELECT MAX(DOC) AS DOC, 'D' AS LNTY
FROM TABLE2
WHERE LNTY = 'D'
我们可以用它来表明您的陈述已经正确:
; with sourceData (Product, Category, Sales, SunAdj, NameDay)
as
(
select 'Meat', null, 1000, 3500, 'Sunday'
union select 'Fish', null, 1000, 3500, 'Wednesday'
union select 'Bakery', null, 1000, 3500, 'Friday'
)
...
只需为我的答案增加一点价值,您就可以使用; with sourceData (Product, Category, Sales, SunAdj, NameDay)
as
(
select 'Meat', null, 1000, 3500, 'Sunday'
union select 'Fish', null, 1000, 3500, 'Wednesday'
union select 'Bakery', null, 1000, 3500, 'Friday'
)
select
Product, Category, Sales, SunAdj, NameDay,
CASE when NameDay = 'Sunday' then [sales]
else [SunAdj] end as AdjustedDays
from sourceData
函数来实现相同的目的:
IIF
两个查询的结果相同:
; with sourceData (Product, Category, Sales, SunAdj, NameDay)
as
(
select 'Meat', null, 1000, 3500, 'Sunday'
union select 'Fish', null, 1000, 3500, 'Wednesday'
union select 'Bakery', null, 1000, 3500, 'Friday'
)
select
Product, Category, Sales, SunAdj, NameDay, iif(NameDay='Sunday', SunAdj, Sales) AdjustedDays
from sourceData