IF中的IF ELSE语句使用SQL查询新列?

时间:2016-10-31 11:18:25

标签: sql ms-access

我的问题是,如果sales.cost是< 100然后'特殊'否则如果sales.cost => 100'定期'

这是我的查询

SELECT 
    List.Item, List.Department, List.Group, List.Cost, 
    [Query 2].Sales, [Query 2].Revenue, special 
FROM 
    [Sales Units], List 
INNER JOIN 
    [Query 2] ON List.Item = [Query 2].Item;

最后一栏是补充,这里有更多解释。

    Special       if List.Cost
    Special      Less than 100
    Regular      100 or greater

我收了很多但是发现案例作为解决方案但是如果没有提供合适的答案我将感谢你,如果你解决了一些小难题

以下是我使用

的情况
SELECT 
    List.Item, List.Department, List.Group, List.Cost, 
    [Query 2].Sales, [Query 2].Revenue, Special,
    CASE
       WHEN [Query 2].Sales < 100 
          THEN Special = 'Special' 
       WHEN [Query 2].Sales => 100 
          THEN Special = 'Regular' 
    END
FROM 
    [Sales Units], List 
INNER JOIN 
    [Query 2] ON List.Item = [Query 2].Item
ORDER BY 
    List.Item;

4 个答案:

答案 0 :(得分:3)

MS Access不支持case。您需要使用iif()代替:

SELECT l.Item, l.Department, l.Group, l.Cost,
       q.Sales, q.Revenue,
       IIF(l.Cost < 100, 'Special', 'Regular') as special 
FROM List as l INNER JOIN
     [Query 2] as q
     ON l.Item = q.Item;

我认为您在查询中不需要[Sales Units]

在SQL Server中 - 或者其他任何数据库 - 你应该使用case而不是数据库特定的函数。

答案 1 :(得分:1)

SELECT l.Item, 
       l.Department, 
       l.Group, 
       FormatCurrency(l.Cost,2,-2,-2,-2) as Cost,
       q.Sales, 
       q.Revenue , 
       CASE WHEN l.Cost < 100 THEN 'Special'
       ELSE 'REGULAR' END AS 'Special'
FROM [List] l INNER JOIN [Query 2] q ON l.Item = q.Item;

SQL使用FORMAT(l.Cost,'C','en-us')

答案 2 :(得分:0)

非常简单:

[Special] = iif(IsNull(List.Cost, 0) < 100, 'Special', 'Regular')

答案 3 :(得分:0)

您可以像这样修改您的查询:

SELECT List.Item, List.Department, List.Group, List.Cost, [Query 2].Sales,
[Query 2].Revenue , 
CASE
       WHEN    [Query 2].Sales <  100   THEN   'Special'
       WHEN    [Query 2].Sales >= 100   THEN   'Regular' 

END as Special
FROM [Sales Units], List INNER JOIN [Query 2] ON List.Item = [Query 2].Item;

希望它有所帮助。 :)