Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 检查约束-表中的所有行,对于每个客户端_Sql_Postgresql - Fatal编程技术网

Sql 检查约束-表中的所有行,对于每个客户端

Sql 检查约束-表中的所有行,对于每个客户端,sql,postgresql,Sql,Postgresql,我有一个为客户存储类别组合的表。类别的数量可能会发生变化,但每个客户的细分必须始终小于或等于100% custom type_ pct ------- ------- ----- Cust1 Type A .33 Cust1 Type B .17 Cust1 Type C .50 Cust2 Type A .30 Cust2 Type D .10 Cust2

我有一个为客户存储类别组合的表。类别的数量可能会发生变化,但每个客户的细分必须始终小于或等于100%

custom     type_      pct  
-------    -------   -----  
Cust1      Type A    .33  
Cust1      Type B    .17  
Cust1      Type C    .50  
Cust2      Type A    .30  
Cust2      Type D    .10  
Cust2      Type E    .10  
Cust2      Type F    .50  
关于如何添加检查约束以强制执行此规则,有什么想法吗? 这是我的开始

ALTER TABLE cust_mix ADD CONSTRAINT ttl_pct_mix CHECK (SUM (pct) <= 1);  

但是,这会检查所有行,而不管客户ID是什么,仅通过添加约束是无法实现的。在insert/update之后,您需要一个触发器来在数据库端进行检查。

不确定在PostgreSQL中是否可以,因为我只使用SQL Server,但是,您实际上不必检查特定的客户Id来检查约束。您只需检查最大和是否有效。这可能有助于将其置于您的约束中

例如:

(
    SELECT TOP 1
        SUM(pct)
    FROM
        cust_mix
    GROUP BY
        custom
    ORDER BY
        SUM(pct) DESC
) <= 1

谢谢,我不认为我能做到这一点,但我必须看看这是否可行。TOP是SQL Server提供的,PostgreSQL使用LIMIT: