Peewee: Querying SUM of field/column - peewee

I've been trying to get the sum total of a field/column in peewee. I thought it would be straightforward, but I've been going around in circles for a couple of hours now.
All I'd like to get back from the query is sum total of the price field/column.
An example of the code I've been using is:
Model
class Package(db.Model):
id = PrimaryKeyField()
code = CharField(max_length=11, unique=True, null=False)
price = DecimalField(null=False, decimal_places=2)
description = TextField()
created = DateTimeField(default=datetime.now, null=False)
updated = DateTimeField(default=datetime.now, null=False)
Query
sum_total = fn.SUM(Package.price).alias('sum_total')
query = (Package
.select(sum_total)
.order_by(sum_total)
)
The outputs I'm getting are:
query.sum_total
AttributeError: 'ModelSelect' object has no attribute 'sum_total'
for q in query:
logger.debug(json.dumps(model_to_dict(q)))
{"code": null, "created": null, "description": null, "id": null, "numberOfTickets": null, "price": null, "updated": null}
I've sure I'm missing something really simple. I haven't been able to find any examples outside of the peewee documentation, and I've tried those, but am still getting nowhere.
Any ideas?

The "model_to_dict()" method is not magic. It does not automatically infer that you want to actually just dump the "sum_total" column into a dict. Additionally, are you trying to get a single sum total for all rows in the db? If so this is just a scalar value, so you can write:
total = Package.select(fn.SUM(Package.price)).scalar()
return {'sum_total': total}
If you want to group totals by some other columns, you need to select those columns and specify the appropriate group_by() - for example, this groups sum total by code:
sum_total = fn.SUM(Package.price).alias('sum_total')
query = (Package
.select(Package.code, sum_total)
.group_by(Package.code)
.order_by(sum_total))
accum = []
for obj in query:
accum.append({'code': obj.code, 'sum_total': obj.sum_total})

Related

Combine two JSON queries on Power BI

