问题描述
- SQL语句统计问题,不想写union all
-
建表测试语句:CREATE TABLE stbuu_cause109_20160331 (
intenbid BIGINT,
intrsrp00 BIGINT,
intrsrp01 BIGINT,
intrsrp02 BIGINT,
intrsrp03 BIGINT,
intrsrp04 BIGINT,
intrsrp05 BIGINT,
intrsrp06 BIGINT
);
插入测试数据:INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,1,0,0,0,0,0,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,1,0,0,0,0,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,0,1,0,0,0,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,0,0,1,0,0,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,0,0,0,1,0,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,0,0,0,0,1,0);
INSERT INTO stbuu_cause109_20160331(intenbid,intrsrp00,intrsrp01,intrsrp02,intrsrp03,intrsrp04,intrsrp05,intrsrp06) values(1110,0,0,0,0,0,0,1);select * from stbuu_cause109_20160331;
需要实现的效果
结果语句是:
select intenbid,-141 as rsrp,sum(intrsrp00) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-140 as rsrp,sum(intrsrp01) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-139 as rsrp,sum(intrsrp02) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-138 as rsrp,sum(intrsrp03) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-137 as rsrp,sum(intrsrp04) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-136 as rsrp,sum(intrsrp05) countt from stbuu_cause109_20160331 group by intenbid UNION all
select intenbid,-135 as rsrp,sum(intrsrp06) countt from stbuu_cause109_20160331 group by intenbid ;目前这种实现方式不靠谱,intrsrp00-99个字段,sql写99个union all 语句会内存溢出,求大神解答,谢谢
解决方案
数据库用的Postgresql
解决方案二:
SQL语句之Union和Union All
sql语句中的union和union all
SQL语句 UNION 和 UNION ALL 使用(一)