I have a table which I would like to get all the points as SUM() for a single user_id
e.g
tblPoints
user_id points
111 50
111 100
111 100
How would I use the $criteria = new CDbCriteria() function to get the SUM(points) for the user_id of '111' - with the result being 250.
So far I have this... how would I make add SUM clause?
$Criteria = new CDbCriteria();
$Criteria->condition = "user_id = 2342312";
$Products = ShopPurchases::model()->find($Criteria);
$criteria->select = array('*', 'SUM(points) as pointsSum');
Need to define $pointsSum as a public property in your model and use:
$Products->pointsSum
Related
Hi guys,
I'm currently trying to join two objects in a same query or result.
My question is if it's possible to show or debug the sum of FIELD A FROM LEAD + sum of FIELD B FROM two different Objects.
Here's an example I'm working on:
Btw I really appreciate your time and comments, and if i'm making a mistake pls let me know, thank you.
public static void example() {
String sQueryOne;
String sQueryTwo;
AggregateResult[] objOne;
AggregateResult[] objTwo;
//I tried to save the following querys into a sObject List
List<SObject> bothObjects = new List<SObject>();
sQueryOne = 'Select Count(Id) records, Sum(FieldA) fieldNA From Lead';
objOne = Database.query(sQueryOne);
sQueryTwo = 'Select Count(Id) records, Sum(FieldA) fieldNB From Opportunity';
objTwo = Database.query(sQueryTwo);
bothObjects.addAll(objOne);
bothObjects.addAll(objTwo);
for(sObject totalRec : bothObjects) {
//There's a Wrapper(className) I created which contains some variables(totalSum)
className finalRes = new className();
finalRes.totalSum = (Integer.valueOf(fieldNA)) + (Integer.valueOf(fieldNB));
System.debug('The sum is: '+finalRes.totalSum);
For example if I call a System debug with the previous variable finalRes.totalSum it's just showing the first value(fieldNA) duplicated.
The following debug shows the current values of the sObject List which I want to sum for example FIELD0 = from leads, FIELD0 = from Opportunities.
}
}
You access the columns in AggregateResult by calling get('columnAlias'). If you didn't specify an alias they'll be autonumbered by SF as expr0, expr1... When in doubt you can always go System.debug(results);
Some more info: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm
This might give you some ideas:
List<AggregateResult> results = new List<AggregateResult>{
[SELECT COUNT(Id) records, SUM(NumberOfEmployees) fieldA, SUM(AnnualRevenue) fieldB FROM Account],
[SELECT COUNT(Id) records, SUM(Amount) fieldA, SUM(TotalOpportunityQuantity) fieldB FROM Opportunity],
[SELECT COUNT(Id) records, SUM(NumberOfEmployees) fieldA, SUM(AnnualRevenue) fieldB FROM Lead]
/* hey, not my fault these are only 2 standard numeric fields on Lead.
It doesn't matter that they're identical to Account fields, what matters is what their SUM(...) aliases are
*/
};
List<Decimal> totals = new List<Decimal>{0,0,0};
for(AggregateResult ar : results){
totals[0] += (Decimal) ar.get('records');
totals[1] += (Decimal) ar.get('fieldA');
totals[2] += (Decimal) ar.get('fieldB');
}
System.debug(totals); // (636, 8875206.0, 9819762558.0) in my dev org
(I'm not saying it's perfect, your wrapper class sounds like better idea or maybe even Map<String, Decimal>. Depends what are you going to do with the results)
I'm new to SQL, please Help me how to convert this query into LinQ
This is My Table Dept:
Id Name Sal Department
1 John 40000 Dotnet
2 mick 45000 DotNet
3 Pillay 777 Sql
Here I want to display Salary Based On Department Name, like:
DepartmentName ToalSal
Dotnet 85000
Sql 777
select DeprtmentName,sum(sal) from Dept_Emp Group by DeprtmentName
I wrote some Part of query
public IEnumerable<Dept_Emp> GetJam()
{
var x = from n in db.Dept_Emp
group n by n.Sal into g
select new
{
DeprtmentName = g.Key
};
// what I mention Here;
}
You are missing calculating sum of sal fields of grouped entities. Also you are grouping by wrong field. You should use department name for grouping
from de in db.Dept_Emp
group de by de.DeprtmentName into g
select new {
DepartmentName = g.Key,
TotalSalary = g.Sum(x => x.Sal) // aggregation here
}
What you have as output is anonymous objects. You cannot return them directly from method. You have several options here
Create custom class like DepartmentTotals with name and total salary fields, and return instances of this class instead of anonymous objects. Then return type will be IEnumerable<DepartmentTotals>.
Create Tuple<string, int> (or whatever type of salary). And return such tuples.
Use C# 7 tuples.
I have a dynamic result from Dapper query that contains records like this:
{DapperRow, billing_currency_code = 'USD', count(*) = '6'}
I'm able to access 'USD' by using rowVariable.billing_currency_code
To get '6' value I tried rowVariable["count(*)"] and rowVariable.kv["count(*)"] and unfortunately nothing works...
I can't change the count(*) column name in my case
How to get the '6' value from the rowVariable of type DapperRow in such case?
If the column name genuinely is "count(*)", then you can cast the row to a dictionary:
var data = (IDictionary<string,object>)row;
object value = data["count(*)"];
For that to work (at least, in SQL Server), your query would need to be something like:
select count(*) as [count(*)]
However, in most cases the column doesn't have a name, in which case: fix your query ;p
Actually, I'd probably say fix your query anyway; the following would be much easier to work with:
select count(*) as [Count]
Suppose Your Data as below
var Details={DapperRow, billing_currency_code = 'USD', count(*) = '6'}
as The columns is coming dynamically
var firstRow= Details.FirstOrDefault();
To get the heading columns of the data
var Heading= ((IDictionary<string, object>)firstRow).Keys.ToArray();
To get the value of the data by using key
var details = ((IDictionary<string, object>)firstRow);
var vallues= details[Heading[0]];
I have a table in Google Datastore that holds n values in n columns, and one of them is a timestamp.
The timestamp property is defined like this, inside the table class (Java):
#Persistent
private Date timestamp;
The table is like this:
id | value | timestamp
----------------------------------------------------------
1 | ABC | 2014-02-02 21:07:40.822000
2 | CDE | 2014-02-02 22:07:40.000000
3 | EFG |
4 | GHI | 2014-02-02 21:07:40.822000
5 | IJK |
6 | KLM | 2014-01-02 21:07:40.822000
The timestamp column was added later to the table, so some rows have not the corresponding timestamp value.
I'm trying, using Python Google App Engine to build an api that returns the total number of rows that have a timestamp >= to some value.
For example:
-- This is just an example
SELECT * FROM myTable WHERE timestamp >= '2014-02-02 21:07:40.822000'
I've made this class, in python:
import sys
...
import webapp2
from google.appengine.ext import db
class myTable(db.Model):
value = db.StringProperty()
timestamp = datetime.datetime
class countHandler(webapp2.RequestHandler):
def get(self, tablename, timestamp):
table = db.GqlQuery("SELECT __key__ FROM " + tablename + " WHERE timestamp >= :1", timestamp )
recordsCount = 0
for p in table:
recordsCount += 1
self.response.out.write("Records count for table " + tablename + ": " + str(recordsCount))
app = webapp2.WSGIApplication([
('/count/(.*)/(.*)', countHandler)
], debug=True)
I've successfully deployed it and I'm able to call it, but for some reason I don't understand it's always saying
Records count for table myTable: 0
I'm struggling with the data type for the timestamp.. I think the issue is there.. any idea? which type should it be declared?
Thank you!
You problem (as discussed in the comments as well) seems to be that you are passing a string (probably) to the GqlQuery parameters.
In order to filter your query by datetime you need to pass a datetime object in to the query params. For that take a look here on how to convert that.
Small example:
# not sure how your timestamps are formatted but supposing they are strings
# of eg 2014-02-02 21:07:40.822000
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f" )
table = db.GqlQuery("SELECT __key__ FROM " + tablename + " WHERE timestamp >= :1", timestamp)
I have a table Employee with say the following records
EmpID Salary Date
10 2000 1/1/2011
10 2000 2/1/2011
20 2000 1/1/2011
I want to count the total number of employees and the total salary (based on some other parameters)
Is there a easy way to write the following SQL query in entity framework.
select Sum(Salary), count(distinct(EmployeeID)) from empdb.employeesalary (where clause)
Have a class into which I need to select these values
class EmployeeEntity
{
decimal TotalAmount;
int EmployeeCount
}
I currently do two queries in EF as follows
objectcontext.employeesalary.Sum(c => c.Salary);
objectcontext.employeesalary.Select(c => c.EmployeeID).Distinct().Count();
How can I merge these into a single statement using Entity Framework. Am I missing something here.
Try something like this:
objectcontext.employeesalary
.Where(c => ...)
.GroupBy(_ => default(string))
.Select(g => new
{
Sum = g.Sum(c => c.Salary),
Count = g.Select(c => c.EmployeeID).Distinct().Count()
});
how about this ? you can merge your result of EF into your Employee Entity Class
var q = from f in objectcontext.employeesalary
where [clause]
group f by f.EmpID into g
select new EmployeeEntity
{
TotalAmount = g.Sum(c => c.Salary),
EmpmloyeeCount = g.Select(c => c.EmployeeID).Discinct().Count()
}
var EmployeeSummary = new List<EmployeeEntity>(q.ToList());