I am retrieving data from an Orchestrator (with a JSON code) to Power BI and for authentication I need to give the variable OrganizationUnitID as follows:
let
Path = "/odata/A",
Auth = Json.Document(Web.Contents(BaseUrl, [Headers=[#"Content-Type"="application/x-www-form-urlencoded"], Content=Text.ToBinary(Uri.BuildQueryString(Credentials))])),
Token = Auth[access_token],
A = Json.Document(Web.Contents(TenantUrl&Path, [Headers=[Accept="application/json", #"Authorization"="Bearer " & Token, #"OrganizationUnitId"="12345"]]))
in A
(PS: I did not post the entire query so that the post is not so long).
However, I would like to retrieve data for all OrganizationUnitIDs. These I can also retrieve as a query (= Id1 below), it currently comes as a list with 15 values:
let
Path = "/odata/Test",
Auth = Json.Document(Web.Contents(BaseUrl, [Headers=[#"Content-Type"="application/x-www-form-urlencoded"], Content=Text.ToBinary(Uri.BuildQueryString(Credentials))])),
Token = Auth[access_token],
Test = Json.Document(Web.Contents(TenantUrl&Path, [Headers=[Accept="application/json", #"Authorization"="Bearer " & Token]])),
value = Test[value],
#"Converted List to Table" = Table.FromList(value, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Expanded Records to Table" = Table.ExpandRecordColumn(#"Converted List to Table", "Column1", {"Name","Id"}, {"Name","Id"}),
Id1 = #"Expanded Records to Table"[Id]
in
Id1
My question is: can I / how can I combine this second query with the first one, so that in the first one I can include all the 15 OrganizationUnitIds?
I have tried some solutions posted online but so far none have worked.

POWER BI - DAX - Measure filter

I have a dax measure . This measure have 1 data . This is "GOOGLE";"YOUTUBE";"AMAZON"
I want to use this 1 line string result in FILTER.
CALCULATE(SUM(_TABLE);_TABLE.COMPANIESNAME; FILTER(_TABLE.COMPANIESNAME IN { mymeasure } ))
Does anyone can help me solve this problem ?
Thank you for help
There are probably way better ways to do what you want. You are treating Power BI like a relational database when you should be using it like a Star Schema. But without more info, I'm just going to answer the question.
Here's my sample table:
// Table
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcsxNrMrPU9JRMlSK1YlWcs/PT89JBXKNwNzI/NKQ0iQQ3xjMd0tMTk3Kz88GCpgoxcYCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Company = _t, Count = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Count", Int64.Type}})
in
#"Changed Type"
I don't have your DAX measure or its name, so I'm using this:
CompanyList = """Google"";""YouTube"";""Amazon"""
Just to prove it's the same as your measure, here it is in the report:
From this post I created a DAX formula that will parse your DAX value into a table with one row for each company name. Add this as a DAX table from Modeling > New Table. I named mine "Filtered table".
Filtered table = VAR CommaSeparatedList = [CompanyList]
VAR BarSeparatedList =
SUBSTITUTE ( CommaSeparatedList, ";", "|" )
VAR Length =
PATHLENGTH ( BarSeparatedList )
VAR Result =
SELECTCOLUMNS (
GENERATESERIES ( 1, Length ),
"Company", SUBSTITUTE( PATHITEM ( BarSeparatedList, [Value] ), """", "")
)
RETURN
Result
Here's what the table looks like:
Add a relationship between the two tables like this (Modeling > Manage relationships > New...):
Then add a DAX column to the filtered table by selecting the table and then Modeling > New Column
Count = CALCULATE(SUM('Table'[Count]))
You can total it up with this DAX measure:
Filtered total = SUM('Filtered table'[Count])
Change the CompanyList measure, and result will update:

Multiple AggregateResult Querys

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)

Cypher statement with distinct match conditions is returning the same result

I am using Neo4j as a database to store voting information related to another database object.
I have a Vote object which has fields:
type:String with values of UP or DOWN.
argId:String which is a string ID value linking to a unique argument object
I am trying to query the number of votes assigned to a given argId using the following queries:
MATCH (v:Vote) WHERE v.argId = '214' AND v.type='DOWN'
RETURN {downvotes: COUNT(v)} AS votes
UNION
MATCH (v:Vote) WHERE v.argId = '214' AND v.type='UP'
RETURN {upvotes: COUNT(v)} AS votes
Note that this above cypher -- works and returns the expected result result like so:
[
{
"downvotes": 1
},
{
"upvotes": 10
}
]
But I feel like the query could be a bit neater and want to write something like this:
MATCH (v:Vote) WHERE v.argId = '214' AND v.type='UP'
MATCH (b:Vote) WHERE b.argId = '214' AND b.type='DOWN'
RETURN {upvotes: COUNT(v), downvotes: COUNT(b)}
Just reading it through, I think it makes sense, b and v are declared as separate variables, so all should be good (so I thought).
But running it given me this:
{
"upvotes": 10,
"downvotes": 10
}
But it should be what I have above.
Why is this?
I'm kinda new to neo4j and cypher so I've probably not understood how cypher works fully.
Can anyone shine any light?
Thank you!
p.s. I'm using Neo4j 3.5.6 and running the queries via the Desktop web browser app.
I think if you run this query you will get a clearer picture of what is happeneing. Your query produces a cartesian product of the upvotes(10) and the downvotes(1). The product is a result set of 10 rows. When they are subsequently counted, there are ten of each.
MATCH (v:Vote) WHERE v.argId = '214' AND v.type='UP'
MATCH (b:Vote) WHERE b.argId = '214' AND b.type='DOWN'
RETURN v.type, b.type
In order to get the result you want you need to filter the values and count them individually.
Rather than have two match statements, have a single match statement that retreives all of the values of interest and then use a conditional statement to filter them into upvotes and downbotes buckets.
Something like this may suit you.
MATCH (v:Vote {argId: '214'})
WHERE v.type IN ['UP', 'DOWN']
RETURN {
upvotes: count(CASE WHEN v.type = 'DOWN' THEN 1 END),
downvotes: count(CASE WHEN v.type = 'UP' THEN 1 END)
} AS vote_result
Using APOC you could do something like this whereby you use the type values themselves to aggregate the counts and then use APOC to convert it to a map with the types as the keys in the map.
MATCH (v:Vote {argId: '214'})
WHERE v.type IN ['UP', 'DOWN']
WITH [v.type, count(*)] AS vote_pair
RETURN apoc.map.fromPairs(collect(vote_pair)) AS votes

Go + App Engine Datastore: How to filter out rows that are null?

How do I filter out rows that are null? I know it's hard to find only-null rows, but hopefully this should be easier.
I'd like to do the following:
q := datastore.NewQuery("MY_KIND").Filter("MY_ID !=", nil)
... but Filter doesn't support the != comparator. FYI, using this GQL syntax in the Datastore Viewer works just fine:
SELECT * FROM MY_KIND WHERE MY_ID != NULL
You can use greater filter with the appropriate value (> 0 for numbers, > "" for strings).
Typically an ID cannot be an empty string or zero.
Here's what works for me.
// Datastore entity with null value
// `DeletedAt` in my case is *time.Time
{
"DeletedAt": NULL,
"Version": 1,
...
}
Here's my query to get records where DeletedAt is NULL:
datastore.NewQuery("MyKind").Filter("DeletedAt =", (*time.Time)(nil))
Hope that this will be helpful to someone of you.

Resources