I want to write a time check. That is 1 customer can't deposit more than 5 times 1 days. I just wrote this to check:
SELECT CUSTOMERID
FROM TRANSACTIONS
WHERE (SELECT DATEPART(HOUR,GETDATE())) BETWEEN ((SELECT DATEPART(HOUR,GETDATE()))-24) AND (SELECT DATEPART(HOUR,GETDATE()))
AND METHODID = 1
AND CUSTOMERID = 8
To count customer and check if >5 return false. But i think it's wrong. Anyone help me the query about hour and date ( Column Date is DATETIME type)
Here the image of my table.
As per my understanding, You have a customer ID and wanna check the number of transaction in a day of that customer and allow it for the transaction if count is less than 5. So try the following query.(Query will return "true" if transactions<5 else "false").
select case when count(*) < 5 then 'True' else 'False' end from [YOUR_TABLE_NAME]
where CUSTOMERID = 8
and cast([YOUR_DATE_COLUMN_NAME] as date)=cast(GETDATE() as date)
You need aggregate function count, group by clause and case when for checking
If your dbms is Mysql then below query will help you
select customerid,date(date) as date_of_month,
case when count(transactionid)>5 then 'false' else 'True'
from TRANSACTIONS
group by customerid,date(date)
If your dbms is mssql server
select customerid,convert(date,[date]) as date_of_month,
case when count(transactionid)>5 then 'false' else 'True'
from TRANSACTIONS
group by customerid,convert(date,[date])
Related
How can I update with one query?
I want to do something like this:
update customer
set balance = (400,150) where customer_id IN ('2','3');
customer 2 will get a new balance of 400 and customer 3 will get 150.
I want 1 query because I'm using spring-boot, JPA
#Modifying
#Query("update customer set balance = (400,150) where customer_id IN ('2','3');")
Can I do here 2 queries? for each customer?
what is recommended? what is acceptable?
thanks.
You can do by this way -
Update customer
SET balance = (case when customer_id = '2' then '400'
when customer_id = '3' then '150'
end)
WHERE
customer_id IN ('2','3');
The CASE statement may be what you are looking for.
UPDATE customer
SET balance = (case
when customer_id = 1 then 150
when customer_id = 2 then 300
end)
WHERE ID in (1,2);
If your customer_id is of type string, add quotes to the customer_id numbers.
My example is just a modified version of:
Example Code:
UPDATE students
SET JavaScore = (case
when ID = 1 then 75
when ID = 2 then 80
when ID = 3 then 86
when ID = 4 then 55
end),
PythonScore = (case
when ID = 1 then 70
when ID = 2 then 85
when ID = 3 then 94
when ID = 4 then 75
end)
WHERE ID in (1,2,3,4);
From this website:
DelftStack
Hibernate can do this for you, no need to write your own query.
The steps.
Set hibernate.jdbc.batch_size to some reasonable size.
Enable insert/update query ordering
Enable statement rewrites for MySQL (set rewriteBatchedStatements to true)
In your application.properties add the following
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
# spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true # Needed when using versioned data
spring.datasource.hikari.dataSourcePoperties.rewriteBatchedStatements=true
See also this and this for a bit more background.
Now in your code you can just update and save your customers and the database will receive only 1 query.
if you want to use the spring-data way, you have to use complex SQL/JPQL as less as possible.
#Entity
class CustomerEntity {
}
#Modifying
#Query("update CustomerEntity customer set customer.balance = :balance where customer.id = :customerId")
int updateCustomerBalance(#Param("customerId") String customerId, #Param("balance") String balance);
customerRepository.updateCustomerBalance("2", "400");
customerRepository.updateCustomerBalance("3", "150");
Common transaction
if you want to update happens in one transaction
#Transactional
void doUpdate() {
customerRepository.updateCustomerBalance("2", "400");
customerRepository.updateCustomerBalance("3", "150");
}
Keep in mind that you have to call service.doUpdate() from outside. if you call the method from another service method, transaction will not be created.
Check that update has happened
int count = customerRepository.updateCustomerBalance("2", "400");
if (count == 0) {
log.error("Customer not updated customerId=2 customerBalance=400");
}
My server would retrieve the latest ID from the database, now it is stuck and keeps returning the id 99999, even though the latest id is now 100040
My code is:
String insertTable = "SELECT * FROM dutyofcare ORDER BY Id DESC LIMIT 1";
ps = conn.prepareStatement(insertTable);
rs = ps.executeQuery();
String ResultS = "";
if (rs.next()) {
ResultS += rs.getString("Id");
}
The issue is that the ORDER BY in your query is doing a lexical (character-by-character) sort where 9 always comes after 1, and not numeric sort which handles the digit positions. This is because of the column type of ID. What you need is to ensure ID is a number before the sort is done.
Either change your ID to a numeric column type and run below query:
SELECT MAX(ID) from dutyofcare;
Or if you want to retain your column type (less efficient than above option):
select MAX(cast(ID AS UNSIGNED)) from dutyofcare;
Or if you want to retain your column type AND just fix your existing query (least efficient of all the options)
select * from dutyofcare order by CAST(ID AS UNSIGNED) desc limit 1;
All these methods basically treat the ID as number and choose the biggest value.
How can I limit the number of rows in an Android room database by removing the oldest item in the row and inserting the newest one?
I am guessing its a standard query when adding an item to the database?
EDIT: I want to limit a database table to have a max row count of say 20. If that limit is reached, we remove the oldest item and insert the new one by keeping the current row count to 20.
I think you can insert the data into your table then remove all the rows except last 20 (limit)
To delete you can use the following query
DELETE FROM tableName where id NOT IN (SELECT id from tableName ORDER BY id DESC LIMIT 20)
In this case, id is the primary key which is set to auto increment. You can use date as key as well if you are storing them by date
Here is sample solution:
Query is :
#Query("SELECT * FROM user LIMIT :limit OFFSET :offset")
User[] loadAllUsersByPage(int limit,int offset);
Here, it will give a list of user based on limit and offset.
if loadAllUsersByPage(2,0) it will return first 2 rows from table.
if loadAllUsersByPage(2,1) it will return 2nd and 3rd rows from table.
but if loadAllUsersByPage(-1,10) then it will serve first 10 rows from table.
Assuming:
Your table is
create table example_table (
ts timestamp,
uid number(19),
some_other_field varchar(64)
);
And you don't want to care about running some query manually.
Use database triggers:
create trigger
if not exists -- I don't actually know if you DB will support this line.
-- Might want to remove it if it's not.
example_table_limiter
on example_table
after insert
begin
delete
from example_table
where ts in (
select ts
from example_table
order by ts
limit -1 -- we don't want to limit how many rows we want to delete
offset 25 -- but we want to offset query result so it leaves 25 rows in table
);
end;
"Offset without limit" syntax is inspired by this answer.
To enable your trigger in java:
Simple Android, where you can override SQLiteOpenHelper:
public class DataBaseSchemaHelper extends SQLiteOpenHelper {
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(<trigger string from above>);
}
}
Android Room version:
public class MyDatabase extends RoomDatabase {
#Override
public void init(DatabaseConfiguration _config) {
super.init(_config);
getOpenHelper().getWritableDatabase().execSQL(<trigger string from above>);
}
}
You can limit columns/rows by doing this: this query will return the new data and remove old data when its reach its limit.
Explanation:
First query is select all data order by descending
Second query is remove data from columns/rows id > 20
If you want your table only have 20 row then set the OFFSET to 20, the LIMIT is represent how many rows inserted & deleted at once.
In my example I remove 1 row (the oldest/last row) when the user inputs 1 new data
#Query("SELECT * FROM my_table ORDER BY timeStamp DESC")
fun getAllData(): List<MyEntityClass>
#Query("DELETE FROM my_table WHERE id IN (SELECT id FROM my_table ORDER BY timeStamp DESC LIMIT 1 OFFSET 20)")
fun removeOldData()
Follow this steps :
1> get count of rows of that table
your_count = SELECT count( * ) FROM table_name;
2> if count is >(greater than) 20 than to get oldest record
SELECT *
FROM table_name
ORDER BY entry_Date ASC
LIMIT 1;
3> now delete these selected records
4> insert new datas
NOTE : if you are inserting multiple entries than put this in loop
Can you please share me code snippet to be written via JPA in order to generate the below sql query
SELECT COUNT(*) FROM Customer c
WHERE c.countryId ='Canada' AND
c.lanuguage ='ENG' AND
ROW_NUM <=10;
Because I tried in the below way. But MaxResults is not getting applied it seems as I can able to recieve the count more than 10.
Query query = em.createQuery("SELECT COUNT(c) FROM Customer c where c.countryId ='Canada' and c.lanuguage ='ENG'");
query.setMaxResults(10);
long customerCount = (Long)query.getSingleResult();
Select on count will always return a single value. If you want to have a count lower than 10, add HAVING.
SELECT COUNT(c) AS
FROM Customer c
WHERE c.countryId='Canada' and c.language='END'
HAVING COUNT(c)<=10
I have a table with name test in Oracle, and (sal(integer),gender) are the two columns in it.
I want to get counter number where gender is male, sal betwwen 1000,3000.
For example: If I have three people in table test (two male ,one female) and person1 sal =1000, person2 sal = 2020, person3 sal = 1040
The return value of sql statement will be equals (2).
The variable will store return value from java.
you actually want to count rows not column, as per what i understood from ur question. then you can use count(column_name) function of SQL along with the conditions (where clause).
Query: SELECT COUNT(*) "Count" FROM test WHERE gender='male' AND salary BETWEEN 1000 AND 3000
try this query,
select count(*) from <table_name> where gender='male' and salary between 1000 to 3000;