java - 当我使用 GROUP BY 组合值时,如何显示 SQL 表中的更改?

标签 java mysql sql swing jtable

我有一个名为 Store_Data 的数据库表,并且在 JTable 中显示了三列。

以下是各列:

  1. 数字

  2. 金额

  3. 日期

如何显示 jtable 中的其他列?其他列缺失

enter image description here

我设法使用此 SQL 命令“SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS”获取组合值,并设法将其显示在 JTable 中。

但是,在 JTable 中,我只看到 NUMBERS 列和显示所有 AMOUNT 值总和的另一列。我在 Jtable 中没有看到其他列。

enter image description here

这是我的代码,

private JTable showRecords(Connection con)
{

    try
    {
        column.clear();
        data.clear();

        _stmt = con.createStatement();

        //String getColumn = "SELECT * FROM APP.NYPMTRIPLESTRAIGHT";

        /*this is only a test*/
        String test = "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS";

        ResultSet rs = _stmt.executeQuery(test);

        //this will collect the data from the database
        ResultSetMetaData metaData = rs.getMetaData();

        //this will count all the columns from 
        int column_count = metaData.getColumnCount();
        for(int j = 1; j <= column_count; j++)
        {
            column.add(metaData.getColumnName(j));
        }

        while(rs.next())
        {

            Vector<Object> vector = new Vector<Object>();

            for(int i = 1; i <= column_count; i++)
            {
                vector.add(rs.getObject(i));
            }

            data.add(vector);
        }

        _records = new JTable(data, column);

        return _records;

    } catch (SQLException ex) 
    {
        JOptionPane.showMessageDialog(null, ex.getMessage());
    }

    return _records;
}  

注意:我知道使用 Vector 是错误的。我只是用它来测试。

最佳答案

您的查询对 AMOUNT 的所有值求和,并使用 Group by 子句显示总和。

分组依据将根据所使用的函数将相似的值分组到一个实体中。 [在你的情况下是“总和”]。

您只需从数据库中获取数字和金额

SELECT NUMBERS, AMOUNT FROM APP.NYPMTRIPLESTRAIGHT;

然后在 JTable 中显示结果集数据。

关于java - 当我使用 GROUP BY 组合值时,如何显示 SQL 表中的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720684/

相关文章:

java - 在java代码中嵌入数据文件

java - Java 中的 "implements Runnable"与 "extends Thread"

mysql - Pentaho如何连接外部服务器的mysql生成报表

c# - 无法解决代码级别统一的 "SQL_Latin1_General_CP1_CI_AI"和 "Latin1_General_CI_AI"之间的排序规则冲突

sql - postgres DB 中的 Concat 列数据

java - 该模块不能是 Android 库?

java - Neo4j 在同一查询中删除/设置标签和属性

php - 向 Facebook API 发布状态,帮助 :(

mysql - 在sql查询中返回列名

mysql - SQL从另一个表返回带有图片计数的用户列表