EF multiple aggregate in single query - entity-framework

I want to get count of a set based on different condition:
var invoices = new AccountingEntities().Transactions
var c1 = invoices.Count(i=>i.Type = 0);
var c2 = invoices.Count(i=>i.Type = 1);
var c3 = invoices.Count(i=>i.Type = 2);
How its possible to call all three queries in one DB round trip to increase performance?

Sure, just wrap up your three counts in a POCO or anonymous type:
using (var invoices = new AccountingEntities())
{
var c = (from i in invoices.Transactions
select new
{
c1 = invoices.Count(i=>i.Type = 0),
c2 = invoices.Count(i=>i.Type = 1),
c3 = invoices.Count(i=>i.Type = 2)
}).Single();
}
Also, dispose your context, as I show.

To aggregate arbitrary subqueries, use a dummy single-row result set from which you nest the desired subqueries. Assuming db represents your DbContext, the code to count invoice types will look like this:
var counts = (
from unused in db.Invoices
select new {
Count1 = db.Invoices.Count(i => i.Type == 0),
Count2 = db.Invoices.Count(i => i.Type == 1),
Count3 = db.Invoices.Count(i => i.Type == 2)
}).First();
If the want to generically get a count of all types, use grouping:
var counts =
from i in db.Invoices
group i by i.Type into g
select new { Type = g.Key, Count = g.Count() };

Related

PowerBI Cumulative Distinctcount by Date, Condition and through Dimension

I have the following Table:
It represents cases on which a certain Team is working on over the Time until the case is closed.
And there is also a Date Table over column Date.
I would like to cumulative count the open cases until the selected date.
So I used this measure:
CountOpen =
VAR CurrentDate = MAX('Date'[Date])
VAR Closed =
CALCULATE(
DISTINCTCOUNT(Tabelle1[case]),
ALL('Date'),'Date'[Date]<=CurrentDate,Tabelle1[Status_Open]="0")
VAR OpenAll =
CALCULATE(
DISTINCTCOUNT(Tabelle1[case]),
ALL('Date'),'Date'[Date]<=CurrentDate,Tabelle1[Status_Open]="1")
RETURN OpenAll-Closed
And it works for the overall view. But for the view within the Dimension CurrentTeam it's not correct:
It should be:
a = 0
b = 1
c = 0
So... this is actually quite tricky, you have to pick the latest status per case up to the selected date. In my solution I create a table, with a column R which ranks the cases per date, then in the result I filter for those depending on which team you have selected.
Measure is below:
VAR CurrentDate = MAX('Date'[Date])
VAR CurrentTeam = SELECTEDVALUE(Tabelle1[CurrentTeam])
VAR tbl =
SUMMARIZE(
FILTER(ALL('Tabelle1'), 'Tabelle1'[Date] <= CurrentDate),
Tabelle1[case],
Tabelle1[CurrentTeam],
Tabelle1[Status_Open],
Tabelle1[Date],
"R",
VAR c = MAX(Tabelle1[case])
VAR d = LASTDATE(Tabelle1[Date])
RETURN
CALCULATE(DISTINCTCOUNT(Tabelle1[Date]),
ALLSELECTED(Tabelle1),
Tabelle1[case] = c,
Tabelle1[Date] >= d)
)
RETURN SUMX(
FILTER(tbl,
[R] = 1 &&
(ISBLANK(CurrentTeam) || [CurrentTeam] = CurrentTeam) &&
[Status_Open])
, 1) + 0 //+0 is here to show 0 where it would be blank

In dart how add multiple list in a list?

I want to add multiple List in a List. The Length of the Outer loop is 2
and the length of the inner loop is 2.
List matchName = [];
List a = [];
List b = [];
void getMatchName(GetUserMatchModelRes m) {
matchName.clear();
for (var i = 0; i < m.ObjectList.length; i++) {
matchName.clear();
matchName.add(
m.ObjectList[i].ContactName,
);
print("i:$i");
for (var j = 0; j < m.ObjectList[i].ContactPhones.length; j++) {
print("j:$j");
matchName.add(
m.ObjectList[i].ContactPhones[j].MatchedContactName,
);
}
a.add(matchName);
print(a);
}
}
Output when outer loop is 0: [[a,b,c]]
When outer loop is 1: [[d,e,f],[d,e,f]]
But I want [[a,b,c],[d,e,f]]
How I can achieve this?
You're essentially doing:
var outer = <List<String>>[];
var inner = ['foo'];
outer.add(inner);
outer.add(inner);
Now outer has two elements that refer to the same object:
+---+---+
outer: | | |
+-|-+-|-+
| |
v v
+-------+
inner: | 'foo' |
+-------+
If you modify inner, you'll see the change in both outer[0] and in outer[1].
To avoid this, you need to add separate objects so that they can be modified independently. Either create new lists to add instead of modifying an existing one:
var outer = <List<String>>[];
outer.add(['foo']);
outer.add(['foo']);
or add copies:
var outer = <List<String>>[];
var inner = ['foo'];
outer.add([...inner]);
outer.add([...inner]);

