attach string variable to ranked column values - java

i had help here to update a table column with values from a computed ranked column.how can i attach string variables to them such that instead of values like 1,2,3,4...they will be 1st,2nd, 3rd,4th..
i wrote this code :
//code create computed ranked column
String sql1 = SELECT COUNT(DISTINCT s2.Total) AS Rank from class1 s1
JOIN class1 s2 on (s1.Total<=s2.Total)
GROUP BY s1.ID order by s1.Name ASC;
pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
// attaching a string variable to the resultset
String type = rs.getString(2);
typ=Integer.parseInt(type);
String type1 = "";
if(typ==1){
type1="st";
}else if(typ==2){
type1="nd";
}else if(typ==3){
type1="rd";
}else if(typ>3){
type1="th";
}
//updating table column with the resultset
String sql = "";
while (rs.next()) {
sql = "update class1 set Position='"+rs.getString(2)+type1+"'"+" WHERE ID="+rs.getString(1);
pst=conn.prepareStatement(sql);
pst.execute();
but what this does is to repeat the result of the first row to all the rows..
| NAME | SCORE 1 | SCORE 2 | TOTAL | POSITION |
------------------------------------------------------------------------
| james | 10.0 | 24.0 | 34.0 | 1st |
| jimmy | 10.0 | 20.0 | 30.0 | 2st |
| josh | 10.0 | 19.0 | 29.0 | 3st |
how do i get it to work like
| NAME | SCORE 1 | SCORE 2 | TOTAL | POSITION |
------------------------------------------------------------------------
| james | 10.0 | 24.0 | 34.0 | 1st |
| jimmy | 10.0 | 20.0 | 30.0 | 2nd |
| josh | 10.0 | 19.0 | 29.0 | 3rd |
thank you.

Related

Stream to filter and sum different fields depending on different conditions

I have a list:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 10.00 | 0.01 | 001
2 | 001 | 001 | 11.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
I want to have this result:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
I want to sum up the transaction amount and charges, but when the charges id is same, I will only calculates once.
Below is the code to sum up based on product code and type:
Map<String, Transaction> map = txs.stream()
.map(s -> {
s.setTotalCount(1);
return s;
})
.collect(Collectors.toMap(f -> f.getProductCode() + f.getProductType()
Function.identity(),
(s, a) -> new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
s.getCharges().add(a.getFeeCharges()),
s.getTotalCount() + 1
)));
List<Transaction> reduced = new ArrayList<>(map.values());
From the code above I got:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | **0.02** | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
You could check the charges id in your mergeFunction to Collectors.toMap:
(s, a) -> {
double charges = (s.getChargesId().equals(a.getChargesId())
? s.getCharges()
: s.getCharges().add(a.getFeeCharges());
return new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
charges,
s.getTotalCount() + 1);
}

How to select next record and previous record in SQLite?

I have been searching like forever
I am using min and max for the last and and first record but how do I get the next/ record? I have a column name rowid it is the pk and auto incremented by one every time a user registers
| rowid | Name |
| 1 | John |*
| 2 | Mark |
| 3 | Peter|
| 4 | Help |
so if I click the next button I wanted to select mark which is in rowid 2
| rowid | Name |
| 1 | John |
| 2 | Mark |*
| 3 | Peter|
| 4 | Help |
but if I click the next button twice I want to be in rowid 4
| rowid | Name |
| 1 | John |
| 2 | Mark |
| 3 | Peter|
| 4 | Help |*
how do I do that? by the way I don't have fixed rows since I have a registration function
so here's my code
JButton btnNextLast = new JButton(">>");
btnNextLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String sQuery = "select * from accountinfo where rowid = (SELECT MAX(rowid) FROM accountinfo)";
PreparedStatement prst = connection.prepareStatement(sQuery);
ResultSet rs = prst.executeQuery();
lblSID.setText(rs.getString("sid"));
lblfirst.setText(rs.getString("last"));
lblLast.setText(rs.getString("first"));
lblmiddle.setText(rs.getString("middle"));
lblbirth.setText(rs.getString("birth"));
lblcontact.setText(rs.getString("contact"));
}catch(Exception qwe){
}
}
});
I've tried
select rowid
from accountinfo
where rowid >1
order by rowid
limit 1
but no luck
and if I remove order by rowid limit 1. It just show the next record which is 2 and never function again

MySQL Count that includes months not within the date range

