Subquery Totals in Access - ms-access

I need to breakdown the two subqueries by File_Date. Now it's just giving me the total number of records per Service_Code.
SELECT
[Request File].File_Date,
Count([Request File].SSN) AS [Borrower Count],
Sum([Request File].Discharge_Amt) AS Total_Discharge_Amt,
(SELECT Count([Request File].SSN) FROM [Request File] WHERE [Request File].Servicer_Code="500") AS 500_Count,
(SELECT Count([Request File].SSN) FROM [Request File] WHERE [Request File].Servicer_Code="579") AS 579_Count
FROM [Request File]
GROUP BY [Request File].File_Date;
If I try and Group By File_Date for the two subqueries, I get an error "At most one record can be returned by this subquery".
SELECT
[Request File].File_Date,
Count([Request File].SSN) AS [Borrower Count],
Sum([Request File].Discharge_Amt) AS Total_Discharge_Amt,
(SELECT Count([Request File].SSN) FROM [Request File] WHERE [Request File].Servicer_Code="500" GROUP BY [Request File].File_Date) AS 500_Count,
(SELECT Count([Request File].SSN) FROM [Request File] WHERE [Request File].Servicer_Code="579" GROUP BY [Request File].File_Date) AS 579_Count
FROM [Request File]
GROUP BY [Request File].File_Date;

In the SELECT-list sub-queries must return one column and one record, because this value will be inserted in one result field.
Since all the data comes from the same table, no sub-query is required. Instead, we use the trick to conditionally count the records by summing up 1 when the condition is fulfilled and 0 otherwise:
SELECT
File_Date,
Count(SSN) AS [Borrower Count],
Sum(Discharge_Amt) AS Total_Discharge_Amt,
Sum(IIf(Servicer_Code="500", 1, 0)) AS 500_Count,
Sum(IIf(Servicer_Code="579", 1, 0)) AS 579_Count
FROM [Request File]
GROUP BY File_Date;

Related

Spring Boot throws an SQL Syntax exception

I am testing new endpoints on my API and getting an error that confuses me a bit.
2022-08-24 11:51:54.283 WARN 9836 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
2022-08-24 11:51:54.283 ERROR 9836 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : 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 'WHERE) FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null ' at line 1
2022-08-24 11:51:54.292 ERROR 9836 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/api/v1] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: 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 'WHERE) FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null ' at line 1
The confusing part for me is that I don't understand where it gets the first part of the query WHERE) in the error message.
Repo
#Query("SELECT * FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR rate_code = :code) AND rate > 0)", nativeQuery = true)
fun getByDateRange(startDate: Date, endDate: Date, code: String?, pageable: Pageable): Page<RateEntity>
Controller
#GetMapping("/historic")
fun ratesForDateRange(
#RequestParam startDate: Optional<Date>,
#RequestParam endDate: Optional<Date>,
#RequestParam(required = false) code: String?,
#RequestParam(required = false) pageNumber: Int?
): Page<RateEntity> {
val lastDate = Date.valueOf(START_DATE)
val page = pageNumber ?: 0
println(code)
return repo.getByDateRange(
startDate.orElse(lastDate),
endDate.orElse(UtilFunctions.getCurrentSQLDate()),
code,
PageRequest.of(page, 50)
)
}
When I use the wrong code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1&code=abc I get an empty page as expected.
When I use the right code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1&code=suv and there are records between specified dates, I get the page with results as expected.
However, when I don't specify the code in request URL /api/v1/historic?startDate=2022-1-1&endDate=2022-3-1 I get this exception.
I use MySQL for Database and if use this query directly in CLI it works as expected.
For example this query
SELECT * FROM rates WHERE (date BETWEEN '2022-01-01' AND '2022-03-01') AND ((null IS NULL OR rate_code = null) AND rate > 0);
returns all results for specified date range as expected.
I think it is the problem with date_and_time in spring boot.
You are comparing two dates whereas the actual values saved are dateAndTime, which spring can not compare. Therefore, you should cast the date field as follow:
CAST(date as DATE)
Complete Query:
#Query("SELECT * FROM rates WHERE (CAST(date as DATE) BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR rate_code = :code) AND rate > 0)", nativeQuery = true)
Ok so I've already found where the problem lies and fixed it. Probably posted too soon.
After some more testing I found out that the exception occurs when amount of results is >= page size (50 in my case).
So after displaying hibernate queries with:
spring.jpa.show-sql = true
I found this:
Hibernate: SELECT count(WHERE) FROM rates WHERE (date BETWEEN ? AND ?) AND ((? IS NULL OR rate_code = ?) AND rate > 0)
That's where WHERE) comes from, which is obviously a syntax error.
The fix was to add custom count query like this:
#Query(
value = "SELECT * FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR currency_code = :code) AND rate > 0)",
countQuery = "SELECT count(*) FROM rates WHERE (date BETWEEN :startDate AND :endDate) AND ((:code IS NULL OR currency_code = :code) AND rate > 0)",
nativeQuery = true
)
fun getByDateRange(startDate: Date, endDate: Date, code: String?, pageable: Pageable): Page<RateEntity>

hibernate access outer query field in subquery

