简体   繁体   中英

Select the first login time every day for each user

I try to select the first time an user has logged into the platform. Every user can enter the platform multiple times in one day, and I have a problem in selecting the first time.

Database access class:

package poin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DataBase {
    Connection conn ;
    Statement stmt; 
    List<Join> list = new ArrayList<Join>();

    public DataBase(){
        super();
    }

    public List<Join> getCard() throws Exception {

        try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
            conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;user=****;password=*******;database=********");

            stmt = conn.createStatement();

            String sql = "SELECT [Id] ,[Last Name] ,[First Name],[Field Time] FROM [******].[dbo].[Jointur] order by [Field Time]";

            ResultSet rs = stmt.executeQuery(sql);

            //STEP 5: Extract data from result set
            //rs.beforeFirst();
            //rs.next();
            //Join obj =new Join(); FAUTE CAR NOUS AVONS CR2ER UN SEUL OBJET POUR TOUTE ARRAY LIST IL FAUT ETRE A L INTERIEUR DE LA BOUCLE VOIR LA BOUCLE

             while(rs.next())
             {  
                Join obj =new Join();// 
                //Retrieve by column name
                obj.setCardHolderId(rs.getInt("ID"));

                obj.setNom(rs.getString("Last Name"));
                obj.setPrenom(rs.getString("First Name"));

                obj.setFieldTime(rs.getDate("Field Time"));
                obj.setTimestamp(rs.getTimestamp("Fiel Time"));

                list.add(obj); 
             }                     

             rs.close();
             stmt.close();
             conn.close();
          }
          catch (ClassNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          return list;
    }
}

Join class; this class contains the type of objects inserted in the ArrayList:

package poin;

import java.sql.Timestamp;
import java.util.Date;

public class Join {

    private int cardHolderId;
    private String Nom;
    private String Prenom;
    private Date fieldTime;
    private Timestamp timestamp;

    public Timestamp getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Timestamp timestamp) {
        this.timestamp = timestamp;
    }

    public Join() {
        super();
    }

    public int getCardHolderId() {
        return cardHolderId;
    }

    public void setCardHolderId(int cardHolderId) {
        this.cardHolderId = cardHolderId;
    }

    public String getNom() {
        return Nom;
    }

    public void setNom(String nom) {
        Nom = nom;
    }

    public String getPrenom() {
        return Prenom;
    }

    public void setPrenom(String prenom) {
        Prenom = prenom;
    }

    public Date getFieldTime() {
        return fieldTime;
    }

    public void setFieldTime(Date fieldTime) {
        this.fieldTime = fieldTime;
    }
}

class Test: class contains main

package poin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

public class Test {

    static Date dateDebut;
    static Date dateFin;

    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        String dateEntre = "2016-03-03";
        String dateF     = "2016-03-03";

        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); 

        dateDebut= ft.parse(dateEntre); 
        dateFin=ft.parse(dateF);

        // TODO Auto-generated method stub
        DataBase obj = new DataBase();

        List<Join> list = new ArrayList<Join>();
        List<Join> result = new ArrayList<Join>();

        try {
            list=obj.getCard();
            //iterateur pour la liste extraite de la base de donnée
            Iterator<Join> it=result.iterator();

            //gregorian calendrier
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(dateDebut);

            //dernier element de la liste: base de donnée

            Join obj2 = list.get(list.size()-1);

            // dernier identifiant de la carte dans la table
            int dernId = obj2.getCardHolderId(); 
            result.add(list.get(0));

            while(!cal.getTime().after(dateFin)){

                for (Join j : list){
                    //System.out.println(cal.getTime());
                    //Join o = it.next();
                    //boolean o2 = result.add(o);

                    if(j.getFieldTime().compareTo(cal.getTime())==0){
                        //ICI LE PROBLEME (translated: HERE IS THE PROBLEM)
                        for (Join i : result){
                            if (i.getCardHolderId() != j.getCardHolderId() && i.getFieldTime() != j.getFieldTime()) result.add(j);
                        }
                    }
                }

                cal.add(Calendar.DAY_OF_WEEK, 1);
            }

            for(Join k : list){
                System.out.println(k.getCardHolderId()+"     "+k.getNom());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

If your data are stored in relational database, it is typical better to use SQL to get the required data (and not to implement the search logic in the code).

Suppose your data are such as

        ID LAST_NAME FIRST_NAME FIELD_TIME        
---------- --------- ---------- -------------------
         1 A.        A.         01.01.2016 10:20:00 
         2 A.        A.         01.01.2016 12:22:00 
         3 A.        A.         03.01.2016 08:50:00 
         4 B.        B.         01.01.2016 15:08:00 

To get the first log per user and a day you must get the day from the datetime column (I use TRUNC which works on Oracle - adapt for your DB if required) and group on user and day calculating the MIN log time.

select  
    LAST_NAME, FIRST_NAME, trunc(FIELD_TIME) log_day,  min(FIELD_TIME) FIRST_LOG
from 
    log_time
group by 
    LAST_NAME, FIRST_NAME, trunc(FIELD_TIME)
order by 
    1, 2, 3;

The result is exact as expected, simple fetch the cursor to get the data

LAST_NAME FIRST_NAME LOG_DAY             FIRST_LOG         
--------- ---------- ------------------- -------------------
A.        A.         01.01.2016 00:00:00 01.01.2016 10:20:00 
A.        A.         03.01.2016 00:00:00 03.01.2016 08:50:00 
B.        B.         01.01.2016 00:00:00 01.01.2016 15:08:00

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