Retrieve without timestamp - sql

I am trying to fetch updated_at without timestamp in order by but unable to do so. I am using date_trunc function but unable to get proper result.Apart from this is there any other function which can give me only date not timestamp
users = User.members(current_user,params).order("date_trunc('datepart', updated_at) DESC, upvotes DESC").paginate(:per_page => PER_PAGE,:page => (params[:page] || 1))

Try following.
users = User.members(current_user,params).order("updated_at.to_date DESC, upvotes DESC").paginate(:per_page => PER_PAGE,:page => (params[:page] || 1))
or
users = User.members(current_user,params).order('updated_at.strftime("%Y-%m-%d") DESC, upvotes DESC').paginate(:per_page => PER_PAGE,:page => (params[:page] || 1))
or
users = User.members(current_user,params).order('updated_at.strftime("%F") DESC, upvotes DESC').paginate(:per_page => PER_PAGE,:page => (params[:page] || 1))

Related

how to use subquery in order by with case in nhibernate?

I need to fetch result from DB table using nhibernate with QueryOver for below sql query. The SQL request is like this:
SELECT Id, Name, Address,phone,ispassed
FROM employee WHERE ispassed = 1
ORDER BY
(CASE WHEN id in (select empId from salary where empId in (2,45,65) and Type=5) THEN 0 ELSE 1 END) asc,
Name desc
I am stuck in Order by. So, please give an example to construct nhibernate query for
ORDER BY
(CASE WHEN id in (select empId from salary where empId in (2,45,65)
and Type=5) THEN 0 ELSE 1 END) asc
I have sub query as :
var subquery = QueryOver.Of<salary>()
.Where(x => x.Type == 5 && x.empId.IsIn(2,65,45))
.SelectList(list => list
.Select(Projections.Distinct(Projections.Property<salary>(x => x.empId))));
and when I am adding subquery in main query as :
query.OrderBy(Projections.Conditional(
Restrictions.In(Projections.SubQuery(subquery)),
Projections.Constant(0),
Projections.Constant(1))).Asc();
It is showing error as "The best overloaded method match for 'NHibernate.Criterion.Projections.SubQuery(NHibernate.Criterion.DetachedCriteria)' has some invalid arguments."
I hope that's what you want:
Employee employeeAlias = null;
var subquery = QueryOver.Of<salary>()
.Where(x => x.Type == 5 && x.empId.IsIn(2,65,45))
.And(x => x.empId == employeeAlias.Id)
.Select(x => x.empId);
var query = session.QueryOver(() => alias)
.Where(x => x.IsPassed)
.OrderBy(Projections.Conditional(
Subqueries.Exists(subquery.DetachedCriteria),
Projections.Constant(0),
Projections.Constant(1))
).Asc
.ThenBy(x => x.Name).Desc
//.Select
//.List
;

Why won't my Rails model save into the Database?

def self.build_prior_month(payee, as_of = Time.current, opts = {})
start_date, end_date, year, month = effective_dates(as_of)
statement = payee.earnings_statements.build(
:year => year,
:month => month,
:balance => 0,
:revenue => 0
)
statement.generate(start_date, end_date, year, month)
statement.update_totals
statement
end
That's a function that I have in a model of mine. It returns statement properly, but doesn't save to the database. Why is that?
The generate function looks like:
def generate_ledger_items(start_date, end_date, year, month)
payee.ledger_entries.for_month_and_year(month, year).each do |entry|
earnings_statement_items.build(
:items => entry.item_group,
:units => entry.units,
:net_revenue => entry.net_revenue,
:net_revenue_per_unit => [entry.net_revenue, entry.units].all? ? (entry.net_revenue / entry.units).round(2) : nil,
:fees => entry.service_fees,
:payments_collected => entry.spendings,
:fee_terms => entry.terms || entry.description, # When would terms be set?
:due => entry.credit || -entry.debit
)
end
end
def update_totals
self.revenue = earnings_statement_items.net_revenue
self.balance = earnings_statement_items.total
end
The build method on your association does not actually save the record into the database. create will. It is similar to the difference between new and create on your models.
statement = payee.earnings_statements.create(
:year => year,
:month => month,
:balance => 0,
:revenue => 0
)
Will save your record. See the documentation.
.build doesn't save the object
call:
statement.save

no id for model?

I get the error
undefined local variable or method `id' for #<Class:0x007fe1dc4e3bb0>
when defining a sql call in my model user:
RECENT_EVENTS_CONDITION = "(user_id = #{id}) OR user_id IN (SELECT user_b_id AS user_id FROM user_follows WHERE user_follows.user_a_id = #{id} )"
Model code
has_many :recent_events,
:class_name => "Activity",
:finder_sql => 'SELECT activities.* FROM activities
WHERE ' + RECENT_EVENTS_CONDITION + '
ORDER BY activities.created_at DESC',
:counter_sql => 'SELECT COUNT(*) FROM activities
WHERE ' + RECENT_EVENTS_CONDITION
Everything works fine until i introduce this recent_events ...
I'm assuming this is a User class or something similar, and I'm assuming when you use #{id}, you're really just trying to use the user's id. So I would do this instead:
RECENT_EVENTS_CONDITION = "(user_id = users.id) OR user_id IN (SELECT user_b_id AS user_id FROM user_follows WHERE user_follows.user_a_id = users.id )"

Rails3/ActiveRecord: select sum with parameters?

Give the following (already simplified) query in SQLite:
def self.calculate(year, month, user_id, partner_id)
where(':user_id = entries.user_id OR :partner_id = entries.user_id', {
:user_id => user_id,
:partner_id => partner_id
}).
where('entries.date <= :last_day', {
:last_day => Date.new(year, month, 1).at_end_of_month
}).
select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {
:user_id => user_id
}).
group("strftime('%Y-%m', date)")
end
The full query has more sums with different case when statements and some of them depend on whether it is user_id oder partner_id. Unfortunately, Rails complains as select does not take the second parameter with the substitutions like where does. Is there any way to achieve what I want without running two queries, one for user_id and one for partner_id?
One can be so blind....instead of:
select('sum(case when joint = "f" and user_id = :user_id then amount_calc else 0 end) as sum_single' , {
:user_id => user_id
}).
just build the string:
select('sum(case when joint = "f" and user_id = ' + user_id.to_s + ' then amount_calc else 0 end) as sum_single').
As nobody answered, this is for the archives :)
Edit: Sorry, beware of that: as noted below, this is vulnerable.

Converting SQL containing top, count, group and order to LINQ (2 Entities)

Some LINQ queries still puzzle me.
for a table 'Hits' containing two columns, 'Page' and 'Date', I want to find the most Pages with the most rows in a defined slice of time.
In SQL I would use this:
SELECT TOP 10
[Page]
,COUNT([Page]) as Number
FROM dbo.[Hits]
WHERE [Date] >= CONVERT(datetime,'14 Jan 2009')
AND [Date] < CONVERT(datetime,'15 Jan 2009')
Group BY [Page]
Order by Number DESC
In LINQ I got no idea how to approach this, can anyone help me here? I tried to convert it using linqer, but it just shows an error for this expression.
Something like this should work:
(from p in DataContext.Hits
where (p.Date >= minDate) && (p.Date < maxDate)
group p by p.Page into g
select new { Page = g.Key, Number = g.Count() }).OrderByDescending(x => x.Number).Take(10);
var top10hits = objectContext.Hits
.Where(h => minDate <= h.Date && h.Date < maxDate)
.GroupBy(h => h.Page)
.Select(g => new { Page = g.Key, Number = g.Count() })
.OrderByDescending(x => x.Number)
.Take(10);