problem while using database column value into Date() sqlite android - java

i have small problem, i googled it many times but i couldn't get it...
i'm using a query (sqlite) to retrieve some data ..
in this query their is Date() used to increase certain date dynamic number of days (coming from column in the same table) ..
if i put this days static (1,2,3,.....) it works fine but if i put column name it doesn't.
this query fails and i want it to work:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";
this works fine :
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "','2 day') ";
where
targetDate: date entered by user to get events of that date
DATE: date of every event in the table
REPETETIONS: dynamic number (column in the same table)
the problem is using REPETITIONS in the date function...
create statement
String SQL_CREATE_EVENT_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TITLE + " TEXT ," +
DATE + " TEXT , " +
IS_NOTIFY + " INTEGER , " +
NOTIFICATION_TIME + " TEXT ," +
REPEAT + " INTEGER ," +
REPEAT_DURATION + " INTEGER ," +
REPETITIONS + " INTEGER ," +
CERTAIN_DATE + " TEXT ," +
NOTE + " TEXT ," +
IS_SPOKEN + " INTEGER " +
" );";
and this is the selecting statement
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE " + DATE + " = '" + targetDate
+ "' OR (( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '0' ) AND " + DATE + " <= '" + targetDate + "')"
+ " OR( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '3' ) AND " + DATE + " <= '" + targetDate + "' AND " + CERTAIN_DATE + " >= '" + targetDate + "'"
+ " OR (" + REPEAT + " = '1' AND " + REPEAT_DURATION + "= '2' ) AND " + targetDate + " >= '" + DATE + "' AND "+ targetDate+ " <= date('" + DATE + "','" + REPETITIONS + " days')";

The variable REPETITIONS in this statement:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";
should be a number and not a column name.
The date function in SQLite has various syntaxes but you use this one:
SELECT date('2014-10-23','+7 day');
you must supply a number before day.
Edit try this:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "', " + REPETITIONS + " || ' day') ";

