我正在尝试根据其他标志填充标题列,并且正在使用case语句来实现此目的。不幸的是我遇到结果问题。不论细节标志如何,每个主要字幕的标题都应相同。
代码:
SELECT Primary_Key, Detail_Flag, Flag_A, Flag_B,
CASE WHEN Detail_Flag=0 THEN
CASE WHEN Flag_A=1 AND Flag_B=1 THEN 1
ELSE 0 END
END AS IsCommercialFlag,
CASE WHEN Flag_A=1 AND Flag_B=1 THEN 'Yes'
ELSE 'No'
END
AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag
实际结果:
预期结果:
答案 0 :(得分:0)
似乎您只需要NULL处理。考虑到您当前正在将ORACLE用作DBMS产品,可以尝试以下查询-
SELECT
Primary_Key,
Detail_Flag,
Flag_A,
Flag_B,
CASE WHEN Detail_Flag=0 THEN
CASE WHEN NVL(Flag_A, 1) = 1 AND NVL(Flag_B, 1) = 1 THEN 1
ELSE 0 END
END AS IsCommercialFlag,
CASE WHEN NVL(Flag_A, 1) = 1 AND NVL(Flag_B, 1) = 1 THEN 'Yes'
ELSE 'No'
END
AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag
如果您使用的是MySQL,只需将NVL
替换为IFNULL
,对于SQL SERVER用户ISNULL。
答案 1 :(得分:0)
您似乎想要窗口功能:
SELECT Primary_Key, Detail_Flag, Flag_A, Flag_B,
(CASE WHEN Detail_Flag = 0 AND Flag_A = 1 AND Flag_B = 1
THEN 1
WHEN Detail_Flag = 0
THEN 0
END) AS IsCommercialFlag,
(CASE WHEN MAX(Flag_A) OVER (PARTITION BY Primary_Key) = 1 AND
MAX(Flag_B) OVER (PARTITION BY Primary_Key) = 1
THEN 'Yes'
ELSE 'No'
END) AS IsCommercialFlagCaption
FROM TableFlags
WHERE Primary_Key IN (123, 456)
ORDER BY Primary_Key, Detail_Flag;
您似乎也不了解数据库中“主键”的含义。这是 unique ,表示不重复这些值。我强烈建议您不要对具有重复值的列使用这样的名称。
答案 2 :(得分:0)
这是我一直在寻找的答案。
SELECT主键,Detail_Flag,Flag_A,Flag_B, 当Detail_Flag = 0时的情况 当Flag_A = 1和Flag_B = 1然后1时的情况 其他0结束 END AS IsCommercialFlag,
当SUM(Flag_A)超过(按PrimaryKey排序)= 1并且时 SUM(Flag_B)over(按PrimaryKey排序)= 1 THEN'是' 否则 结束 AS IsCommercialFlagCaption
FROM表标志 在哪里Primary_Key IN(123,456) ORDER BY Primary_Key,Detail_Flag