I have the below query which works in Mysql Workbench but get an error in hibernate
insert into namingsequences(currentseq, namingtype, scope, sequencekey, startrange, endrange, steprange, rangeactive)
select (a.currentseq + 5) as currentseq, namingtype, scope, sequencekey, startrange, endrange, steprange, rangeactive from namingsequences a
where a.sequencekey = 'test1123' and a.namingtype = 'test' and a.scope = 'test'
and a.currentseq >= a.startrange and a.currentseq <= a.endrange and not exists
(select 1 from namingsequences b where b.sequencekey = 'test1123' and b.namingtype = 'test'
and b.currentseq >= b.startrange and b.currentseq <= b.endrange
and b.scope = 'test' and b.currentseq = (a.currentseq+5) )
order by currentseq ;
insert into NamingSequences ( namingtype, scope, sequencekey,startrange,
endrange, steprange, currentseq, rangeactive )
select namingsequ0_.namingtype as col_0_0_, namingsequ0_.scope as col_1_0_,
namingsequ0_.sequencekey as col_2_0_, namingsequ0_.startrange as col_3_0_,
namingsequ0_.endrange as col_4_0_, namingsequ0_.steprange as col_5_0_,
namingsequ0_.currentseq+? as col_6_0_, namingsequ0_.rangeactive as col_7_0_ from NamingSequences namingsequ0_
where namingsequ0_.sequencekey=? and namingsequ0_.namingtype=? and namingsequ0_.scope=?
and namingsequ0_.currentseq>=namingsequ0_.startrange and namingsequ0_.currentseq<=namingsequ0_.endrange
and not (exists (select 1 from NamingSequences namingsequ1_ where
namingsequ1_.sequencekey=? and namingsequ1_.namingtype=?
and namingsequ1_.currentseq>=namingsequ1_.startrange
and namingsequ1_.currentseq<=namingsequ1_.endrange
and namingsequ1_.scope=? and
namingsequ1_.currentseq=NamingSequences.currentseq+?))
order by namingsequ0_.currentseq
[DEV: 2018-Feb-28 16:32:47,884][WARN ][http-nio-8082-exec-35]SQL Error: 1054, SQLState: 42S22
[DEV: 2018-Feb-28 16:32:47,884][ERROR]http-nio-8082-exec-35 Unknown column 'NamingSequences.currentseq' in 'where clause'
It seems that it cannot access the outer query field from the subquery. The error seems to be from the hibernate query penultimate line.
Also, can i restrict that only one row will be returned by select and inserted?
Query hbquery = session.createQuery(queryString);
hbquery.setMaxResults(1);
hbquery.setParameter("scope", scope);
hbquery.setLong("increment", step);
hbquery.setParameter("nameType", namingType);
hbquery.setParameter("seqKey", seqKey);
int ret = hbquery.executeUpdate();

Combining rows on a query in access 2010

First off I know nothing about VB and the post I have seen on here refer to that, I am sure that this is a very simple thing to do so please help
I am trying to hve my TN Route be my primary key/no duplicates and have date driver 1 driver 2 and driver 3 all in diff cells and all side by side, and even though the tbl that it is pulling from the TN route is primary, it keeps adding additional rows for each driver.
See attached screenshot:
Thank you in advance.
Stan
data sheet view of query
This query will do it for you. Again, it's not preferable because in Access SQL tends to be a little messy on account of it not having features that more robust SQL platforms do - but it will work. You'll need to change the name of your Date column to Route Date in order for this to work, and replace my tblTest with whatever your table name is:
SELECT DISTINCT tblTest.[TN Route], tblTest.[Route Date], tA.[Driver 1], tB.[Driver 2], tC.[Driver 3]
FROM ((tblTest LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 1] FROM tblTest WHERE [Driver 1] <> '') AS tA ON (tblTest.[Route Date] = tA.[Route Date]) AND (tblTest.[TN Route] = tA.[TN Route]))
LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 2] FROM tblTest WHERE [Driver 2] <> '') AS tB ON (tblTest.[Route Date] = tB.[Route Date]) AND (tblTest.[TN Route] = tB.[TN Route]))
LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 3] FROM tblTest WHERE [Driver 3] <> '') AS tC ON (tblTest.[Route Date] = tC.[Route Date]) AND (tblTest.[TN Route] = tC.[TN Route])
In Access 2010, go Create > Query Design > add your table, and then paste the SQL into the SQL view of the query designer. You can even make a standalone table out of the result.

Select closed request in mysql but getting error means servlet not showing result

I want to select only pending request in servlet
String sql = SELECT emailid as request,status as Request_Time, etr as ETR_Time
FROM it_Service_ticket
INNER JOIN it_problem ON
it_service_ticket.it_problem_id=it_problem.it_problem_id
WHERE status="closed";
PreparedStatement pst = con.prepareStatement(sql);

I trying to update some records with Inner join in JPA Query but we getting some exception

This is MySQL query:
UPDATE grademyadvisor.gma_error AS ge
INNER JOIN
grademyadvisor.yodlee_error_code AS yec ON yec.id = ge.yodlee_error_id
SET
ge.is_resolved = 0
WHERE
ge.client_id = 639
AND yec.error_code = 402;
Spring Data JPA Query And getting Exception. Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting "set", found 'INNER' near line 1, column 39 [ UPDATE com.gma.domain.GMAError AS ge INNER JOIN ge.yodleeErrorCode AS yec SET ge.isResolved=:isResolved WHERE ge.client.id=:clientId AND yec.errorCode=:errorCode ]
#Query(" UPDATE GMAError AS ge "
+ "INNER JOIN ge.yodleeErrorCode AS yec "
+ "SET ge.isResolved=:isResolved "
+ "WHERE ge.client.id=:clientId "
+ "AND yec.errorCode=:errorCode ")
Use a subquery in the WHERE clause to get rid of the INNER JOIN statement:
UPDATE grademyadvisor.gma_error
SET
is_resolved = 0
WHERE
client_id = 639
AND yodlee_error_id = (SELECT id FROM grademyadvisor.yodlee_error_code WHERE error_code = 402);