我正在尝试编写查询以从表中选择一行(附带的屏幕截图)。这是特殊的,*
表示任何价值。我需要选择Amount
应该在开始金额和结束金额之间的行,而部门应该是IT。
Country
和Sub Department
的条件有点棘手。如果所选国家/地区不在Country
列中,则查询应该返回*
的记录,子部门也是如此。
我尝试了一种基于Department和数量选择列的方法
Select * from table_name where Department = 'IT'
and 1000 BETWEEN Start Amount AND End Amount
但是,在此之后我不知道如何以低于条件获得结果。
如果国家不是印度,那么我应该得到所有*
个结果。
答案 0 :(得分:1)
我相信你想要的东西:
SELECT *
FROM table_name
WHERE Department = 'IT'
AND 1000 BETWEEN `Start Amount` AND `End Amount`
AND country IN ('India','*')
AND `Sub Department` IN ('SD2','*')
ORDER BY country = 'India' DESC,
`Sub Department` = 'SD2' DESC
LIMIT 1
答案 1 :(得分:1)
使用union all按优先顺序将组号分配给country / sub_department的每个允许组合,即(India,SD1) (India,*) (*,*)
,然后只选择组号最小的行。
select t1.* from (
Select t1.* ,
if(@minGroup > groupNumber, @minGroup := groupNumber, @minGroup) minGroupNumber
from (
Select t1.*, 1 groupNumber from table_name t1
where Department = 'IT'
and 1000 BETWEEN `Start Amount` AND `End Amount`
and country = 'India'
and sub_department = 'SD1'
union all
Select t1.*, 2 groupNumber from table_name t1
where Department = 'IT'
and 1000 BETWEEN `Start Amount` AND `End Amount`
and country = 'India'
and sub_department = '*'
union all
Select t1.*, 3 groupNumber from table_name t1
where Department = 'IT'
and 1000 BETWEEN `Start Amount` AND `End Amount`
and country = '*'
and sub_department = '*'
) t1 cross join (select @minGroup := 3) t2
) t1 where groupNumber = @minGroup
答案 2 :(得分:0)
重新发送bcz,明星被截断
选择NVL(tc.Country,'*')Country_Column_name, NVL(tsd.Sub_Dept,'*')Sub_Dept_Column_name 来自table_name tn LEFT OUTER JOIN table_country tc ON tn.Country = tc.Country LEFT OUTER JOIN table_sub_dept tsd ON tn.Sub Dept = tsd.Sub Dept 哪个部门='IT' 和1000开始金额和结束金额
注意:国家和地区Sub Dpt表应该具有唯一列,并且应该在连接中使用。