AGGrid - Aggregation, Filtering

In agGrid, I have an aggregation which is based on two columns. When I apply filter, the aggregates based on two columns are not updated. There is no problem with sum, max, min aggregate functions as all these are based on same column.
here is the steps I follow,
Group by a Column --> Value Aggregation --> Weighted Avg(Custom Aggregation) --> Add a filter.
When I add a filter after weighted avg aggregation calculation, the new weighted avg is not refreshed.
I have this aggregate calculated using a valueGetter function (as in the code below).
Is there a way to update the aggregates which comes from a valueGetter function when I modify the filter?
Thanks in advance.
Regards,
Vijay.
function weightedAverageGetter(params) {
var col = params.column.colId.split('.')[1];
var value = 0;
if (params.data){
value = params.data.qli?params.data.qli[col]:0;
if (col == 'P1prime__c' || col == 'P2Prime__c'){
value = Math.ceil(value);
}
}
var avgW = 0;
if (params.node){
var sumVal = 0;
var sumQty = 0;
for (var node in params.node.allLeafChildren){
var nodeValue = params.node.allLeafChildren[node];
var val = 0;
var qty = 0;
if (nodeValue.data){
val = nodeValue.data.qli?nodeValue.data.qli[col]:0;
qty = nodeValue.data.qli?parseFloat(nodeValue.data.qli.Quantity):0;
}
if (typeof val !=='undefined' && val != '' && typeof qty !=='undefined' && qty != '') {
sumQty += qty;
sumVal += qty*val;
}
}
avgW = sumVal/sumQty;
}
avgW = Math.round(avgW * 100) / 100;
if(!params.column.aggregationActive || Number.isNaN(avgW)){
avgW = '';
}
return params.data?value:avgW;
}

How to exclude a column when using getAllColumns property in ag-grid

I have a function that counts and hides the number of columns that does not fit the screen. I want to exclude a column when resizing and hiding the columns. Here is what I have.
let ctrOfColumns = this.gridOptionsValue.columnApi.getAllColumns();
this returns the columns that i have. I want to exclude a specific column which has a colId of 'toBeExcludedId' so that It won't be included in the hiding of columns algo.
Here is my algo in hiding of the columns
let gridWidthOfMyTable = $('#idOfMyGrid').outerWidth();
let columnsToBeShown = [];
let columnsToBeHidden = [];
let totalWidthOfColumn = 0;
for(let x = 0 ; x < ctrOfColumns.length; x ++){
const singleColumn = ctrOfColumns[x];
totalWidthOfColumn += singleColumn.getMinWidth();
if (totalWidthOfColumn > gridWidthOfMyTable) {
columnsToBeHidden.push(singleColumn);
} else {
columnsToBeShown.push(singleColumn);
}
}
this.gridOptionsValue.columnApi.setColumnsVisible(columnsToBeShown, true);
this.gridOptionsValue.columnApi.setColumnsVisible(columnsToBeHidden, false);
There is no need to loop through all the values in your array. You can just use chaining and apply a filter directly to getAllColumns(), like this:
let ctrOfColumns = this.gridOptionsValue
.columnApi
.getAllColumns()
.filter((column) => column.colId !== 'toBeExcludedId');

How to get total number of records across all databases in MongoDB?

Is there any way through which i can get total number of records across all the databases in MongoDB server.
There is command for finding total records in a particular collection of a databases. But i want to get the count of total number of records across all databases.
Simply use db.stats
db.stats().objects
The objects property return the count of documents in the database across all collections.
To get the total number across all databases, you may need to do something like this:
let client = db.getMongo();
client.getDBNames().filter( name => name !== 'local')
.map( elt => client.getDB(elt).stats().objects )
.reduce( ( acc, cur ) => acc + cur, 0);
can use this
var alldbs = db.getMongo().getDBNames();
for(var j = 0; j < alldbs.length; j++)
{
var db = db.getSiblingDB(alldbs[j]);
var collections = db.getCollectionNames();
for(var i = 0; i < collections.length; i++){
var name = collections[i];
if(name.substr(0, 6) != 'system'){
var c = db.getCollection(name).count() ;
print(db + ' ' + name + ' ' + c );
}
}
}
You can use this simple python script
from pymongo import MongoClient
client = MongoClient()
cot = 0
db_list = client.database_names()
for item in db_list:
db = client[item]
col = db.collection_names()
try:
num = db[col[0]].count()
except Exception:
num = 0
cot += int(num)
print('\tšŸ“ˆ' + str(cot))