I'm trying to implement the following SQL query with QueryOver:
SELECT [Time]/1000
FROM TableName
GROUP BY [Time]/1000
Here's my current attempt:
var result = session
.QueryOver<TableName>
.Select(Projections.GroupProperty(
Projections.SqlFunction(
new VarArgsSQLFunction("(", "/", ")"),
NHibernateUtil.Int64,
Projections.Property("Time")
Projections.Constant(1000))
))
.List<object>();
Unfortunately I get the following exception (GenericADOException):
could execute query
[ SELECT (this_.Time/#p0) as y0_ FROM [TableName] this_ GROUP BY (this_.Time/?) ]
And the inner exception:
Incorrect syntax near ?.
I can replace the "GroupProperty" with a "Sum" and it works. Any idea what's missing?
Update:
Apparently it's a bug in NHibernate. See also this question.
Why don't you just use Projections.SqlGroupProjection:
var result = session
.QueryOver<TableName>
.Select(Projections.SqlGroupProjection(
Time/1000 AS TimeValue",
"Time/1000",
new[]{"TimeValue"},
new[]{NHibernateUtil.Int32}))
.List<object>();
Related
I am trying to execute mysql query
SELECT COUNT( * ) FROM `Mytable` WHERE `col1` = 'value' GROUP BY MONTH(Date_time)
Laravel statement for the same is :
DB::table('Mytable')->where('col1','value')->GroupBy(MONTH('Date_time'))->count();
As query is fine but getting error :
Call to undefined function App\Http\Controllers\MONTH()
Any suggestion will be helpful
Instead of:
->GroupBy(MONTH('Date_time'))
try
->groupBy(DB::raw("MONTH('Date_time')"))
as MONTH() is a mysql function, not laravel function.
This would be your code:
DB::table('Mytable')->where('col1','value')
->groupBy(function($date) {
return Carbon::parse($date->Date_time)->format('m'); // grouping by months
})
->count();
Hope this works!
I have a query that will display columns with duplicate or with more than 1 values.I can display it using sql
select date_created,loan_id,count(1) as cnt
from collections
group by date_created,loan_id
having count(1)>1;
I want that to convert to Doctrine 1 query,I tried
public function getDuplicateDatePayment() {
$q = $this->createQuery('c')
->select('c.date_created,c.loan_id,c.count(1) as cnt')
->groupBy('c.date_created','c.loan_id')
->having('c.count(1) > 1');
return $q->execute();
}
But it only return errors.Any Idea on how to correctly convert the said working sql into a doctrine 1 query?
SQLSTATE[42000]: Syntax error or access violation: 1630 FUNCTION c.count does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual. Failing Query: "SELECT c.id AS c__id, c.date_created AS c__date_created, c.loan_id AS c__loan_id, c.count(1) AS c__0, c.count(1) AS c__0 FROM collections c GROUP BY c.date_created HAVING c.count(1) > 1"
I hope the problem may be with count. Try the following
public function getDuplicateDatePayment() {
$q = $this->createQuery('c')
->select('c.date_created,c.loan_id,count(c.1) as cnt')
->groupBy('c.date_created','c.loan_id')
->having('c.count(1) > 1');
return $q->execute();
}
I am trying to use the following query in SQL Server
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
IIf(a.expiryDate > Now(), 'TRUE', 'FALSE') AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT *
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;
but always get the error
Error in list of function arguments: '>' not recognized.
Unable to parse query text.
How do I resolve it?
Like Martin Smith said you need to use a case statement. Also it looks like you are only using a couple of fields in the derived table therefor I would suggest not using *. I put a example below.
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
case when a.expiryDate > GetDate() then 'TRUE' else 'FALSE' end AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT expiryDate, itemid
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;
I have the following Sybase query,
select *
from dbo.translation_style_sheet t1
where t1.create_date = (select max(t2.create_date)
from dbo.translation_style_sheet t2
where t1.file_name = t2.file_name);
I'm trying to convert it to a hibernate criteria query, but haven't been able to figure it out. I'm assuming I need to use a DetachedCriteria to handle this, but not sure how to work with it.
This is what I have thus far.
DetachedCriteria maxCreateDate = DetachedCriteria.forClass(TranslationStyleSheet.class, "translationStyleSheet2")
.setProjection( Property.forName("createDate").max() )
.add( Property.forName("translationStyleSheet2.fileName").eqProperty("translationStyleSheet.fileName") );
List<TranslationStyleSheet> translationStyleSheets = this.session.createCriteria(TranslationStyleSheet.class, "translationStyleSheet")
.add( Property.forName("createDate").eq(maxCreateDate))
.list();
I'm getting the following exception.
org.hibernate.exception.GenericJDBCException
could not execute query
SQL
select this_.translation_style_sheet_id as translat1_20_0_, this_.create_date as create2_20_0_, this_.description as descript3_20_0_, this_.file_content as file4_20_0_, this_.file_extension as file5_20_0_, this_.file_name as file6_20_0_, this_.file_size as file7_20_0_, this_.style_sheet_content as style8_20_0_, this_.style_sheet_type as style9_20_0_ from translation_style_sheet this_ where this_.create_date = (select max(translationStyleSheet2_.create_date) as y0_ from translation_style_sheet translationStyleSheet2_ where translationStyleSheet2_.file_name=this_.file_name)
SQLState
ZZZZZ
Does anybody know what I'm doing wrong?
UPDATE
The error seems to be be happening at the max(translationStyleSheet2_.create_date) as y0_
as. When I remove the as y0_ in the sql statement, I'm able to run the query the query, however I'm not sure how to repair this in hibernate criteria though.
So I had no success getting this to work as a criteria query, but I did have success getting it to work as an HQL query.
HQL solution
this.session.createQuery("from TranslationStyleSheet this "
+ "where this.createDate = (select max(translationStyleSheet2.createDate) "
+ "from TranslationStyleSheet translationStyleSheet2 "
+ "where translationStyleSheet2.fileName=this.fileName)")
.list();
I'm still interested in getting the query to work as a criteria query though.
I need a list of messages where each one is the most recent in the "conversation" between the current user and each other user.
The same query is described in this question
The code I have so far is:
t1 = Arel::Table.new(:messages, :as => 't1')
t2 = Arel::Table.new(:messages, :as => 't2')
convs1 = t1.
project(
t1[:receiver_user_id].as('other_user_id'),
t1[:receiver_user_id].as('receiver_user_id'),
t1[:sender_user_id].as('sender_user_id'),
t1[:created_at].as('created_at')
).
where(t1[:sender_user_id].eq(user.id))
convs2 = t2.project(
t2[:sender_user_id].as('other_user_id'),
t2[:receiver_user_id].as('receiver_user_id'),
t2[:sender_user_id].as('sender_user_id'),
t2[:created_at].as('created_at')
).
where(t2[:receiver_user_id].eq(user.id))
conv = convs1.union(convs2)
First off, I get an error:
ActiveRecord::StatementInvalid: Mysql2::Error: 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 \
'UNION SELECT `t2`...
This works if I manually replace "UNION" with "UNION ALL" in the sql produced below.
conv.to_sql from the above code produces:
SELECT `t1`.`receiver_user_id` AS other_user_id,
`t1`.`receiver_user_id` AS receiver_user_id, `
t1`.`sender_user_id` AS sender_user_id,
`t1`.`created_at` AS created_at
FROM `messages` `t1`
WHERE `t1`.`sender_user_id` = 50
UNION
SELECT `t2`.`sender_user_id` AS other_user_id,
`t2`.`receiver_user_id` AS receiver_user_id,
`t2`.`sender_user_id` AS sender_user_id,
`t2`.`created_at` AS created_at
FROM `messages` `t2`
WHERE `t2`.`receiver_user_id` = 50
Any idea why there's a MySQL UNION error. Is it an arel bug?
Secondly, any help with completing the query would be much appreciated.
Update:
Using Arel::Nodes::Union.new works
I think this is more probably a mysql fault, this is a mySQL error text. Something similar is discussed in here, but not exactly this issue.
Try to migrate to another sql server, and check again, or if union all works then use this:
conv = convs1.union(convs2, :all)
Based on documentation.
The problem is actually the parentheses in the sql. It works if I run:
Message.find_by_sql conv.to_sql.delete('()')
which removes the leading "(" and trailing ")"
Weird.. I don't know how I would chain this to complete the query. (Arel::Nodes::Union doesn't have a group method). This is Rails 3.1.4
I had a similar problem and solved it as follows:
def last_messages
Message.find_by_sql("
SELECT messages.*,
(IF(recipient_id = #{id}, 0,1)) as outlast,
users.avatar_name,
users.name
FROM messages
INNER JOIN users
ON users.id=(IF(recipient_id = #{id}, sender_id,recipient_id))
WHERE messages.id IN
( SELECT max(id)
FROM messages
WHERE recipient_id = #{id} OR sender_id = #{id}
GROUP BY (IF(recipient_id = #{id}, sender_id, recipient_id))
)
ORDER BY messages.id DESC")
end
This is the code I used instead in the end
all_msgs = Message.where("messages.sender_user_id = ? OR messages.receiver_user_id = ?",
user.id, user.id)
msg_ids = all_msgs.select("sender_user_id, receiver_user_id, max(id) as max_id")
.group(:sender_user_id, :receiver_user_id).map { |m| m.max_id }
all_msgs = all_msgs.where(:id => msg_ids)