无法创建唯一聚簇索引对于Indexed视图,在Aggregation中使用case语句时

时间:2018-04-06 08:47:27

标签: sql-server

当我执行以下SQL语句

CREATE VIEW sales.products_value
  WITH SCHEMABINDING
  AS
    (SELECT
       p.id         AS product_id,
       CASE
       WHEN sum(ov.value) > 99
         THEN 99
       ELSE sum(ov.value)
       END          AS margin_perc,
       COUNT_BIG(*) AS count
     FROM sales.products p
       JOIN sales.orders o ON p.id = o.product_id
       JOIN sales.order_value ov ON ov.id = o.order_value_id
     GROUP BY p.id
    );
GO ;
CREATE UNIQUE CLUSTERED INDEX IDX_product_id
  ON sales.products_value (product_id);
GO ;

我收到以下错误

  

无法创建聚集索引' IDX_product_id'在view' sales.products_value'因为视图的选择列表包含聚合函数或分组列结果的表达式。考虑从聚合函数的结果中删除表达式或从选择列表中分组列。

谁能告诉我我做错了什么?并解释为什么会这样。

1 个答案:

答案 0 :(得分:2)

您无法在索引视图中操作聚合函数结果。你应该返回普通的聚合结果。

CREATE VIEW sales.products_value
  WITH SCHEMABINDING
  AS
    SELECT
       p.id         AS product_id,
       sum(ov.value) AS TotalSum,
       COUNT_BIG(*) AS count
     FROM sales.products p
       JOIN sales.orders o ON p.id = o.product_id
       JOIN sales.order_value ov ON ov.id = o.order_value_id
     GROUP BY p.id

然后创建索引

CREATE UNIQUE CLUSTERED INDEX IDX_product_id ON sales.products_value (product_id);

如果您需要扭曲结果,可以创建辅助视图。

CREATE VIEW sales.products_value_with_perc WITH SCHEMABINDING
AS
    SELECT
        T.product_id,
        CASE WHEN T.TotalSum > 99 THEN 99 ELSE T.TotalSum END AS margin_perc,
        T.count
    FROM
        sales.products_value AS T

正如Damien建议的那样,在访问此视图时应使用表提示NOEXPAND,这样它就不会尝试转到基础表(绕过材质索引)。

SELECT * FROM sales.products_value_with_perc WITH (NOEXPAND)