简体   繁体   中英

How do I show changes in my SQL table when I combined the values using GROUP BY?

I have this database table named Store_Data and I show three columns in the JTable.

Here are the columns:

  1. NUMBERS

  2. AMOUNT

  3. DATE

How do I show the other columns in the jtable? The other columns are missing

在此处输入图片说明

I managed to obtain combined values using this SQL command, "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS", and I managed show it in the JTable.

However, In the JTable I only see the column NUMBERS and another column showing all the sum of the AMOUNT values. I don't see the other columns in the Jtable.

在此处输入图片说明

Here is my code,

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;
}  

NOTE: I know it is wrong to use Vector. I am only using it for testing.

Your query sums all the values of AMOUNT and displays the sum using a Group by clause.

Group by will group similar values into one entity based on the functions used. ["sum" in your case].

You need to get the numbers and amount from your database simply

SELECT NUMBERS, AMOUNT FROM APP.NYPMTRIPLESTRAIGHT;

then display the resultset data in your JTable.

Try this:

SELECT 
  t1.NUMBERS, 
  CONCAT(YEAR(T1.DATE) , '-' , MONTH(t1.DATE) , '-' ,DAY(t1.DATE)) as DATE, 
  SUM(AMOUNT) AS AMOUNT 
FROM table1 t1 
GROUP BY 1, 2

And here you have the sqlfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM