该列应包含: 计数= 0的“无订单”计数= 1的“一次性”计数范围2-5的“常规”计数范围6-10的“经常”计数大于10的“忠诚”
下面是查询,在这里我无法使用其他条件,例如“大于范围”
SELECT c.CustomerID, c.TerritoryID,
COUNT(o.SalesOrderid) [Total Orders],
CASE COUNT(o.SalesOrderid)
WHEN 1
THEN 'One Time'
WHEN 0
THEN 'No Order'
ELSE 'None'
END AS [Frequency]
FROM Sales.Customer c
LEFT OUTER JOIN Sales.SalesOrderHeader o
ON c.CustomerID = o.CustomerID
WHERE DATEPART(year, OrderDate) = 2007
GROUP BY c.TerritoryID, c.CustomerID;
答案 0 :(得分:2)
您可以使用documentation中所述的搜索格式,而不是简单的CASE
表达式,如下例所示。另外,我建议您避免将DATEPART
函数应用于OrderDate
中的WHERE
并按如下所示进行重构,以便表达式可修改,从而可以有效地使用索引。
SELECT
c.CustomerID
, c.TerritoryID
, COUNT(o.SalesOrderid) [Total Orders]
, CASE
WHEN COUNT(o.SalesOrderid) = 0 THEN 'No Order'
WHEN COUNT(o.SalesOrderid) = 1 THEN 'One Time'
WHEN COUNT(o.SalesOrderid) BETWEEN 2 AND 5 THEN 'Regular'
WHEN COUNT(o.SalesOrderid) BETWEEN 6 AND 10
THEN 'Often'
ELSE 'Loyal'
END AS [Frequency]
FROM Sales.Customer c
LEFT OUTER JOIN Sales.SalesOrderHeader o
ON c.CustomerID = o.CustomerID
WHERE OrderDate >= '20070101' AND OrderDate < '20080101'
GROUP BY c.TerritoryID, c.CustomerID;