// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Cmplx {
    public static void main(String[] args) {
        try {
            System.out.println("Java - top customers by sales:");
            Class.forName("org.sqlite.JDBC");
            Connection con = DriverManager.getConnection("jdbc:sqlite:test.db");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customers.name,SUM(orderlines.price) AS totalsales " +
                                             "FROM customers " +
                                             "LEFT JOIN orders ON customers.customer_id = orders.customer_id " +
                                             "LEFT JOIN orderlines ON orders.order_id = orderlines.order_id " +
                                             "WHERE orders.status = 'Delivered' " +
                                             "GROUP BY customers.name " +
                                             "HAVING totalsales > 10 " +
                                             "ORDER BY totalsales DESC " +
                                             "LIMIT 3");
            while(rs.next()) {
                String name = rs.getString(1);
                int totalsales = rs.getInt(2);
                System.out.printf("%s : %d\n", name, totalsales);
            }
            rs.close();
            stmt.close();
            con.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
