Informix

使用字元作為總和值的 case 語句

  • May 20, 2020

我有一個表,我試圖在選擇上提取單個返回值,表示通過使用總和計算器啟用或禁用表上的壓縮,列值壓縮必須為否,並且 auto_compressed 必須等於禁用。

以下是表中的範例數據:

partnum          1048577
dbsname          rootdbs
owner            informix
tabname          sysdatabases
collate
dbsnum           1
compressed       No
auto_compressed  Disabled

partnum          1048577
dbsname          rootdbs
owner            informix
tabname
collate          TBLSpace
dbsnum           1
compressed       No
auto_compressed  Disabled

partnum          1048577
dbsname          rootdbs
owner            informix
tabname          sysdatabases
collate
dbsnum           1
compressed       No
auto_compressed  Enabled

partnum          1048577
dbsname          rootdbs
owner            informix
tabname          sysdatabases
collate
dbsnum           1
compressed       Yes
auto_compressed  Disabled

您可以使用以下內容進行測試:

create table test (
partnum         varchar(255),
dbsname         varchar(255),
owner           varchar(255),
tabname         varchar(255),
collate         varchar(255),
dbsnum          varchar(255),
compressed      varchar(255),
auto_compressed varchar(255));

insert into test values ('1048577','rootdbs','informix','','TBLSpace','1','No','Disabled');
insert into test values ('1048577','rootdbs','informix','sysdatabases','','1','No','Disabled');
insert into test values ('1048577','rootdbs','informix','sysdatabases','','1','No','Enabled');
insert into test values ('1048577','rootdbs','informix','sysdatabases','','1','Yes','Disabled');

我只想在一天結束時確定數據庫中的所有記錄是否壓縮 = 否或 auto_compressed = 禁用,然後我想要一個返回說禁用或啟用。

我把它放在一起,但我正在努力用值替換數字:

select
sum(case when Compressed != 'No' OR auto_compressed != 'Disabled' then 'Enabled' else 'Disabled' end) as Condition
from test

我在下面收到此錯誤消息:

367: Sums and averages cannot be computed for character columns.

我可以用數字替換這些值,它的工作原理如下:

select
sum(case when Compressed != 'No' OR auto_compressed != 'Disabled' then 1 else 0 end) as seven
from test

我相信我的案例陳述是不正確的,或者有更好的方法來做到這一點。我確實需要幫助,因為此時我的想法令人難以置信。

測試

SELECT CASE SUM(CASE WHEN Compressed = 'Yes' AND auto_compressed = 'Compressed'
                    THEN 1 
                    ELSE 0 
                    END)
      WHEN 0 THEN 'Disabled'
      ELSE        'Enabled'
      END AS Condition
FROM test

我看到這也有效:

select 
case when seven > 0 then 'Enabled' else 'Disabled' end) as Compression
from (
select
sum(case when Compressed != 'No' OR auto_compressed != 'Disabled' then 1 else 0 end) as seven
from test
) a

引用自:https://dba.stackexchange.com/questions/267510