微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL 行变列的小应用

好久没写博客了 也好久没写代码了 拿这个充充数吧 哈哈


今天在群里看到一朋友提问

问题是截图,截图如下


用Postgresql的crosstab很快就能做出来

CREATETABLEsales
(
yearinteger,--年
monthinteger,--月
countsinteger--日
)
WITH(
OIDS=FALSE
);
ALTERTABLEsales
OWNERTOpostgres;
COMMENTONTABLEsales
IS'销售报表';
COMMENTONCOLUMNsales.yearIS'年';
COMMENTONCOLUMNsales.monthIS'月';
COMMENTONCOLUMNsales.countsIS'日';
insertintosalesvalues(1991,1,11),(1991,2,12),3,13),4,14),(1992,21),22),23),24);
CREATEEXTENSIONtablefunc;
select*fromsales;
SELECT*FROMcrosstab('selectyear,month,countsfromsalesorderby1','selectdistinctmonthfromsalesorderby1')
ASt("年"integer,"一月"integer,"二月"integer,"三月"integer,"四月"integer);

另外需要注意下crosstab这个EXTENSION需要create才可以用。


结果如下截图

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