In sqlite date() function, the NNN days is a string modifier and not an expression. Therefore you cannot use column names or even || string concatenation there.
You can format the modifier string in your code and place it in the SQL. This requires additional query to the database, which is likely not what you want.
If you can assume each day is 24 hours (which is not always true, consider e.g. DST events), you could try something like
... date(strftime('%s', '" + targetDate + "', " + REPETITIONS + "*24*60*60, 'unixepoch') ...
where strftime('%s', ...) converts to seconds and date(..., 'unixepoch') converts back to datestamp.
But seriously I'd consider redesigning the schema to better support your functional requirements.

Related

CASE expression in JPQL

In my SpringBoot project I have CrudRepository with next method:
public interface LoanRequestRepository extends CrudRepository<LoanRequest, UUID> {
#Query(
value = "select " +
"lr.id as id," +
"lr.state as state," +
"lr.iban as iban," +
"lr.amount as amount," +
"lr.rate as rate," +
"lr.term as term," +
"lr.best_offer as best_offer," +
"lr.contract_number as contract_number," +
"lr.created as created," +
"lr.company_id as company_id," +
"lr.closed as closed," +
"lr.loan_colvir_id as loan_colvir_id," +
"lr.contract_date as contract_date," +
"lr.first_payment_date as first_payment_date, " +
"lr.gesv as gesv, " +
"c.id as comp_id," +
"c.name as comp_name," +
"c.bin as comp_bin," +
"c.colvir_id as comp_colvir_id," +
"c.kod as comp_kod," +
"c.type as comp_type," +
"c.location_address as comp_location_address," +
"c.registration_address as comp_registration_address," +
"c.legal_address as comp_legal_address," +
"c.actual_address as comp_actual_address," +
"c.department_code as comp_department_code," +
"c.department_name as comp_department_name," +
"c.resident as comp_resident," +
"c.created as comp_created," +
"c.registration_date as comp_registration_date," +
"c.economic_sector as comp_economic_sector," +
"c.short_name as comp_short_name," +
"c.colvir_reference_id as comp_colvir_reference_id," +
"c.card_system_id as comp_card_system_id," +
"c.initial_registration as comp_initial_registration " +
"from loan_request lr " +
"left join company c on c.id = lr.company_id " +
"where 1=1 " +
"and case when :amount is not null " +
" then lr.amount = :amount " +
" else 1=1 end " +
"and case when cast(:dateFrom as date) is not null " +
" then lr.created >= cast(:dateFrom as date)" +
" else 1=1 end " +
"and case when cast(:dateTo as date) is not null " +
" then lr.created <= cast(:dateTo as date) " +
" else 1=1 end " +
"and case when :bin is not null " +
" then c.bin like concat('%', :bin, '%') " +
" else 1=1 end " +
"and case when :companyName is not null " +
" then lower(c.name) like lower(concat('%', :companyName, '%')) " +
" else 1=1 end " +
" group by lr.id, c.id " +
"order by " +
" CASE WHEN :isAscending = true THEN :orderBy END ASC, " +
" CASE WHEN :isAscending = false THEN :orderBy END DESC " +
"limit :size offset :page;")
Iterable<LoanRequestDto> findAllLoanRequestDtoByFilters(#Param("dateFrom") LocalDate dateFrom,
#Param("dateTo") LocalDate dateTo,
#Param("bin") String bin,
#Param("amount") BigDecimal amount,
#Param("companyName") String companyName,
#Param("page") Integer page,
#Param("size") Integer size,
#Param("orderBy") String orderBy,
#Param("isAscending") Boolean isAscending);
}
All query works well, but it ignores "order by" with case expression and list comes in inordered way. I am sending values as "lr.iban", "c.name" to orderBy parameter, and if translate it to sql, it works. But in JPQL it does not work.
So, where am I wrong? How can I solve it?
Also, if change last part with CASE expression to the next:
order by CASE WHEN :isAscending = true THEN c.name END ASC
It also works, well in JPQL. List comes in ordered way.

ORA-01830: date format picture ends before converting entire input string site:community.oracle.com

Could you please help what wrong with this query when calling from Java. When I run the same query in PL/SQL developer it runs perfectly but not when i call from java,.
CRE_DTTM is in DATE datatype
String query4="SELECT NVL(SUM(cur_amt),0) FIRST_PAY" +
" FROM ci_ft ft " +
"WHERE sa_id IN "+
" (SELECT sA_id FROM ci_Sa WHERE acct_id='"+acctid.getIdValue()+"' )" +
"AND TRUNC(crE_dttm)>= (SELECT MAX(crE_Dttm) FROM ci_bill" +
" WHERE accT_id='"+acctid.getIdValue()+"' AND crE_dttm<= (SELECT add_months(To_Date('2016-03-10','YYYY-MM-DD'), -1) FROM dual ) )" +
"AND fT_type_flg IN ('PS','PX')AND ft.cRE_dttm <= (" +
" CASE" +
" WHEN ( to_Date(" +
" (SELECT MAX(crE_Dttm)" +
" FROM ci_bill" +
" WHERE accT_id ='"+acctid.getIdValue()+"'" +
" AND crE_dttm < To_Date('2016-03-10','YYYY-MM-DD')" +
" ) , 'YYYY-MM-DD') = to_Date (" +
" (SELECT MAX(crE_Dttm)" +
" FROM ci_bill" +
" WHERE accT_id='"+acctid.getIdValue()+"'" +
" AND crE_dttm<=" +
" (SELECT add_months(To_Date('2016-03-10','YYYY-MM-DD'), -1) FROM dual" +
" ) ) ,'YYYY-MM-DD'))" +
" THEN To_Date('2016-03-10','YYYY-MM-DD')" +
" ELSE" +
" ( SELECT MAX(crE_Dttm)" +
" FROM ci_bill" +
" WHERE accT_id='"+acctid.getIdValue()+"'" +
" AND crE_dttm < To_Date('2016-03-10','YYYY-MM-DD')) " +
" END)";
com.splwg.base.api.sql.PreparedStatement ps4 = createPreparedStatement(query4);
logger.info(ps4);
ps4.execute();
if(!ps4.list().isEmpty())
{
first_pay=new BigDecimal(ps4.list().get(0).get("FIRST_PAY").toString());
logger.info("first_pay=="+first_pay);
}
}
The error is:
ORA-01830: date format picture ends before converting entire input string site:community.oracle.com
Please note the PreparedStatement is from com.splwg.base.api.sql.PreparedStatement
I think you are passing different date formats in your where clause. Please try matching the date format of crE_dttm with To_Date('2016-03-10','YYYY-MM-DD')
e.g. to_date(crE_dttm, 'YYYY-MM-DD') < To_Date('2016-03-10','YYYY-MM-DD')
Thanks
Sabiha