Supposed I have a table that contains the following table:
+----+-----------+---------+-------------------------+
| id | item | .... | dateLogged |
+----+-----------+---------+-------------------------+
| 1 | 2015-001 | .... | 2015-06-01 12:09:00 |
| 2 | 2015-001 | .... | 2015-06-01 12:09:00 |
| 3 | 2015-002 | .... | 2015-06-30 15:40:02 |
| 4 | 2015-002 | .... | 2015-06-30 15:40:03 |
| 5 | 2015-003 | .... | 2015-07-02 13:38:22 |
+----+-----------+---------+-------------------------+
I want to search the number of items based on the year, month and count from the dateLogged, with the expected data:
+--------+----------+----------------+
| year | month | total |
+--------+----------+----------------+
| 2015 | January | 0 |
| 2015 | February | 0 |
| 2015 | March | 0 |
| 2015 | April | 0 |
| 2015 | May | 0 |
| 2015 | June | 4 |
| 2015 | July | 1 |
| 2015 | August | 0 |
| 2015 | September| 0 |
| 2015 | October | 0 |
| 2015 | November | 0 |
| 2015 | December | 0 |
+--------+----------+----------------+
But I am only getting this based on the following SQL:
SELECT DATE_FORMAT(dateLogged, '%Y') as 'year', MONTHNAME(dateLogged)
as 'month', COUNT(id) as 'total' from item a where dateLogged >= '2015-06-29 00:00:00'
and dateLogged <= '2015-07-02 23:59:59'
GROUP BY DATE_FORMAT(a.dateLogged, '%Y%m');
+--------+---------+----------------+
| year | month | No of items |
+--------+---------+----------------+
| 2015 | June | 4 |
| 2015 | July | 1 |
+----+-------------+----------------+
I've tried searching elsewhere from stackoverflow, but wasn't able to get any answers, or probably have missed. Wanna know if there is any solution to this, thanks.
I am using Java to compute this, so any suggestions using Java to compute the above is also welcomed.
You could change your query to return the 0 values as well using loops to iterate over months and years and then find the count. Something like this:
Map<String, Integer> values = new HashMap<String, Integer>();
for(int year = 2015; year < 2017; year++)
{
for(int month = 1; month <= 12; month++)
{
rs = stmt.executeQuery("SELECT COUNT(id) as 'total' from item where
MONTH(dateLogged) = " + month + " and YEAR(dateLogged) = " + year + ";";
rs.next();
int count = rs.getInt("total");
String time = Integer.toString(year) + "-" + Integer.toString(month);
values.Add(time, count);
}
}
This would return you a map like this:
values['2015-1'] = 0;
values['2015-2'] = 0;
.. and so on.
Of course, you could store the returned count with year and month however you want, depending on how you wish to use it further.
One idea is to, somehow, create a calendar table, and use it, so that you get a row for each month of year 2015:
SELECT DATE_FORMAT(m, '%Y') as 'year',
MONTHNAME(m) as 'month',
COUNT(id) as 'total'
FROM (SELECT '2015-01-01' AS m UNION ALL SELECT '2015-02-01' UNION ALL
SELECT '2015-03-01' UNION ALL SELECT '2015-04-01' UNION ALL
SELECT '2015-05-01' UNION ALL SELECT '2015-06-01' UNION ALL
SELECT '2015-07-01' UNION ALL SELECT '2015-01-08' UNION ALL
SELECT '2015-09-01' UNION ALL SELECT '2015-10-01' UNION ALL
SELECT '2015-11-01' UNION ALL SELECT '2015-12-01') AS x
LEFT JOIN item a
ON DATE_FORMAT(a.dateLogged, '%Y%m') = DATE_FORMAT(x.m, '%Y%m')
AND dateLogged >= '2015-06-29 00:00:00'
AND dateLogged <= '2015-07-02 23:59:59'
GROUP BY DATE_FORMAT(x.m, '%Y%m');
The above query makes use of sort of an inline calendar table for year 2015. This table is used as a basis in the FROM clause, so that the query returns a row for each of the months of year 2015.
Demo here

Select data from specific year

I need a solution for my problem here.
I got 2 tables, assetdetail and assetcondition. Here is the structure of those tables.
assetdetail
-----------------------------------------------------------
| sequenceindex | assetcode | assetname | acquisitionyear |
-----------------------------------------------------------
| 1 | 110 | Car | 2012-06-30 |
| 2 | 111 | Bus | 2013-02-12 |
assetcondition
--------------------------------------------------------------------------
|sequenceindex | indexassetdetail | fiscalyear | assetamount | assetprice |
---------------------------------------------------------------------------
| 1 | 1 | 2012 | 1 | 20000000 |
| 2 | 1 | 2013 | 1 | 15000000 |
| 3 | 2 | 2013 | 1 | 25000000 |
And i want the result is like this:
------------------------
assetname | assetprice |
------------------------
Car | 20000000 |
Bus | 25000000 |
Note: using "SELECT WHERE fiscalyear = "
Without explaining how your tables are linked one can only guess. Here's the query I came up with.
select assetdetail.assetname,
sum( assetcondition.assetprice )
from assetdetail
inner join assetcondition
on assetcondition.indexassetdetail = assetdetail.sequenceindex
where assetcondition.fiscalyear = 2013
group by assetdetail.assetname;
I haven't understand from a logical point of view your query. By the way the operator that you have to you use is the JOIN's one.
The SQL that follows, I don't know if it is what you want.
Select assetname, assetprice
From assetdetail as ad join assetcondition as ac on (as.sequenceindex = ac.sequenceindex)
Where fiscalyear = '2013'
Not quite sure if it is what you're looking for, but I guess what you want is a JOIN:
SELECT
assetdetail.assetname, assetcondition.assetprice
FROM
assetdetail
JOIN
assetcondition
ON
assetdetail.sequenceindex = assetcondition.sequenceindex
WHERE
YEAR(acquisitionyear) = '2013'

Usage of mysql variables in query in Spring Jdbc Template gives error

I have a requirement of picking top 2 students within each subject. Here is my table and the query which I am using to get that.
CREATE TABLE `students` (
`student` varchar(10) DEFAULT NULL,
`subject` varchar(10) DEFAULT NULL,
`marks` int(10) DEFAULT NULL
);
INSERT INTO students VALUES
('Deepak', 'Maths', 100),
('Neha', 'Maths', 90),
('Jyoti', 'Maths', 80),
('Ashwini', 'Maths', 70),
('Amit', 'Maths', 30),
('Sandeep', 'Maths', 95),
('Cinni', 'Maths', 86),
('Anand', 'Maths', 75),
('Deepak', 'Science', 100),
('Neha', 'Science', 90),
('Jyoti', 'Science', 80),
('Ashwini', 'Science', 70),
('Amit', 'Science', 30),
('Sandeep', 'Science', 95),
('Cinni', 'Science', 86),
('Anand', 'Science', 75),
('Deepak', 'History', 100),
('Neha', 'History', 90),
('Jyoti', 'History', 80),
('Ashwini', 'History', 70),
('Amit', 'History', 30),
('Sandeep', 'History', 95),
('Cinni', 'History', 86),
('Anand', 'History', 75);
mysql> SELECT * FROM students
+---------+---------+-------+
| student | subject | marks |
+---------+---------+-------+
| Deepak | Maths | 100 |
| Neha | Maths | 90 |
| Jyoti | Maths | 80 |
| Ashwini | Maths | 70 |
| Amit | Maths | 30 |
| Sandeep | Maths | 95 |
| Cinni | Maths | 86 |
| Anand | Maths | 75 |
| Deepak | Science | 100 |
| Neha | Science | 90 |
| Jyoti | Science | 80 |
| Ashwini | Science | 70 |
| Amit | Science | 30 |
| Sandeep | Science | 95 |
| Cinni | Science | 86 |
| Anand | Science | 75 |
| Deepak | History | 100 |
| Neha | History | 90 |
| Jyoti | History | 80 |
| Ashwini | History | 70 |
| Amit | History | 30 |
| Sandeep | History | 95 |
| Cinni | History | 86 |
| Anand | History | 75 |
+---------+---------+-------+
24 rows in set (0.00 sec)
mysql> Set character_set_connection=latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> Set character_set_results=latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> Set character_set_client=latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> SET #rowcnt := 0; SET #grp := ''; SELECT d.* FROM (
-> SELECT
-> cs.*,
-> #rowcnt := IF(#grp != cs.subject, 1, #rowcnt + 1) AS rowcnt,
-> #grp := cs.subject
-> FROM (
-> SELECT * FROM students ORDER BY subject, marks DESC
-> ) cs
-> ) d
-> WHERE d.rowcnt < 3;
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+---------+---------+-------+--------+--------------------+
| student | subject | marks | rowcnt | #grp := cs.subject |
+---------+---------+-------+--------+--------------------+
| Deepak | History | 100 | 1 | History |
| Sandeep | History | 95 | 2 | History |
| Deepak | Maths | 100 | 1 | Maths |
| Sandeep | Maths | 95 | 2 | Maths |
| Deepak | Science | 100 | 1 | Science |
| Sandeep | Science | 95 | 2 | Science |
+---------+---------+-------+--------+--------------------+
6 rows in set (0.00 sec)
mysql>
Now, everything works fine from the console, but when I execute the same query in Spring JdbcTemplate, it gives me error.
jdbcTemplate.query(query, new StudentRowMapper());
The query prints out to following which is exactly same as the query which I am using on command line.
SET #rowcnt := 0; SET #grp := ''; SELECT d.* FROM ( SELECT cs.*, #rowcnt := IF(#grp != cs.subject, 1, #rowcnt + 1) AS rowcnt, #grp := cs.subject FROM ( SELECT * FROM students ORDER BY subject, marks DESC ) cs ) d WHERE d.rowcnt < 3;
Here is the error which I get while running this:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET #grp := ''; SELECT d.* FROM ( SELECT cs.*, ' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2324)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:646)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:589)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:639)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:668)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:676)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716)
Just place the vars in the select like this
SELECT d.*
FROM
( SELECT cs.*, #rowcnt := IF(#grp != cs.subject, 1, #rowcnt + 1) AS rowcnt, #grp := cs.subject
FROM ( SELECT * FROM (select #rowcnt :=0, #grp :='') a,students ORDER BY subject, marks DESC ) cs ) d
WHERE d.rowcnt < 3;

Categories