我正在尋找構建一個過濾器組件,其中我的搜索類似于 b_cycle_type = '1st Day Of The Month'
并且在資料庫中 b_cycle_type 存盤為 -1,0,1,2,3,4,5
我如何準備 postgres 宣告
我在嘗試
SELECT "customers".* FROM "customers" WHERE (CASE customers.b_cycle_type
WHEN -1 THEN 'Last day of the month'
WHEN 0 THEN 'Align with first'
ELSE
to_char(customers.b_cycle_type, '99th') || ' Day Of The Month'
END = '27th Day Of The Month')
它沒有給我任何結果。
uj5u.com熱心網友回復:
這部分to_char(customers.b_cycle_type, '99th')實際上導致' 27th'(to_char Docs [* 6th from the bottom])所以為了解決這個問題,我將使用 TRIM 函式。
CREATE TABLE customers(
id SERIAL PRIMARY KEY,
b_cycle_type INT);
INSERT INTO customers(b_cycle_type)
SELECT * FROM generate_series(-1,30);
SELECT "customers".*
FROM "customers"
WHERE
CASE b_cycle_type
WHEN -1 THEN 'Last day of the month'
WHEN 0 THEN 'Align with first'
ELSE
TRIM(to_char(b_cycle_type, '99th')) || ' Day Of The Month'
END = '27th Day Of The Month'
例子
您可以避免使用原始 SQL,但它并不漂亮
your_variable = '27th Day Of The Month'
customer_table = Customer.arel_table
case_stmt = Arel::Case.new(customer_table[:b_cycle_type])
.when(-1).then(Arel.sql("'Last day of the month'"))
.when(0).then(Arel.sql("'Align with first'"))
.else(
Arel::Nodes::InfixOperation.new('||'
Arel::Nodes::NamedFunction.new('TRIM',[
Arel::Nodes::NamedFunction.new('to_char',
[customer_table[:b_cycle_type],Arel.sql("'99th'")])
]),
Arel.sql("' Day Of The Month'")
)
)
Customer.where(case_stmt.eq(your_variable))
uj5u.com熱心網友回復:
SELECT "customers".*
FROM "customers"
WHERE (CASE b_cycle_type
WHEN -1 THEN 'Last day of the month'
WHEN 0 THEN 'Align with first'
ELSE
CASE
WHEN "customers".b_cycle_type BETWEEN -1 AND 31
THEN trim(to_char("customers".b_cycle_type,'99th')||' Day Of The Month')
END
END = '27th Day Of The Month');
但:
- 如果
b_cycle_typecolumn 是日期,則應將 column 定義為date型別,而不是數字型別。它會讓你做的簡單where extract('day' from b_cycle_type) = 27。它還將負責驗證任何人試圖插入表中的所有資料,而無需維護自定義觸發器和約束。 - 如果出于某種原因您必須將其作為一天的偏移量,則應將其設為.
smallint或什至decimal(2,0). 此外,將其對應的實際日期另存為單獨的列,以便能夠輕松說明具有不同長度的月份,以及二月較長的閏年。 - 如果您無法更改
"customers"表結構,則無論何時處理表中的資料,都應確保b_cycle_type介于 -1 和 31 之間,并且在給定年份中給定月份的可能天數內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/523783.html
上一篇:Ruby寶石沖突
