在Expressions SQL中的表达式

时间:2018-09-11 18:08:09

标签: sql expression field

我首先要为我的屠杀SQL道歉。新手在这里。

这是我的问题。

   SELECT Day,
    COUNT(CASE WHEN
          Shopping.Fruits Like '%1%'
            THEN
              'DewBerry'
        WHEN
          Shopping.Fruits Like '%2%'
            THEN
              'Kiwi'
         WHEN 
            Shopping.Fruits Like '%3%'
             THEN
               'Tangerine'
         ELSE
            'Inactive'
      END) AS Total, ***Total As FruitType***
    FROM Shopping
    GROUP BY Day
    ORDER BY Day desc

除了我用“ ***”括起来的内容外,其他所有方法都有效,我试图显示FruitType字段。我的尝试没有用。我觉得它有些细微的东西我正在俯视,但我似乎无法理解。

这就是我得到的 水果类型总计

Day             Total
9/11/2018 0:00  24
9/10/2018 0:00  113
9/9/2018 0:00   17
9/7/2018 0:00   62
9/6/2018 0:00   94
9/5/2018 0:00   15

任何帮助,

谢谢。...

2 个答案:

答案 0 :(得分:0)

这看起来像

  SELECT 
    Day,
    SUM(CASE WHEN Shopping.Fruits Like '%1%' THEN 1
             ELSE 0  
         END
       ) AS DewBerry_Count,
    SUM(CASE WHEN Shopping.Fruits Like '%2%' THEN 1
             ELSE 0  
         END
       ) AS Kiwi_Count,
    SUM(CASE WHEN Shopping.Fruits Like '%3%' THEN 1
             ELSE 0  
         END
       ) AS Tangerine_Count,
    SUM(CASE WHEN Shopping.Fruits NOT LIKE '%1%'
              AND Shopping.Fruits NOT LIKE '%2%'
              AND Shopping.Fruits NOT LIKE '%3%' THEN 1
             ELSE 0  
         END
       ) AS Inactive_Count
    FROM ScreeningManu
    GROUP BY Day
    ORDER BY Day desc

答案 1 :(得分:0)

这是您要做什么吗?

SELECT s.Day,
       (CASE WHEN s.Fruits Like '%1%' THEN 'DewBerry'
             WHEN s.Fruits Like '%2%' THEN 'Kiwi'
             WHEN s.Fruits Like '%3%' THEN 'Tangerine'
            ELSE 'Inactive'
       END) as FruitType,
      COUNT(*) AS Total
FROM ScreeningManu s
GROUP BY s.Day,
         (CASE WHEN s.Fruits Like '%1%' THEN 'DewBerry'
               WHEN s.Fruits Like '%2%' THEN 'Kiwi'
               WHEN s.Fruits Like '%3%' THEN 'Tangerine'
               ELSE 'Inactive'
          END)
ORDER BY s.Day DESC;