根据此查询,我缺少了什么:
SELECT mymonth, Header1 FROM ( SELECT month(startdatetime) as mymonth, (CASE WHEN MyTable.somecolumn =2 THEN count(somecolumn2) END) as Header1 FROM MyTable WHERE year(startdatetime)=2013 group by startdatetime ) x GROUP BY Header1
我在某个地方表示Informix不支持按别名分组,但是在尝试设置GROUP BY 2时出现了红色错误,列标题1也必须位于Group by子句中
您的SQL非常不寻常。Informix服务器对于CASE表达式是否是一个聚合表达式感到困惑-我也是。
SELECT mymonth, Header1 FROM (SELECT MONTH(startdatetime) AS mymonth, COUNT(somecolumn2) AS Header1 FROM MyTable WHERE YEAR(startdatetime) = 2013 AND SomeColumn = 2 GROUP BY startdatetime ) AS x -- GROUP BY Header1; ;
我没有看到(注释掉)外层GROUP BY子句的理由。给定以下测试数据:
CREATE TEMP TABLE MyTable ( startdatetime DATE NOT NULL, somecolumn INTEGER NOT NULL, somecolumn2 VARCHAR(10) ); INSERT INTO MyTable VALUES('2013-03-01', 2, NULL); INSERT INTO MyTable VALUES('2013-03-02', 2, 'Elephant'); INSERT INTO MyTable VALUES('2013-03-03', 2, 'Rhinoceros'); INSERT INTO MyTable VALUES('2013-03-04', 1, 'Elephant'); INSERT INTO MyTable VALUES('2013-03-05', 3, 'Rhinoceros');
查询的输出是:
mymonth header1 SMALLINT DECIMAL(15,0) 3 0 3 1 3 1
但是,我怀疑您已经做了一些查询最小化来说明问题(如果是,谢谢),实际上您的主子查询将具有一些类似的CASE表达式,而不仅仅是一个。在这种情况下,您应该按照以下方式重写CASE表达式和聚合:
SELECT mymonth, Header1 FROM (SELECT MONTH(startdatetime) AS mymonth, COUNT(CASE WHEN MyTable.somecolumn = 2 THEN somecolumn2 END) AS Header1 FROM MyTable WHERE YEAR(startdatetime) = 2013 GROUP BY mymonth ) AS x ;
对于相同的样本数据,将产生:
mymonth header1 SMALLINT DECIMAL(15,0) 3 2
假设您使用的是IBM Informix 11.50而不是11.70或12.10,则可能必须对此使用变体才能完成聚合:
SELECT MonthNum, COUNT(Header1) AS Header1 FROM (SELECT MONTH(startdatetime) AS MonthNum, CASE WHEN MyTable.somecolumn = 2 THEN somecolumn2 END AS Header1 FROM MyTable WHERE YEAR(startdatetime) = 2013 ) x GROUP BY MonthNum;
输出:
monthnum header1 SMALLINT DECIMAL(15,0) 3 2
基本思想是使用CASE表达式在子查询的Header1列中生成所需的值,然后将聚合应用于子查询的结果(而不是在子查询中进行聚合)。我尚未验证它是否可以在11.50中工作(在11.70.FC6中也可以),但是很有可能。