Groupby using GORM or MySql - mysql

My table has three column
created(Date)
score(int)(value is between 1-3)
id(long)
currently I am using Grails(GORM)
def listData= DaSes.createCriteria().list([max: 5, order: 'desc', sort: 'created']) {
projections {
groupProperty('created')
count('id')
}
}
[[date,count(of all scores)],[date,count(of all scores),...]
But I want result like this
[[date,count(of all scores),count(score1 for current day),count(score2 current day),count(score3 current day)],....]
Please guide me in this .

This is logically not possible.If you are using Group by on multiple columns then it gives
And this result is correct.

Related

mysql query works in phpmyadmin but not in node.js

I have a query like this...
SELECT *
FROM `000027`,`000028`
WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`)
AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)
which returns something like this in phpmyadmin...
id time value id time value
However, in react.js it is only returning one of these like this...
id time value
2 questions, Why is it doing this? and, how can I get it to return both instead of one?
my node.js code...
const sqlSelect = "SELECT * FROM `000027`,`000028` WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`) AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)"
dbPlant.query(sqlSelect, (err, result) => {
console.log(result)
res.send(result)
res.end()
})
and it sends this back with only one rowdatapacket when it should be two, or two of each of those values...
[
RowDataPacket {
id: 652,
time: 2021-01-24T17:28:01.000Z,
value: '262'
}
]
Your two tables have some column names in common. This is okay to have repeated column names in a result set in the mysql client, but some programming interfaces map a rows of a result set into a hash array, where the column names are the keys. So if you have duplicate column names, one naturally overwrites the other.
The remedy is to define column aliases for one or the other of each duplicate, so they are mapped into distinct keys in the result set.
You must do this one column at a time. Sorry, you can't use SELECT * anymore (you shouldn't use SELECT * anyway). There is no "automatic alias all columns" option.
SELECT
`000027`.id AS id27,
`000027`.time AS time27,
`000027`.value AS value27,
`000028`.id AS id28,
`000028`.time AS time28,
`000028`.value AS value28
FROM `000027`,`000028`
WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`)
AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)

Cannot order by two fields using django filter in graphene-django

I am using DjangoFilterConnectionField in my project like this:
all_sessions = DjangoFilterConnectionField(SessionNode, filterset_class=AgendaFilter)
SessionNode is created based on Session model in my Django application. Now, I would like to be able to order these sessions by two fields: start_date and start_time.
To achieve that I've created the following filter:
class AgendaFilter(FilterSet):
class Meta:
model = Session
exclude = []
order_by = OrderingFilter(
fields=(
("start_date", "start_date"),
("start_time", "start_time")
)
)
When I filter sessions by only one field using orderBy , the query results are ordered correctly as expected. When I try to use both fields in the filter (shown below), the results returned are not ordered according to either of them:
{
allSessions(orderBy: "[start_date, start_time]") {
edges {
node {
id
startDate
startTime
}
}
}
}
I've tried different ways of passing the two fields to orderBy, but none of them worked for me. How can I correctly order by start_date and then by start_time in one query? According to the graphene documentation, this is possible:
Ordering
You can use OrderFilter to define how you want your returned results to be ordered.
Extend the tuple of fields if you want to order by more than one field.
Is this is a bug in graphene or am I doing something wrong?

Rails dynamically add condition to mysql query

How to add condition dynamically to sql query
for example if i have one element than it will look like
query=['one_element']
User.where('name LIKE ?, %"#{query[0]}"%')
but if it more than one
User.where('name LIKE ? and LIKE ? and Like... , %"#{query}"%', ..so on)
Im use myslq
so my main goal to split search query if it contains more than 2 words and search by them separately in one sql query
not where(name:'john dou') but where(name:'john' and name:'dou')
If you have a version of MySQL that supports RLIKE or REGEXP_LIKE:
User.where("RLIKE(name, :name_query)", name_query: query.join("|"))
Otherwise, you'll have to manually build with the ActiveRecord or operator:
# In the User model
scope :name_like, ->(name_part) {
return self.all if name_part.blank?
where("name LIKE :name_query", name_query: "%#{name_part}%")
}
scope :names_like, ->(names) {
relation = User.name_like(names.shift)
names.each { |name| relation = relation.or(name_like(name)) }
relation
}
Then you can pass it an array of any name partials you want:
query = ["john", "dou"]
User.names_like(query)
First split the word by it's separator like this query.split(' ') this will give you array of words. Then you can use like below in rails.
User.where(name: ['John', 'dou']

GORM criteria group by in subquery

Let's assume the following Grails domains:
Owner {
String name
static hasMany [cars: Cars]
}
Car {
Date inspectionDate
}
I want to be able to search for Owners through Criteria, with the following rule: Most recent Car by inspectionDate in Owner's cars list being lower than *given date*.
As an example, I want to apply the following code to a select query in GORM:
queryResultsList = allOwnersList.filter { owner ->
owner.cars.min{ car -> car.inspectionDate }.inspectionDate < myDate
}
I need to achieve it using Criteria because I am already filtering Owners on other fields.
The whole given code is used as an example, some parts of the original code has been ommited, and source code is not about cars and owners.
As on first thought I assumed I needed a subquery in SQL to retrieve my data as I expected, I tried the following:
Owner.createCriteria().list {
// [...] some filters on other fields
cars {
lt('inspectionDate', params.inspectionDate)
'in'('inspectionDate', new grails.gorm.DetachedCriteria(Owner).list {
projections {
cars {
min('inspectionDate')
}
}
})
}
}
I also tried to add groupProperty in different places in the projection, ending with MissingPropertyException.
I am using Grails 2.2.4
After a few days testing solutions, I've come to the following one:
Owner.createCriteria().list {
// [...] some filters on other fields
cars {
lt('inspectionDate', params.inspectionDate)
'in'('inspectionDate', Owner.createCriteria().list {
projections {
cars {
min('inspectionDate')
}
groupProperty 'id'
}
// this allows to only get first property, which is inspectionDate
}.collect { it[0] })
}
}
However, I still feel like doing things wrong. In particular, the collect part looks like a code smell.
I am posting this because it does what I need, but any help with finding a good solution will be appreciated.

DBIx::Class Temporary column

I am using DBIx::Class and I have a query like this:
$groups = $c->model('DB::Project')->search(
{ "sessions.user_id"=>$c->user->id,done_yn=>'y' },
{
select => ["name", "id",\'SUM(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time)) as total_time'], #\''
join => 'sessions',
}
);
I'd like to be able to get the value of SUM(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time)), but because this is not a real column in the table, referencing total_time for a DBIx::Class::Row object doesn't seem to work. Does anyone know how I can get these temporary columns? Thanks!
The select docs describe perfectly how to achieve what you're trying to accomplish.
It's also recommended to avoid literal SQL when possible, you can use { sum => \'UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time)' } instead.
The 'as' in the literal SQL isn't required to give the column a name, you have to use either the as search attribute or better the columns shortcut instead of select+as.