【问题标题】:SQL Group By in to separate result tablesSQL Group By in 以分隔结果表
【发布时间】:2016-12-19 22:33:11
【问题描述】:

我正在创建报告,我有一个如下表

EmployeeName |  Department |    Zone |

Joseph       |   IT        |    1    |

Jack         |   IT        |    3    |

John         |   IT        |    2    |

James        |   IT        |    3    |

Jashua       |   IT        |    1    |

Jingle       |   IT        |    2    |

Sam          |   HR        |    4    |

Sid          |   HR        |    5    |

Steve        |   HR        |    6    |

Sal          |   HR        |    5    |

Stephen      |   HR        |    6    |

Signa        |   HR        |    4    |

结果集应采用以下格式

Department  | Zone  

IT          | 1

EmployeeName

Joseph

Jashua



Department |    Zone

IT         |    2


EmployeeName

John

Jingle


Department | Zone

IT         | 3


EmployeeName

Jack

James



Department  |  Zone
HR          |  4

EmployeeName

Sam

Signa



Department  |  Zone

HR          |  5


EmployeeName

Sid

Sal


Department  |  Zone

HR          |  6


EmployeeName

Steve

Stephen

我怎样才能做到这一点?谢谢

【问题讨论】:

    标签: sql group-by reporting


    【解决方案1】:

    SQL 选择语句的结果始终是一个表(或单个值),但绝不是一组动态表。 我建议使用像

    这样的查询
    select department, zone, employename
    from my table
    order by department, zone
    

    在 SQL 中,由于结果是单个表,因此在部门或区域更改时不会有任何分隔符。 但是,如果您使用其他编程语言生成报告,则可以遍历结果并观察部门和区域的变化并输入水平线。

    在伪代码中,这可能如下所示:

    prevDept='';
    prevZone='';
    while (hasNextRecord()))
    {
      record = getNextRecord();
      if (prevDept <> record.department OR prevZone <> record.zone)
        writeHorizontalLine();
      prevDept = record.departnemt;
      prevZone = record.zone;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多