“超过4天”和“少于4天”的产品数量

时间:2017-01-31 02:02:12

标签: sql sql-server

我正在尝试学习如何在我的case语句中添加sum函数。这会计算出“超过4天”或“少于4天”的产品数量。我在Microsoft sql中使用adventureworks2014。在这里我的查询如下。

USE AdventureWorks2014;

GO

SELECT

CASE 

WHEN DAYSTOMANUFACTURE < = 4 THEN  'LESS THAN 4 DAYS'

ELSE 'MORE THAN 4 DAYS'

END AS TIMEFRAME, 

ProductID,NAME

FROM PRODUCTION.PRODUCT  

ORDER BY TIMEFRAME 

1 个答案:

答案 0 :(得分:0)

我认为您只想要GROUP BYCOUNT()

SELECT (CASE WHEN DAYSTOMANUFACTURE < = 4 THEN  'LESS THAN 4 DAYS'
             ELSE 'MORE THAN 4 DAYS'
        END) AS TIMEFRAME, 
       COUNT(*) as NumProducts
FROM PRODUCTION.PRODUCT  
GROUP BY (CASE WHEN DAYSTOMANUFACTURE < = 4 THEN  'LESS THAN 4 DAYS'
               ELSE 'MORE THAN 4 DAYS'
          END);