I'm working with Hibernate and I want to obtain a substraction from two values fetched from two diffeent subqueries but I am gettin the following error:
SQLGramarEception: could not execute query
SELECT termQuery.term.id,
(SELECT COALESCE(MIN(termResult2.position),101) FROM termQuery2.results termResult2 WHERE termResult2.url.hostname MEMBER subscription.account.domains) as **prevPosition**,
(SELECT COALESCE(MIN(termResult.position),101) FROM termQuery.results termResult WHERE termResult.url.hostname MEMBER subscription.account.domains) as **currentPosition**,
prevPosition - currentPosition as change --<<<<<<
FROM TermSubscription subscription, TermQuery termQuery, TermQuery termQuery2
WHERE subscription.account.id=1197
AND termQuery.term=subscription.term
AND termQuery.provider.id=2
AND termQuery.queryDate.yearWeek = '201242'
AND termQuery2.term=termQuery.term
AND termQuery2.provider.id=termQuery.provider.id
AND termQuery2.queryDate.yearWeek = '201241'
ORDER BY subscription.term.id, termQuery.queryDate.yearWeek
I know that it is not possible to substract those two values like that but I don't know the way to do it. So, what would be the way?
Thanks
select only the 3 other values, and while iterating on the results of the query, subtract the currentPosition from the prevPosition, in Java.
Related
I have a table which has dstipv4 and pkts fields. I want to calculate STDEV of normalized pkts for each dstipv4. I write a query like this it but does not work — generating the error:
#1111 - Invalid use of group function
How to write a correct query?
SELECT dstipv4, STDEV((pkts-min(pkts))/(max(pkts)-min(pkts))) FROM flow
group by dstipv4
I'm not sure how best to explain it, but your calculation as shown requires prescience on the part of the DBMS, and the error message is the DBMS telling you that it doesn't have the requisite foresight.
I think you need to calculate the MAX and MIN values in a sub-query:
SELECT f.dstipv4, STDEV((f.pkts - m.min_pkts) / (m.max_pkts - m.min_pkts))
FROM flow AS f
JOIN (SELECT dstipv4, MIN(pkts) AS min_pkts, MAX(pkts) AS max_pkts
FROM flow
GROUP BY dstipv4
) AS m
ON f.dstipv4 = m.dstipv4
GROUP BY f.dstipv4
I have the following query:
SELECT routes.route_date, time_slots.name, time_slots.openings, time_slots.appointments
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
ORDER BY route_date, name
This works just fine and will produce the following results:
What I want to do is only return one name per date. So the 9th, name = 1, would only have 1 result, rather than 2, as it currently does.
UPDATE: See the SQLFIDDLE for different type of solutions here: http://sqlfiddle.com/#!2/9ac65b/6
Will it solve your request if you use...
SELECT DISTINCT routes.route_date...your query... ?
It depends if you know that your rows always will have the same values, for same date/name.
Otherwise use group by...
(which I think suits your request best)
SELECT routes.route_date, time_slots.name, sum(time_slots.openings), sum(time_slots.appointments)
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
group by routes.route_date, time_slots.name
ORDER BY route_date, name
(i did a sum for the openings and appointments, you could do min, max, count, etc. Pick the one that fits your requirements best!)
You need to figure out which "name" you want when there are several for the same date.
Then you can group by date and select the right "name" by using an aggregate function like COUNT, MAX, etc.
I can't help you more if you don't explain your rule for picking one.
So I'm trying to aggregate exam data, and because the database lives on another server I'm trying to reduce this to as few database calls as possible.
I have this model (whose corresponding table is in a mySQL database if that matters):
class Exam(models.Model):
submitted = models.BooleanField(default=False)
score = models.DecimalField(default=Decimal(0))
And this query:
>>> exam_models.Exam.objects\
... .using("exam_datebase")\
... .aggregate(average=Avg("score"),
... total=Count("submitted"))
{'average': 22.251082, 'total': 231}
What I'm looking for is a way to also retrieve the number of passed exams, something along the lines of:
>>> exam_models.Exam.objects\
... .using("exam_datebase")\
... .aggregate(average=Avg("score"),
... total=Count("submitted"))
... passed=Count("score__gte=80"))
{'average': 22.251082, 'total': 231, 'passed': 42}
I know I can just send another query using .filter(score__gte=80).count(), but I was really hoping to get both the total count and the passing count on the same aggregate. Any ideas?
You are either going to need two queries, or do the aggregation manually.
To see why, let's consider the underlying SQL that Django generates and uses to query the database.
Exam.objects.aggregate(average=Avg("score"), total=Count("submitted"))
roughly translates to
SELECT AVG(score), COUNT(submitted)
FROM exam
The "Count" part of the aggregate is applying to the SELECT clause in the underlying sql query. But if we want to include only scores greater than some value, the SQL query would need to look something like this:
SELECT AVG(score), COUNT(submitted)
FROM exam
WHERE score > 80
Filtering Exams with a particular "score" is applies to the WHERE or HAVING clause of the underlying SQL statement.
Unfortunately, there is not really a way to combine these two things. So, you are stuck doing two queries.
Having said all that, if you REALLY want to do a single query, one option is to just do the aggregation in your python code:
exams = Exam.objects.all()
total_score = 0
total_submitted = 0
passed = 0
for exam in exams:
total_score += exam.score
if exam.submitted:
total_submitted += 1
if exam.score >= 80:
passed += 1
exam_aggregates = {
'average': total_score / len(exams),
'submitted': total_submitted,
'passed': passed,
}
Hi I want to get the count of this linq query.Im using entity framework with repository pattern.
It is possible to get the result by queryUserWalls.ToList().Count()
which I think is inefficient.
Can any body help.
var queryUserWalls = (from participation in _eventParticipationRepository.GetAll()
join eve in _eventRepository.GetAll() on participation.EventId equals eve.Id
join userWall in _userWallRepository.GetAll() on participation.EventId equals userWall.EventId
where participation.UserId == userId
select userWall.Id)
.Union(from userWall in _userWallRepository.GetAll()
select userWall.Id);
Leave out the ToList because it forces query execution. You want to use Queryable.Count, not Enumerable.Count. Then, it will execute on the server.
I'm trying to update one column of MySQL table with subquery that returns a date, and another subquery for the WHERE clause.
Here is it:
UPDATE wtk_recur_subs_temp
SET wtk_recur_date = (SELECT final_bb.date
FROM final_bb, wtk_recur_subs
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn)
WHERE wtk_recur_subs_temp.wtk_recur_msisdn IN (select final_bb.msisdn
from final_bb)
The response from the MySQL engine is "Subquery returns more than 1 row".
Use:
UPDATE wtk_recur_subs_temp,
final_bb,
wtk_recur_subs
SET wtk_recur_subs_temp.wtk_recur_date = final_bb.date
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn
AND wtk_recur_subs_temp.wtk_recur_msisdn = final_bb.msisdn
The error is because:
SET wtk_recur_date = (SELECT final_bb.date
FROM final_bb, wtk_recur_subs
WHERE final_bb.msisdn = wtk_recur_subs.wtk_recur_msisdn)
...the final_bb.date value is all the date values where the final_bb and wtk_recur_subs msisdn column values match.
This may come as an utter shock to you, but one of your subqueries is returning more than one row!
This isn't permitted in the circumstance you've set up. Each of those two subqueries must return one and only one row. Or no rows.
Perform each subquery on it's own and determine which one is returning more than one row. If they shouldn't return more than one row, your data may be wrong. If they should return more than one row, you'll either want to modify the data so they don't (as I assume you expect), or add a LIMIT clause. Or add an aggregate function (like MAX) outside the query to do something proper with the multiple rows being returned.