create-table中的case语句

时间:2012-12-26 20:15:27

标签: sql postgresql create-table

你如何使用" java if-statement"在SQL => PostgreSQL,同时创建表/列?

    CREATE TABLE Store(
           Discount INT 
                AS CASE 
         WHEN SOLD_Amount>100000 THEN 2
         WHEN SOLD_Amount>500000 THEN 5
         WHEN SOLD_Amount>1000000 THEN 10
         ELSE 0
     END       
           NOT NULL)

这可能是错误的,请告诉我们,社区如何做这种行动。

2 个答案:

答案 0 :(得分:3)

您在这里寻找的是一个计算列,Postgres不直接支持。您可以在视图中实现此功能,如下所示:

CREATE VIEW someview AS
SELECT SOLD_Amount,
     CASE 
         WHEN SOLD_Amount>100000 THEN 2
         WHEN SOLD_Amount>500000 THEN 5
         WHEN SOLD_Amount>1000000 THEN 10
         ELSE 0
     END As Discount

或者您可以使用触发器在插入/更新时填充列。

答案 1 :(得分:2)

您可以使用特殊的PostgreSQL功能:“生成”列。

基于现有表格,请说:

CREATE TABLE store (sold_amount int, ...):

您可以创建此特殊功能:

CREATE FUNCTION store_sold_amount(rec store)
  RETURNS int LANGUAGE SQL IMMUTABLE
AS
 $func$
 SELECT CASE
         WHEN rec.sold_amount > 100000 THEN 2
         WHEN rec.sold_amount > 500000 THEN 5
         WHEN rec.sold_amount > 1000000 THEN 10
         ELSE 0 END;
 $func$;

然后你可以查询:

SELECT s.amount, s.store_sold_amount
FROM   store s;

在这些相关问题下更多:
How can I create a column in postgres from values and selections based on other columns?
Store common query as column?