SQL Query containing Timestamp Date comparison

I have a table - event_log which has a field in Timestamp format. Some of the example entries are - '2016-01-28 12:37:48' , '2016-01-28 15:26:51'
Now I want to write a query that will select some rows between startTime and endTime. When I fire this Query in an SQL client
SELECT Time,Data
FROM event_log
WHERE Data IN ('player disconnected','Player connected to server')
AND Player_Details_ID = '1'
AND Time > '2016-01-28 11:46:49' AND Time < '2016-02-09 14:38:39'
ORDER BY Time;
it gives me the desired output. But when I write a similar query in Java it fails to give me the result.
sqlQuery = "Select e.Time,e.Data"
+ " from event_log e "
+ "where e.Data IN ('player disconnected','Player connected to server') "
+ "and e.Player_Details_ID = '1' and "
+ "e.TIME > " + "' + startSqlDate + '" + " and e.TIME < " + "' + endSqlDate + '"
+ " order by e.Time";
Where am I going wrong?
Regardless of the values of any 'startSqlDate' and 'endSqlDate' variables you may have defined, the query submitted to the database will invariably be:
Select e.Time,e.Data from event_log e where e.Data IN ('player disconnected','Player connected to server') and e.Player_Details_ID = '1' and e.TIME > ' + startSqlDate + ' and e.TIME < ' + endSqlDate + ' order by e.Time
That is because your variables names are in the string. Change it to this:
"Select e.Time,e.Data" + " from event_log e " + "where e.Data IN ('player disconnected','Player connected to server') " + "and e.Player_Details_ID = '1' and " + "e.TIME > '" + startSqlDate + "' and e.TIME < '" + endSqlDate + "' order by e.Time"
Your 5th line should be:
+ "e.TIME > '" + startSqlDate + "' and e.TIME < '" + endSqlDate + "'"
(Provided your variables are Strings in the right format.)
Your version doesn't use your variables at all, but compiles to a static String.
"e.TIME > " + "' + startSqlDate + '" + " and e.TIME < " + "' + endSqlDate + '"
instead of this , try below
"e.TIME > '"+ startSqlDate + "' and e.TIME < '"+ endSqlDate + '"+ " order by e.Time";
In my opinion you need to write \' than '.
This should avoid some problems with strings.
Also as you can see you have variable names in string.
Something like that should work:
sqlQuery = "SELECT e.Time,e.Data"
+ " FROM event_log e "
+ "WHERE e.Data IN (\'player disconnected\',\'Player connected to server\') "
+ "AND e.Player_Details_ID = \'1\' AND "
+ "e.TIME > " + "\'" + startSqlDate + "\'" + " AND e.TIME < " + "\'" + endSqlDate + "\'"
+ " ORDER BY e.Time";

SQLite How To - Sum by Value in a JOIN

