Skip to content
Advertisement

How to determine all details should go to first line item if we have multiple duplicate dates?

1)I have four fields like material no, item no, date, quantity.

Input:

   Material  item    date               quantity
    101       91    06/05/2020             4
    101       92    06/05/2020             6
    101       93    06/05/2020             4

Requirement is we need to consider date as reference

2) If date is repeated twice or n number of times , the output should goes to first item with adding quantity.

Output:

        Material  item       date            quantity
          101       91        06/05/2020           14

Advertisement

Answer

It seems you need to run the following SQL query:

SELECT `material`, `date`, MIN(item), SUM(quantity)
FROM `your_table`
GROUP BY `material`,`date`

JDBC Example:

String sql = "SELECT `material`, `date`, MIN(item) AS item, SUM(quantity) AS quantity "
           + "FROM `your_table` "
           + "GROUP BY `material`,`date`";
try (
    Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
    Statement  stmt = conn.createStatement();
    ResultSet  rs = stmt.executeQuery(sql);
) {
  while (rs.next()) {
     //Retrieve by column name
     int material = rs.getInt("material");
     Date date = rs.getDate("date");
     int item = rs.getInt("item");
     int quantity = rs.getInt("quantity");

     //Display values
     System.out.printf("%dt%st%dt%d%n", material, date, item, quantity);
  }
}

Update

If MySQL 8 is used it should be possible to use its FIRST_VALUE function to locate first item in a group.

Otherwise, the query may be rewritten to use subquery with LIMIT 1 for item:

SELECT `material`, `date`, SUM(quantity),
(
    SELECT item 
    FROM `your_table` in_tab 
    WHERE in_tab.material = out_tab.material AND in_tab.`date`=out_tab.`date` 
    LIMIT 1) AS item
FROM `your_table` out_tab
GROUP BY `material`,`date`
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement