1

我正在尝试对 SQL Server 2012 进行分类(查看SQL Fiddle演示)

但是,当我引入子查询时,它检索到以下消息:“子查询返回超过 1 个值。当子查询遵循 =、!=、<、<=、>、>= 或使用子查询时,这是不允许的作为表达

我应该改用什么脚本?

编辑:我希望有以下输出,基于 SQL Fiddle 演示:

CATEGORY    REGION    PRECIO    CATEGORY
Pepe         Paris      21        Other
Pizza        Paris      21        Pizza
Pizza        Paris      22        Pizza
Salad        Paris      22        Other
Beverage    Vidreres    20       Beverage   
Beverage    Vidreres    24       Beverage   
Pizza       Vidreres    19        Pizza
Pizza       Vidreres    20        Pizza 

提前致谢。

4

4 回答 4

3

添加计数(请停止更改要求)。为避免重复代码,您可以CASE在 CTE 中执行表达式(也可以使用派生表)。

;WITH x AS 
(
  SELECT Category, Region, Precio, 
    Products = CASE WHEN Category IN ('Pizza','Beverage')
      THEN Category ELSE 'Other' END
  FROM dbo.supportContacts
)
SELECT Category, Region, Precio, Products,
  ProductCount = COUNT(*) OVER (PARTITION BY Products)
FROM x;

SQL小提琴演示

于 2013-04-12T13:42:41.210 回答
2

尝试这个。

SELECT *, case
            when Category = 'Pizza' then 'Pizza'
            when Category = 'Beverage' then 'Beverage'
            else 'Other' end as Products

 FROM supportContacts
Group by Region, Category, Precio
于 2013-04-12T13:32:33.230 回答
2

你不需要子查询

SELECT *, case
      when Category = 'Pizza' then 'Pizza'
          when Category = 'Beverage' then 'Beverage'
       else 'Other' end as Products
 FROM supportContacts
Group by Region, Category, Precio

输出:

| CATEGORY |   REGION | PRECIO | PRODUCTS |
-------------------------------------------
|     Pepe |    Paris |     21 |    Other |
|    Pizza |    Paris |     21 |    Pizza |
|    Pizza |    Paris |     22 |    Pizza |
|    Salad |    Paris |     22 |    Other |
| Beverage | Vidreres |     20 | Beverage |
| Beverage | Vidreres |     24 | Beverage |
|    Pizza | Vidreres |     19 |    Pizza |
|    Pizza | Vidreres |     20 |    Pizza |

SQLFiddle

于 2013-04-12T13:32:47.027 回答
1

我认为您编写该查询以获得以下结果...

在此处输入图像描述

如果我得到你然后尝试下面的查询..

Select Category, Region, Precio,Products,count(Products) _Count from
(Select Category, Region, Precio,
case
        when Category = 'Pizza' then 'Pizza'
        when Category = 'Beverage' then 'Beverage'
        else 'Other' 
end as Products 
FROM supportContacts) res
Group by Category,Region,Precio,Products
于 2013-04-12T13:34:40.537 回答