I have a sample sqlite database that currently has 7 entries which is queried via:
String selectQuery = "SELECT * FROM " + TABLE_TRANSACTIONS + " x " +
"JOIN (SELECT " + KEY_TYPE_ID + ", COUNT(*) count FROM " + TABLE_TRANSACTIONS + " GROUP BY " + KEY_TYPE_ID + " ORDER BY count DESC) y " +
"ON x.type_id = y.type_id " + //type_id vs. KEY_TYPE_ID as alias won't recognize KEY_TYPE_ID
"WHERE x.type_id = " + TagData.TYPE_EXPENSE;
The output is:
Type A = 2500
Type A = 2599
Type B = 45000
Type C = 299
Type C = 2699
Type C = 10000
Type C = 12000
which correctly groups my types by their respective values. However, the ideal output would be:
Type B = 45000
Type C = 24998
Type A = 5099
where each type is then ordered by the sum of each type. Is this possible? If so what else should I be doing in my query? I'm relatively new to SQL and haven't been able to figure this out yet. Thank you in advance for any insight.
EDIT
Based on your input #CL. I now have a more simplified query:
String selectQuery = "SELECT *, SUM(" + KEY_AMOUNT + ") AS amount_sum " +
"FROM " + TABLE_TRANSACTIONS + " " +
"GROUP BY " + KEY_LABEL_ID + " " +
"ORDER BY amount_sum DESC";
which works as expected when I use sqlfiddle at http://www.sqlfiddle.com/#!5/b3615/1 but not when I use the query in Android. In Android, only the most recent entry for each label type is returned. The SUM doesn't seem to actually do its job.
What am I missing here?
Moving the aggregation and ordering into a subquery does not make sense.
If you want to get the count of all expense transactions per type, just use a simple aggregation:
SELECT Type_ID,
COUNT(*) count
FROM TRANSACTIONS
WHERE TYPE_IF = 'TYPE_EXPENSE'
GROUP BY TYPE_ID
ORDER BY count DESC
This is an aggregation query. Fortunately, SQLite supports CTEs, so you can just do something like this:
with t as (
<your query here>
)
select type, sum(value) as sumv
from t
group by type
order by sumv desc;
Even without the with clause, you could just use your query as a subquery.
You would, of course, use the appropriate column names in the query.
#CL. Your response led me down the correct path, for those interested here is the resulting query that achieved what I was after:
String selectQuery = "SELECT " + KEY_LABEL_ID + ", " + " SUM(" + KEY_AMOUNT + ") as total, " + KEY_TYPE_ID + " " +
"FROM (" +
"SELECT " + KEY_LABEL_ID + ", " + KEY_AMOUNT + ", " + KEY_TYPE_ID + " " +
"FROM " + TABLE_TRANSACTIONS + " " +
") as trans_table " +
"WHERE " + KEY_TYPE_ID + " = " + TagData.TYPE_EXPENSE + " " +
"GROUP BY " + KEY_LABEL_ID + " " +
"ORDER BY total DESC";

How correctly address to specific column in Cursor?

Lets assume, that we have some 2 tables in SQLite: TBL_PRODUCT and TBL_PRODUCT_ALIASES. Now, I want to query some data from joined two tables:
String sql = "SELECT " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + ", " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" FROM " + TBL_PRODUCT + " LEFT JOIN " + TBL_PRODUCT_ALIASES + " ON " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + " = " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" WHERE " + C_PROD_SERVER_ID + " = ? LIMIT 1";
Cursor cursor = SQLiteDataHelper.getInstance().rawQuery(sql, new String[] {"" + js_CartProduct.getLong("prod_id")});
Thats works great without any problem. And then I want to acquire some data from the returned cursor:
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long prodId = cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID));
//... Some other code
}
Now, here is the problem: C_PROD_PKEY_ID and C_PROD_ALIASES_PKEY_ID are in the real world the same Strings: "_id". And as the result getLong() returns long not from the needed column of cursor.
How should I correctly address to the needed column? Are there other methods besides using AS in sql query OR/AND using definite numbers in cursor.getLong(0) instead of cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID))?
Update:
cursor.getColumnNames() returns this: [_id, _id].

Categories

Resources