我有tblControlFlag表,其数据如下。
我想编写一个查询,当
时输出为1 RRO_FLAG=1
AND SEAL_FLAG=1
AND TEST_CODE='VLXXXXXX'
AND SERIAL_NO='k7jpevdt'
如果任何Flag值不匹配,则查询返回空值。
直到现在,我已经尝试了Sub Query,但仍然无法实现结果。
那么这是可以实现的吗?
请帮帮我。谢谢
答案 0 :(得分:0)
使用此查询
Select Case WHEN Count(*)>0 then 1 else null END AS TesColumn From tblControlFlag when RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'
答案 1 :(得分:0)
我不清楚您的问题。不确定要如何获得结果。
无论如何
在GROUP BY
条件下使用HAVING()
。这将返回符合条件的SERIAL_NO
select SERIAL_NO
from tblControlFlag
group by SERIAL_NO
HAVING MAX(CASE WHEN FLAG_NAME = 'PRO_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'SEAL_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'TESTCODE' THEN FLAG_VALUE END) = 'VLXXXXXX'
或者如果您想要结果列1或0
select SERIAL_NO,
MATCH = CASE WHEN MAX(CASE WHEN FLAG_NAME = 'PRO_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'SEAL_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'TESTCODE' THEN FLAG_VALUE END) = 'VLXXXXXX'
THEN 1
ELSE 0
END
from tblControlFlag
group by SERIAL_NO
答案 2 :(得分:0)
由于您尝试了子查询和EXISTS,因此这是非常简单的查询,但可能无法快速运行。
SELECT COUNT(DISTINCT SERIAL_NO)
FROM @tblControlFlag AS T1
WHERE EXISTS (SELECT * FROM @tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'RRO_FLAG' AND FLAG_VALUE = '1')
AND EXISTS (SELECT * FROM @tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'SEAL_FLAG' AND FLAG_VALUE = '1')
AND EXISTS (SELECT * FROM @tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'TEST_CODE' AND FLAG_VALUE = 'VLXXXXXX')
由于每个SERIAL_NO没有重复的FLAG_NAME,因此您可以将行转换为列并执行检查RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'
SELECT *
FROM (
SELECT * FROM @tblControlFlag
) AS T
PIVOT (
MAX(FLAG_VALUE) FOR FLAG_NAME IN (RRO_FLAG, [SEAL_FLAG], [TEST_CODE])
) AS P
WHERE RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'