UNION in Spring data JPA native query two table - java

I have a requirement where i need to fetch number of record both the table using JPA native UNION query for Pagination
table 1=>txrh_bcaterms
table 2=> txrm_bcaterms
Ex: txrh_bcaterms UNION txrm_bcaterms
In Below code i am trying to fetching the record in both table Using UNION
#Query(nativeQuery = true,value= "SELECT "
+ " customerid, "
+ "finance_type, "
----------
-------etc----
+ "institution, "
+ "limit_groupid, "
+ "tx_booking_location, "
+ "finance_tenor_days, "
+ "margin_type , "
+ "additional_margin_percentage, "
+ "margin_percentage, "
+ "stale_document_condition_proforma_fin, "
+ "customer_name "
+ "from "
+ "txrh_bcaterms "
+ "where "
+ " institution=:institution "
+ "AND tx_booking_location=:txBookingLocation "
+ "OR finance_type=:financeType "
+ "OR customerid=:customerID "
+ "OR limit_groupid=:limitGroupID "
+ "UNION "
+ "SELECT "
+ "customerid, "
+ "finance_type, "
----------
-------etc----
+ "institution, "
+ "limit_groupid, "
+ "tx_booking_location, "
+" finance_tenor_days, "
+ "margin_type, "
+ "additional_margin_percentage, "
+ "margin_percentage, "
+ "stale_document_condition_proforma_fin, "
+ "customer_name "
+ "from txrm_bcaterms "
"
+ " institution=:institution "
+ "AND tx_booking_location=:txBookingLocation "
+ "OR finance_type=:financeType "
+ "OR customerid=:customerID "
+ "OR limit_groupid=:limitGroupID "
)
Page<Map<String,Object>> historyAndMaster(#Param("institution") String institution, #Param("txBookingLocation") String txBookingLocation,
#Param("financeType") String financeType, #Param("customerID") String customerID, #Param("limitGroupID") String limitGroupID, Pageable page);
NOTE:Actually stepid is the primary key txrh_bcaterms table and stepid is not there txrm_bcaterms table
ERROR
-------
in ui i passed institution =BC/AC/EC then UNION query able to execute and getting data
but if i passed SC then getting below exception
Caused by ERROR: each UNION query must have the same number of columns
Position: 581
at org.axonframework.axonserver.connector.ErrorCode.lambda$static$15(ErrorCode.java:107)
... 9 common frames omitted
=>If there is no same number of columns then how it is worked BC/AC/EC
I am new the Spring Data JPA Could you please help me to resolve this issue
Any other better suggestion welcome!

Related

SQLite query for ordering a list based on mistakes made

I would like to know how to query a database based on the amount of mistakes made by a waiter.
The two tables I have are
Employee
String employeeTable = "CREATE TABLE " + EMP_TABLE + " ("
+ ID_EMP + " INTEGER PRIMARY KEY, "
+ FIRST_NAME + " TEXT,"
+ LAST_NAME + " TEXT,"
+ PROFIT + " INTEGER);";
MistakeEmployee
String mistakeTable = "CREATE TABLE " + MISTAKE_TABLE + " ("
+ ID_MISTAKE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ID_WAITER_MISTAKE + " INTEGER,"
+ ID_ORDER_MISTAKE + " INTEGER,"
+ MISTAKE_TOTAL + " INITGER,"
+ " FOREIGN KEY (" + ID_WAITER_MISTAKE + ") REFERENCES " + EMP_TABLE + "(" + ID_EMP + "), "
+ " FOREIGN KEY (" + ID_ORDER_MISTAKE + ") REFERENCES " + ORDER_TABLE + "(" + ID_ORDER + "));";
I am trying to order the list based on the Employee with the most Mistakes which would be counted in the mistakes table using the ID_WAITER_MISTAKE.
String query = SELECT * , COUNT(Mistake_TABLE.ID_Waiter) as Count
FROM EMP_TABLE
ORDER BY Count DESC
You must join the tables, group by employee and aggregate:
SELECT e.ID_EMP, e.FIRST_NAME, e.LAST_NAME,
COUNT(m.ID_MISTAKE) AS Mistake_Count
FROM employeeTable e LEFT JOIN mistakeTable m
ON m.ID_WAITER_MISTAKE = e.ID_EMP
GROUP BY e.ID_EMP, e.FIRST_NAME, e.LAST_NAME
ORDER BY Mistake_Count DESC, e.ID_EMP
and in Java code you should construct the sql string like this:
String query =
"SELECT e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + ", " +
"COUNT(m." + ID_MISTAKE + ") AS Mistake_Count " +
"FROM " + EMP_TABLE + "AS e LEFT JOIN " + MISTAKE_TABLE + " AS m " +
"ON m." + m.ID_WAITER_MISTAKE + " = e." + ID_EMP + " " +
"GROUP BY e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + " " +
"ORDER BY Mistake_Count DESC, e." + ID_EMP ;
I hope there are no typos.

JDBC query returning zero when using simple arithmetic operations and alias even though the data in table is not zero

I am building a web portal through android and a query i am running through JDBC drivers is returning 0 where data should not be zero.
This is the query:
ResultSet set = statement.executeQuery("select it.itcod, it.itnam, it.packn, it.tradp, " +
"sum(nvl(itd.slbox,0) - nvl(itd.srbox,0) - nvl(itd.brbox,0) - nvl(itd.gsbox,0)) as sbox, " +
"sum(nvl(itd.slbbx,0) - nvl(itd.srbbx,0) - nvl(itd.brbbx,0) - nvl(itd.gsbbx,0)) as sbbx, " +
"SUM(NVL(itd.PRBOX,0) - NVL(itd.RPBOX,0) - NVL(itd.TRBOX,0)) as pbox, " +
"SUM(NVL(itd.PRBBX,0) - NVL(itd.RPBBX,0) - NVL(itd.TRBBX,0)) as pbbx " +
"from items it " +
"LEFT join item_daily itd " +
"on (it.cocod = itd.cocod " +
"and it.itcod = itd.itcod " +
"and ITD.ddate between " + fdate + " and " + tdate + ")" +
"WHERE IT.COCOD = " + COCOD +
"AND IT.DCODE = " + DCODE +
"AND NVL(IT.FREZE,'N')!='Y' " +
"group by it.cocod, it.itcod, it.itnam, it.packn, " +
" it.tradp, it.pkqty, it.dcode, it.freze, " +
" it.ishow, it.sltax, it.dcont, it.mcode, " +
" it.nwcod " +
"order by itnam ");
I have tried using resultsetmetadata but that does not work either.
you should be careful to this line
+ fdate + " and " + tdate
because you should use like this:
" .. to_date('"+fdate+"','***your_date_format') and to_date('"+fdate+"','***your_date_format')"

sqLite error when using update statement

I am busy using a SQLite database with a java application and after updating the database successfully I get the following error
org.sqlite.jdbc4.JDBC4PreparedStatement#4e1c6f
Below is my update code
PreparedStatement update = con.prepareStatement("UPDATE highLeaker SET " + cyc + " = "
+ dataArray[3] + " , "
+ "gasSurveyOperator" + " = "
+ dataArray[1] + " , "
+ "gasSurveySerial" + " = "
+ dataArray[2] + " , "
+ "loss" + " = "
+ dataArray[4] + " , "
+ "comment" + " = "
+ dataArray[5] + " , "
+ "cycle" + " = '"
+ cycleT + "' , "
+ "date" + " = "
+ dataArray[6]
+ " WHERE leakerID = " + dataArray[0]+";");
System.out.println(update);
update.executeUpdate();
dataRow = CSVFile.readLine(); // Read next line of data.
You printed out the object. Also, I would highly recommend using place holders instead when executing SQL queries.

Using SQlite to populate expandable list duplicating data into headers

I am trying to populate my expandable list from a SQLite DB, I got the expandable list tutorial from androidhive but it was for static data.
I got it working about 80% but now my problem is that the data gets populated under all the headers and not their unique headers. I think my problem is because all header and child data is using the same arrays and need to be unique to the headers?
What I was thinking was creating arrays dynamically with variable names but I have no idea how to do that and can't think of another way of doing this since this is my first time working with expandable lists.
Here is my code. I also have a feeling the way I am doing the nested cursors isn't the right way
String sqlQ = "SELECT Distinct "
+ "strftime('%d-%m-%Y', "+ SQLdb.DB_TIMEOPEN +") header " +
" FROM " + SQLdb.DICTIONARY_TABLE_NAME
+ " WHERE " + SQLdb.DB_PACKAGE + " = '"+ appPackage +"'"
+ " ORDER BY " + SQLdb.DB_TIMEOPEN + " ASC";
Cursor mCursor = dataBase.rawQuery(sqlQ, null);
Log.i("SQL",sqlQ);
if (mCursor.moveToFirst()) {
do {
listDataHeader.add(mCursor.getString(mCursor
.getColumnIndex("header")));
String sqlQ2 = "SELECT " + SQLdb.DB_NAME + ", "
+ SQLdb.DB_PACKAGE + ", "
+ SQLdb.DB_TIMEOPEN + ", "
+ SQLdb.DB_TIMECLOSED + ", "
+ SQLdb.DB_DURATION + ", "
+ "strftime('%d-%m-%Y', "+ SQLdb.DB_TIMEOPEN +") header " +
" FROM " + SQLdb.DICTIONARY_TABLE_NAME
+ " WHERE " + SQLdb.DB_PACKAGE + " = '"+ appPackage +"'"
+ " AND strftime('%d-%m-%Y', "+ SQLdb.DB_TIMEOPEN +") = '"+ mCursor.getString(mCursor
.getColumnIndex("header")) +"'"
+ " ORDER BY " + SQLdb.DB_TIMEOPEN + " ASC";
Cursor mCursor2 = dataBase.rawQuery(sqlQ2, null);
if (mCursor2.moveToFirst()) {
do {
listDataChildInner.add(mCursor2.getString(mCursor2
.getColumnIndex(SQLdb.DB_DURATION)));
listDataChildInnerO.add(mCursor2.getString(mCursor2
.getColumnIndex(SQLdb.DB_TIMEOPEN)));
listDataChildInnerC.add(mCursor2.getString(mCursor2
.getColumnIndex(SQLdb.DB_TIMECLOSED)));
Log.i("ACT CHILDT",mCursor.getString(mCursor
.getColumnIndex("header")) + " -> " + mCursor2.getString(mCursor2
.getColumnIndex(SQLdb.DB_TIMEOPEN)));
} while (mCursor2.moveToNext());
}
listDataChild.put(mCursor.getString(mCursor
.getColumnIndex("header")).toString(), listDataChildInner);
listDataChildO.put(mCursor.getString(mCursor
.getColumnIndex("header")).toString(), listDataChildInnerO);
listDataChildC.put(mCursor.getString(mCursor
.getColumnIndex("header")).toString(), listDataChildInnerC);
} while (mCursor.moveToNext());
}

how to find out table name after we combine some record from multiple table?

okay i have source like this
public List<SearchRecord> getResult() {
List<SearchRecord> searchResult = new ArrayList<SearchRecord>();
String query = "SELECT " + A + ", " + B+ ", " + C
+ " FROM " + TABLE_A+ " UNION ALL SELECT " + A+ ", "
+ B+ ", " + C+ " FROM " + TABLE_B + " UNION ALL SELECT " + A+ ", " + B+ ", "
+ C+ " FROM " + TABLE_C + " UNION ALL SELECT "
+ A+ ", " + B+ ", " + C+ " FROM "
+ TABLE_D;
Cursor cursor = mDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
do {
SearchRecord sr = new SearchRecord();
sr.setRecordA(cursor.getString(0));
sr.setRecordB(cursor.getString(1));
sr.setRecordC(cursor.getString(2));
searchResult.add(sr);
} while (cursor.moveToNext());
return searchResult;
}
return null;
}
with this code i can get some record from multiple table who have same column name, and store the result in a List object. but how to i find out which table is this record belongs ? is it from TABLE_A, TABLE_B, TABLE_C, or the other
As per SQL, no, you are joining 3 sets of rows and operating them the same way, each record cannot be distinguished by its origin.
Of course, you could do something like
String query = "SELECT 'TABLE_A', " + A + ", " + B+ ", " + C
+ " FROM " + TABLE_A+ " UNION ALL SELECT 'TABLE_B' " + A+ ", "
+ B+ ", " + C+ " FROM " + TABLE_B
+ " UNION ALL SELECT 'TABLE_C', " + A+ ", " + B+ ", "
+ C+ " FROM " + TABLE_C + " UNION ALL SELECT 'TABLE_D', "
+ A+ ", " + B+ ", " + C+ " FROM "
+ TABLE_D;
:-)

Categories