在crosstab()函数中使用ORDER BY

沙沙语

架构名称:"C_GT_Master""C_GT_Master"我的表名是items两种模式都有相同的表。

领域:itemnoitemnameunitno

我想从items两种模式的表中获取详细信息我正在使用以下代码:

SELECT stckreport.* FROM public.crosstab('select itemname, ''GT'' anal,
itemno from  "C_GT_Master".items i 
union all 
select itemname, ''UnitNo'' anal,unitno from  "C_GT_Master".items i 
union all 
select itemname, ''New'' anal,itemno from  "G_New_Master".items i  
union all 
select itemname, ''UnitNo'' anal,unitno from  "G_New_Master".items i 
','select ''GT'' union all select ''New'' union all select ''UnitNo''') 
as stckreport 
(itemname text,GT text,New Text,UnitNo text)

该查询返回:

 itemname  gt  new unitno
   AB           1    
   AB                1
   AB       1          
   AB                2

但我想要:

itemname  gt   new  unitno
 AB             1    1
 AB       1          2

如何使用来获得该结果crosstab()我在项目中真正遇到的问题太大,因此我使用此表进行解释。

我正在使用PostgreSQL 9.1。

欧文·布兰德斯特(Erwin Brandstetter)

如果我正确理解并且您希望每个架构一行,则此修改后的crosstab()查询应该可以工作:

SELECT  "schema", itemname, "GT", "New", "UnitNo"
FROM    public.crosstab($$
    SELECT 'c' || itemname, "C_GT_Master" AS sch, itemname
        , 'GT'::text AS anal, itemno FROM "C_GT_Master".items
    UNION ALL 
    SELECT 'c' || itemname, "C_GT_Master",  itemname
       , 'UnitNo', unitno FROM  "C_GT_Master".items
    UNION ALL 
    SELECT 'g' || itemname, "G_New_Master", itemname
        , 'New'   , itemno FROM  "G_New_Master".items
    UNION ALL 
    SELECT 'g' || itemname, "G_New_Master", itemname
        , 'UnitNo', unitno FROM  "G_New_Master".items
   ORDER BY 1$$

    ,$$VALUES ('GT'::text), ('New'), ('UnitNo')$$
   ) 
AS stckreport (
   item text, "schema" text, itemname text
 , "GT" text, "New" text, "UnitNo" text);

要点

  • 添加ORDER BY 1第一个查询字符串。那是你的主要错误。

  • 我将架构的哈希值连接到,itemname以将其组合为一个值,以使每行产生一行(schema, itemname)此外,我添加了模式,并itemname分别将其包含在结果中。仅选择外部的那些SELECT进行显示。有关“附加列”的更多详细信息:
    使用Tablefunc在多个列上进行枢轴
    连接以及有关连接行名称的操作:
    具有2个(或更多)行名称的交叉表

  • 使用美元报价可以使您的生活更轻松。

  • VALUES为第二个查询字符串使用一个表达式。

  • 更多基本信息,请参见crosstab()
    PostgreSQL交叉表查询

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章