如何将我的cfquery分组到多个列?

时间:2012-10-18 01:24:15

标签: sql coldfusion coldfusion-8

我需要将多个列匹配的查询分组。例如,将日期,类别和描述匹配的所有行分组。我知道在对一列进行分组时如何使用cfoutput分组,例如:

<cfoutput query="myQry" group="date">
  #date#
  <cfoutput>
    #detail#
  </cfoutput>
</cfoutput>

但是,我想分组多列匹配的位置,如下所示:

<cfoutput query="myQry" group="date,category,description">
  #date# #category# #description#
  <cfoutput>
    #detail#
  </cfoutput>
</cfoutput>

我知道cfoutput分组不像上面那样工作。那么如何对多列进行分组呢?

2 个答案:

答案 0 :(得分:13)

您添加了额外的<cfoutput group="">代码。

<cfoutput query="myQry" group="date">
 <cfoutput group="category">
  <cfoutput group="description">
   #date# #category# #description#
   <cfoutput>
    #detail#
   </cfoutput>
  </cfoutput>
 </cfoutput>
</cfoutput>

答案 1 :(得分:4)

看起来你对Matt有一个答案,但是如果你对纯sql方法感到好奇:这会创建一个“虚拟”列来执行“单个”组,将结果连接回原始表,并且使用distinct来摆脱重复。丑陋,但仍然有点整洁,我认为:)

postgres=# create table myTable(col1 int, col2 int, val int);
CREATE TABLE
postgres=#
postgres=# insert into myTable values(1, 1, 1);
INSERT 0 1
postgres=# insert into myTable values(1, 2, 2);
INSERT 0 1
postgres=# insert into myTable values(1, 2, 3);
INSERT 0 1
postgres=# insert into myTable values(2, 1, 4);
INSERT 0 1
postgres=# insert into myTable values(2, 1, 5);
INSERT 0 1
postgres=# insert into myTable values(2, 1, 6);
INSERT 0 1
postgres=# insert into myTable values(2, 2, 7);
INSERT 0 1
postgres=# insert into myTable values(2, 3, 8);
INSERT 0 1
postgres=# insert into myTable values(2, 3, 9);
INSERT 0 1
postgres=# insert into myTable values(2, 3, 10);
INSERT 0 1
postgres=# insert into myTable values(2, 3, 11);
INSERT 0 1
postgres=#
postgres=# select col1, col2, count(*)\
Invalid command \. Try \? for help.
postgres-#   from myTable
postgres-#   group by col1, col2
postgres-#   order by 1, 2;
 col1 | col2 | count
------+------+-------
    1 |    1 |     1
    1 |    2 |     2
    2 |    1 |     3
    2 |    2 |     1
    2 |    3 |     4
(5 rows)


postgres=#
postgres=#
postgres=# select col1 || ',' || col2 AS theGroup
postgres-#       ,count(*) AS theCount
postgres-#   from myTable
postgres-#   group by col1 || ',' || col2
postgres-#   order by 1;
 thegroup | thecount
----------+----------
 1,1      |        1
 1,2      |        2
 2,1      |        3
 2,2      |        1
 2,3      |        4
(5 rows)


postgres=#
postgres=#
postgres=# select distinct a.col1, a.col2, b.theCount
postgres-#   from myTable a
postgres-#       ,( select col1 || ',' || col2 AS theGroup
postgres(#                ,count(*) theCount
postgres(#            from myTable
postgres(#            group by col1 || ',' || col2 ) b
postgres-#   where a.col1 || ',' || a.col2 = b.theGroup
postgres-#   order by 1, 2;
 col1 | col2 | thecount
------+------+----------
    1 |    1 |        1
    1 |    2 |        2
    2 |    1 |        3
    2 |    2 |        1
    2 |    3 |        4
(5 rows)


postgres=#