I read a lot of topics about this problem but most of them were having problem with some complex (at least for me) code;
I have followed the oracle ROWNUM Pseudocolumn guide but when I write
SELECT * FROM " + tableName + "
WHERE ROWNUM < 12;
I get this error:
Unknown column 'ROWNUM' in 'where clause'
I then tried to do like the solution suggested here Select where row number = rownum
but nothing changes.
My code looks like this:
sql = "SELECT C.* "
+ "FROM ( SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.ROWNUM < 12;";
resultSet = statement.executeQuery(sql);
You can refer http://www.w3schools.com/sql/sql_top.asp.
ROWNUM is used in Oracle. Assuming you are using MySQL as you have tagged your question to MySQL.
You can change ROWNUM with limit clause
SELECT * FROM " + tableName + "
LIMIT 11;
Use the below
sql = ""
+ "SELECT C.*,ROWNUM as RECNUM "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.RECNUM < 12;";
resultSet = statement.executeQuery(sql);
Try this it will helpful for ur problem:
select * from (select * from " + tableName + ") "WHERE C.ROWNUM < 12;
Try this : [if you use mysql]
sql = ""
+ "SELECT C.* "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "LIMIT 11;";
resultSet = statement.executeQuery(sql);
For sql server :
SELECT TOP 12 ...
Related
I am try to find the costumer with the highest bill using this sql that I wrote , but apparently I run into this error :
Every derived table must have its own alias
This is what I wrote:
public static void findCustomerWithHighestBill(Connection c) throws SQLException {
String query = "SELECT CustomerID, CustomerName, CITY, sum(sum_all) As 'data'\r\n"
+ "FROM (SELECT *, sum(Price) As 'sum_all'\r\n"
+ " FROM (SELECT *, Customer.NAME AS \"CustomerName\"\r\n"
+ " FROM Transactions\r\n"
+ " INNER JOIN Product ON Product.ID = Transactions.ProductID\r\n"
+ " INNER JOIN Customer ON Customer.ID = Transactions.CustomerID)\r\n"
+ " GROUP BY CustomerID, ProductID\r\n"
+ " ) \r\n"
+ "GROUP BY CustomerID\r\n"
+ "ORDER BY data DESC";
Statement statement = c.createStatement();
ResultSet set = statement.executeQuery(query);
set.next();
System.out.println("CustomerID: " + set.getInt("CustomerID") +
", Name: " + set.getString("CustomerName") + ", City: " +
set.getString("CITY") + ", Bill: " + set.getFloat("data"));
}
Can please somoane help me zith this ?
Coming back ,
It seems that indeed ad most of you says in the comments I should identify my tables first but, apparently I also have miss to avoid the duplicate ID column.
Here goes my new query:
String query = "SELECT CID, CustomerName, City, sum(sum_all) As data" +
" FROM (SELECT *, sum(PPROD) As sum_all" +
" FROM (SELECT Product.ID as PID,Customer.ID as CID,Product.Price as PPROD,City, Customer.NAME AS CustomerName" +
" FROM Transactions" +
" INNER JOIN Product ON Product.ID = Transactions.ProductID" +
" INNER JOIN Customer ON Customer.ID = Transactions.CustomerID) As t2" +
" GROUP BY CID, PID" +
" ) As t1" +
" GROUP BY CID" +
" ORDER BY data DESC;";
Hi i have written a join query for my app and its working. My next requirement is to convert that query to prepared statement where I am stuck.
"SELECT * FROM " + TableA.TABLE + " as d LEFT JOIN " + TableB.TABLE + " as c ON d."+ TableA.DAMAGECODE + "=c." + TableB.DAMAGECODE + " AND d."
+ TableA.INDEX + "=c." + TableB.DAMAGECODEINDEX + " AND d."
+ TableA.OBJECTTYPE + "=c." + TableB.OBJECTCLASS + " WHERE d."+ TableA.LEAF + " = '1' AND d." + TableA.OBJECTTYPE + " = ? AND " + "(d."+ TableA.DAMAGECODE + " LIKE ? OR d." + TableA.DAMAGETEXT + " LIKE ?) AND c." + TableB.CONSTRUCTIONSERIES + " = ? ORDER BY " + TableA.DAMAGETEXT;
cursor = db.rawQuery(sql,new String[]{String.valueOf(objectClass),"'%" + query + "%'","'%" + query + "%'",constructionSeries});
When i ran raw query i am getting results ,but when ran the above prepared statements i am getting cursor count always zero
You don't need to add the ' yourself when you pass a String parameters, the PreparedStatement will manage those itself.
"'%" + query + "%'"
For the moment you have condition like
where columnA = "'%somethingToFind%'"
So unless you have a value in columnA like 'somethingToFindInColumnA' (note the quote at the begin and the end of that String). You will never get a result.
Remove those to get something like :
"%" + query + "%"
Full answer :
db.rawQuery(sql,new String[]{String.valueOf(objectClass),"'%" + query + "%'","'%" + query + "%'",constructionSeries});
Become :
db.rawQuery(sql,new String[]{String.valueOf(objectClass),"%" + query + "%","%" + query + "%",constructionSeries});
I'm converting all our sql queries to use Hibernate parameters. Now when I add a parameter in my query and map it with an variable it always give me the error:
ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Error converting data type
nvarchar to bigint.
It doesn't make any sense because I added a string parameter.
The query looks like:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid WHERE itemid IN ( :items ) "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= Cast( :endDate AS DATE) "
+ "GROUP BY o.materialrequireddate, itemid")
.setString("items", items).setString("endDate", endDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
When I return to my original working query it looks like:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r " + "JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid " + "WHERE itemid IN (" + items + ") "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= Cast('" + endDate + "' AS DATE) "
+ "GROUP BY o.materialrequireddate, itemid");
What can create this exception when I use named parameters? I'm using Hibernate 5.1 and for the database MS SQL server.
I changed my query to not cast to a date and sets the parameters with a correct type:
Query query = session.createSQLQuery("SELECT Sum([qtyrequired]) as pcs, o.materialrequireddate, itemid "
+ "FROM [materialManagement].[pcsorderrequirement] r JOIN materialmanagement.pcsorders o "
+ "ON o.id = r.pcsorderid WHERE itemid IN ( :items ) "
+ "AND Cast(o.materialrequireddate AS DATE) >= Cast(Getdate() AS DATE) "
+ "AND o.materialrequireddate <= :endDate "
+ "GROUP BY o.materialrequireddate, itemid").setParameterList("items", items.stream().map(Item::getId).collect(Collectors.toList()))
.setDate("endDate", Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
I'm writing a query where there is pivot table that has to generated. Right now below is my code.
select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
("XXX", "AAA", "BBB")
) as pivoting
But instead of giving the rows in for-in, I need to get this dynamically, I've seen a query here SQL Server dynamic PIVOT query? And modified my query to be
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME([case owner])
FROM StatusTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
('+#cols+')
) as pivoting'
execute(#query)
And this is working fine, but the problem is that I've to use this query in my JDBC program. And without using execute(#query), it is not running in my SQL Server. Can I make this query similar to the first query, so that I can use the same in my program?
Microsoft's JDBC Driver for SQL Server (mssql-jdbc) supports the execution of an anonymous code block (multiple SQL statements) so we can just execute the same SQL code, including the EXECUTE(...) at the end:
String sql = " "
+ "SET NOCOUNT ON; "
+ "DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX); "
+ " "
+ "SET #cols = "
+ " STUFF( "
+ " ( "
+ " SELECT distinct ',' + QUOTENAME([case owner]) "
+ " FROM StatusTable c "
+ " FOR XML PATH(''), TYPE "
+ " ).value('.', 'NVARCHAR(MAX)'), "
+ " 1, "
+ " 1, "
+ " ''); "
+ " "
+ "set #query = 'select * "
+ "from "
+ "( "
+ " select [case owner], [time taken(minutes)] from StatusTable "
+ ") as pivotdata "
+ "pivot( "
+ " sum([time taken(minutes)]) for [CASE OWNER] in ('+#cols+') "
+ ") as pivoting'; "
+" "
+ "execute(#query); ";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
// print column headings
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rsmd.getColumnLabel(i));
}
System.out.println();
rs.next();
// print column values
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rs.getString(i));
}
System.out.println();
/* console output:
AAA BBB XXX
2 13 1
*/
i am trying to do the following and it doesnt accept it.
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ="' + cu_ID + "'";
select from two tables and two values( variables)
Try this:
String sql_eco = "select * +
from orders +
where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
^
Try, assuming CustomerID and EmployeeID are both Integer column type
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID =" + cu_ID;
Use this. you have misplaced " for CustomerId
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
values variable u wanna say something like this?
String sql_eco = "select * +
from orders +
where 1=1 ";
if(e_ID != null) {
sql_eco += " AND EmployeeID=" +e_ID ;
}
if(cu_ID != null){
sql_eco += " and CustomerID ='" + cu_ID + "'";
}
to improve this code u can use stringbuilder/stringbuffer