在多列中排序

时间:2014-03-19 07:16:43

标签: sql postgresql sql-order-by union postgresql-9.1

我有以下表格:

 TABLE NAME    FIELD NAMES
 t1            id,group1,group2,itemname
 t2            group1id,name
 t3            group2id,name

示例数据:

T2

   group1id      name
   1             Aa
   2             AA
   3             1AC

T3

   group2id       name
   1              BB
   2              CC

T1

   id    group1    group2    itemname
   1     1         1         Abc
   2     2         1         Bca
   3     3         2         DEC

我想根据group1,group2获取itemname。我想

使用hyphon显示组名称,然后显示项目名称下面的组。

所以我试过这样:

select g1.name||'-'||g2.name grp, g1.name || ' - ' || g2.name as name from 
t2 as g1,t3 as g2,t1 i where i.group1=g1.group1id and i.group2=g2.group2id

union all

select g1.name||'-'||g2.name||'-'||itemname grp, itemname as name from 
t2 as g1,t3 as g2,t1 i where i.group1=g1.group1id and i.group2=g2.group2id
order by grp

显示输出如:

grp          Name

1AC-CC       1AC - CC
1AC-CC-dex   dex
Aa-BB        Aa - BB
AA-BB        AA - BB
AA-BB-Abc    Abc
Aa-BB-Bca    Bca

但我想:

grp          Name

1AC-CC       1AC - CC
1AC-CC-dex   dex
Aa-BB        Aa - BB
Aa-BB-Bca    Bca
AA-BB        AA - BB
AA-BB-Abc    Abc

如何更改我的订单? grp仅用于订购目的。

使用 PostgreSQL 9.1。

2 个答案:

答案 0 :(得分:1)

UNION查询中,您只能按结果中的列进行排序。但是,您需要按基表中的列进行排序。

包含所需的排序列,并将其放入最终的外部SELECT。在其中添加了一些其他改进。

SELECT grp, name
FROM  (
   SELECT g1.group1 || '-'   || g2.group2 AS grp
        , g1.group1 || ' - ' || g2.group2 AS name
        , g1.group1 , g2.group2  -- for sortting only
   FROM   group1 g1
   JOIN   items  i  USING (group1id)
   JOIN   group2 g2 USING (group2id)

   UNION ALL
   SELECT g1.group1 || '-' || g2.group2 || '-' || item AS grp
        , item AS name
        , g1.group1 , g2.group2  -- for sortting only
   FROM   group1 g1
   JOIN   items  i  USING (group1id)
   JOIN   group2 g2 USING (group2id)
   ) sub
ORDER  BY group1, group2;

grp is used for order purpose only开始,您可以进一步简化:

SELECT name
FROM  (
   SELECT  g1.group1 || ' - ' || g2.group2 AS name
         , g1.group1 , g2.group2
   FROM   group1 g1
   JOIN   items  i  USING (group1id)
   JOIN   group2 g2 USING (group2id)

   UNION ALL
   SELECT item AS name
        , g1.group1 , g2.group2
   FROM   group1 g1
   JOIN   items  i  USING (group1id)
   JOIN   group2 g2 USING (group2id)
   ) sub
ORDER  BY group1, group2

SQL Fiddle.

答案 1 :(得分:0)

您应该按原始列排序:

ORDER BY t2.name, t3.name, t1.itemname

但要清理你的问题。你混合表名和别名,这很难阅读。一些正确的格式肯定有助于理解您的查询。