条件MySQL列

时间:2012-07-03 15:01:10

标签: mysql sql windows datagridview

表:qa_selltypes

selltype_code, selltype_name
'1', 'unit'
'2', 'pound'
'3', 'box'
'4', 'gallon'

表:qa_items

item_code, item_name, selltype_code, item_price
'1', 'PS2 Keyboard', '1', '10.45'
'2', 'Screws', '3', '15.02'
'3', 'Oil', '2', '30.00'

我需要根据与selltype_code字段的关系重新填充包含四个字段(单位,档位,磅,加仑)的网格建立item_price,其中一个示例:其余设置为0

DGV:

item_code, item_name, unit, box, pound, gallon
'1', 'PS2 Keyboard', '10.45', '0', '0', '0'
'2', 'Screws', '0', '0', '15.02', '0'
'3', 'Oil', '0', '30.00', '0', '0'

2 个答案:

答案 0 :(得分:3)

select i.item_code, i.item_name, 
    case when q.selltype_name = 'unit' then i.item_price else 0 end as unit,
    case when q.selltype_name = 'box' then i.item_price else 0 end as box,
    case when q.selltype_name = 'pound' then i.item_price else 0 end as pound,
    case when q.selltype_name = 'gallon' then i.item_price else 0 end as gallon
from qa_items i
inner join qa_selltypes q on i.selltype_code = q.selltype_code

答案 1 :(得分:1)

您可以使用case。例如:

select case when some_column = 'abc'
            then 'hello'
            else 'good bye'
            end as conditional_column
from your_table