Add Commas to a Sum LinQ - sql

I have a Group by Sum operation, but i would like to add ',' every 3 digits
right now i get this output:
{ Pdv = REST, Total = $20786 }
But i would like this Output:
{ Pdv = REST, Total = $2,0786 }
This is my Linq Group By:
foreach (var item in Model.Select(x => new //here you count your total
{
Rid = x.Rid,
Total = x.Total
})
.GroupBy(l => l.Rid) //and then grouping
.Select(z => new
{
Turno = z.Key,
Total = "$" + Decimal.Round(z.Sum(l => l.Total), 0)
}))
{
//Loop Code
}

Your "Total" must be String.
String.Format("{#,##0.00}", 1243.50); // Outputs "1,243.50"
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 1243.50); // Outputs "$1,243.50"
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", -1243.50); // Outputs"($1,243.50)"
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 0); // Outputs “Zero"

Related

how to add conditional where parameters to sql query in node js

I have the below method that aims to filter records from a table. But sometimes, the user might only select one filter or two. I want to add where conditions only for parameters that the user sends. At the moment, it filters with all conditions. One possibility I know is to use some conditions to concatenate the string if true but I do not think this is the best way.
Any better way of doing this?
// Retrieve hotels by filter
app.get('/filter', (request, response) => {
var name = request.query.name;
var country = request.query.country;
var freeWifi = request.query.freeWifi;
var freeParking = request.query.freeParking;
var restaurant = request.query.restaurant;
var pool = request.query.pool;
var gym = request.query.gym;
var airconditioning = request.query.airconditioning;
let query = `select * from hotels h inner join hotelFilters hf on h.id = hf.hotelId where h.title like "%${isNullOrUndefined(name) ? '' : name}%"
and hf.freeWifi = ${freeWifi} and hf.freeParking = ${freeParking} and hf.restaurant = ${restaurant} and hf.outdoorPool = ${pool}
and hf.airConditioning = ${airconditioning}
and hf.gym = ${gym}`;
connection.query(query, (error, result) => {
if (error) {
console.log(error, 'Error occurred with hotels/filter API...');
}
if (result.length > 0) {
response.send({
result
})
}
})
});

In JavaScript, retrieve the value and performed the addition after that want to return the value after the for loop in cypress automation?

verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.log("Total of all connected OS= " + sum)
}
In the cypress automation, when I'm running this block of code it is returning the sum=0 but I don't know why it is displaying 0. Please help me out.
Cypress commands are asynchronous.
cy.log captures the sum value before the first xpath command gets really executed.
To synchronize access to the sum you can use a then callback:
verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.then(() => {
cy.log("Total of all connected OS= " + sum)
})
}
Look at this article for details on how to handle variables at Cypress.

.NET Core - EF - trying to "OR" built up Where's in a for loop

I try to filter data using multiple Where, built up in a loop. They must be chained with a OR
I read I should use PredicateBuilder from this page ttp://www.albahari.com/nutshell/predicatebuilder.aspx
problem : it does not return any data
I managed to debug the final query and noticed
the OR clauses are not present
a strange CAST line was present (which when I remove it, data appear)
here is the part that adds to the IQueryable:
IQueryable<Lead> data = context.Leads.AsQueryable();
List<ZipCodeRange> ranges = Tools.CreateZipCodesRanges();
var items = JsonConvert.DeserializeObject<List<MenuItem>>(leadsSearch.searchByZipcodes);
var activeRanges = items
.Where(item=>item.active)
.Select(item => ranges[item.id])
.ToList();
data = data.Where(d => activeRanges.Any(range => range.Min <= d.Company.ZipCodeNum &&
range.Max >= d.Company.ZipCodeNum));
var leads = await data.ToListAsync();
here is how I generate the ranges :
public static List<ZipCodeRange> CreateZipCodesRanges()
{
List<ZipCodeRange> zipCodeRanges = new List<ZipCodeRange>();
zipCodeRanges.Add(new ZipCodeRange() { Min = 1000, Max = 1495 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 4000, Max = 7999 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 1500, Max = 1999 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 2000, Max = 2699 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 2800, Max = 2999 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 3000, Max = 3499 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 3500, Max = 3999 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 8000, Max = 8999 });
zipCodeRanges.Add(new ZipCodeRange() { Min = 9000, Max = 9999 });
return zipCodeRanges;
}
here is the generated query:
SELECT [l].[Id], [l].[AdminNotes], [l].[CompanyId], [l].[ContactId], [l].[CreationDate], [l].[CreationUserId], [l].[FacialValue], [l].[FedEce], [l].[FirstOrderDate], [l].[Identifier], [l].[LastOrderDate], [l].[Locked], [l].[ModificationDate], [l].[ModificationUserId], [l].[Notes], [l].[PartnerId], [l].[PrestationPercent], [l].[Products], [l].[Status], [l].[TicketsPerDay], [l].[ToTreat], [c].[Id], [c].[BceNumber], [c].[Box], [c].[City], [c].[Country], [c].[Name], [c].[Number], [c].[Size], [c].[Street], [c].[ZipCode], [c].[ZipCodeNum], [c0].[Id], [c0].[Civility], [c0].[CreationDate], [c0].[CreationUserId], [c0].[Email], [c0].[FirstName], [c0].[Language], [c0].[LastName], [c0].[Mobile], [c0].[ModificationDate], [c0].[ModificationUserId], [c0].[Phone], [c0].[Position], [c0].[Type]
FROM [leads] AS [l]
INNER JOIN [companies] AS [c] ON [l].[CompanyId] = [c].[Id]
INNER JOIN [contacts] AS [c0] ON [l].[ContactId] = [c0].[Id]
WHERE CAST(0 AS bit) = CAST(1 AS bit)
what am I doing wrong ?
thanks for your help
[edit]
System.InvalidOperationException: The LINQ expression 'DbSet<Lead>
.Join(
outer: DbSet<Company>,
inner: l => EF.Property<Nullable<int>>(l, "CompanyId"),
outerKeySelector: c => EF.Property<Nullable<int>>(c, "Id"),
innerKeySelector: (o, i) => new TransparentIdentifier<Lead, Company>(
Outer = o,
Inner = i
))
.Where(l => __activeRanges_0
.Any(range => (Nullable<int>)range.Min <= l.Inner.ZipCodeNum && (Nullable<int>)range.Max >= l.Inner.ZipCodeNum))' could not be translated.
This can be achieved without using PredicateBuilder by simply doing
var data = context.Leads
.Where(lead => items.Any(item => item.Min <= lead.Company.ZipCodeNum &&
item.Max >= lead.Company.ZipCodeNum))
Edit
For your updated code in the screenshot just remove the foreach at all and replace it with
var activeRanges = items
.Where(item.active)
.Select(item => ranges[item.id])
.ToList();
data = data.Where(d => activeRanges.Any(range=> range.Min <= d.Company.ZipCodeNum &&
range.Max >= d.Company.ZipCodeNum))
Since I cant get an answer, maybe EF is limited or something , so I did it this way:
List<int?> leadsIdsAll = new List<int?>();
foreach (var item in items)
{
if(item.active)
{
ZipCodeRange range = ranges[item.id];
List<int?> leadsIds = context.Leads.Where(l => range.Min <= l.Company.ZipCodeNum && range.Max >= l.Company.ZipCodeNum)
.Select(l => l.Id).ToList();
leadsIdsAll.AddRange(leadsIds);
}
}
data = data.Where(l => leadsIdsAll.Contains(l.Id));

Datatable sum column by row grouping and show sum result at the end of each group

I am using datatable row grouping from https://datatables.net/examples/advanced_init/row_grouping.html and it works fine.
I have following scenario:
Now I want to calculate sum(sub-total) by each grouping abd show result in row at the end of grouping as you see in image.
At the end of listing , want to show a final row of total amount.
How to accomplish that.
Js used code is:
$(function() {
var table = $('#table').DataTable({
"columnDefs": [
{ "visible": false, "targets": 1 }
],
"order": [[ 1, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(1, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group" style="background-color:#F5F5F5;"><td colspan="3">'+group+'</td></tr>'
);
last = group;
}
} );
}
});
});
For the same exemple here : https://datatables.net/examples/advanced_init/row_grouping.html
I have made some changes inside "drawCallback": function ( settings ) {
Check this fiddle https://jsfiddle.net/bLykqbo6/110/
I hope it helps
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last = null;
var sum = 0;
var groupColumn = 1; //index of column which you are going to group by.
var amtColumn = 3; // index of column which you are going to sum.
api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
api.rows().data().each( function(item){
if (item[groupColumn] == group){
sum = sum + (+item[amtColumn]);
}
});
$(rows).eq( i ).before(
'<tr class="group"><td colspan="2" style="background-color: #e7e7e7;"><b>'+group+'</b></td><td style="background-color: #e7e7e7;"><b>'+ sum +'</b></td></tr>'
);
last = group;
sum = 0;
}
});
}

Create a running sum graph in dc.js

I am trying to create a running sum in crossfilter to use with dc.js.
I have a set of records like the following :
records = [{"date":"2014-01-01","field1":"value1","field2":"value11","value_field":-20},
{"date":"2014-01-02","field1":"value2","field2":"value12","value_field":100},
{"date":"2014-01-03","field1":"value1","field2":"value11","value_field":-10},
{"date":"2014-01-04","field1":"value2","field2":"value12","value_field":150},
]
So far I have created a barGraph which plays nicely with the other dimensions but I would like to be able to show an line graph of the theoretical field runnning_total (along the dimension date).
To have it done in crossfilter would allow me to then group using the fieldx fields and easily get the same running total graph but restricted to a subgroup of values using dc.js.
Any help is welcome.
Since you are grouping across date (as per your date dimension), the reduce() function would be used to perform aggregations grouped by date, as per the highlighted cells in my Mickey Mouse example below:
With a running total you'd need to perform an entirely different operation, looping down the rows:
You can aggregate the data and then append the running total field as follows. I've also included an example of how to calculate an average value, using the reduce function:
records = [{ "date": "2014-01-01", "field1": "value1", "field2": "value11", "value_field": -20 },
{ "date": "2014-01-02", "field1": "value2", "field2": "value12", "value_field": 100 },
{ "date": "2014-01-03", "field1": "value1", "field2": "value11", "value_field": -10 },
{ "date": "2014-01-04", "field1": "value2", "field2": "value12", "value_field": 150 }
];
var cf = crossfilter(records);
var dimensionDate = cf.dimension(function (d) {
return d.date;
});
function reduceAdd(p, v) {
p.total += v.value_field;
p.count++;
p.average = p.total / p.count;
return p;
}
function reduceRemove(p, v) {
p.total -= v.value_field;
p.count--;
p.average = p.count ? p.total / p.count : 0;
return p;
}
function reduceInitial() {
return {
total: 0,
count: 0,
average: 0,
};
}
var average = dimensionDate.group().reduce(reduceAdd, reduceRemove, reduceInitial).all();
var averageWithRunningTotal = appendRuningTotal(average);
function appendRuningTotal(average) {
var len = average.length,
runningTotal = 0;
for (var i = 0; i < len; i++) {
runningTotal += average[i].value.total;
average[i].RunningTotal = runningTotal;
}
return average;
}
And this returns the following:
{"key":"2014-01-01","value":{"total":-20,"count":1,"average":-20},"RunningTotal":-20}
{"key":"2014-01-02","value":{"total":100,"count":1,"average":100},"RunningTotal":80}
{"key":"2014-01-03","value":{"total":-10,"count":1,"average":-10},"RunningTotal":70}
{"key":"2014-01-04","value":{"total":150,"count":1,"average":150},"RunningTotal":220}
Well I know the op already built a solution but after struggling with for a while I was able to crack it, so posting it here if someone else searches for it.
using the cumulative for the following: https://groups.google.com/forum/#!topic/dc-js-user-group/W9AvkP_dZ0U
Running Sum:
var _group = dim.group().reduceSum(function(d) {return 1;});
var group = {
all:function () {
var cumulate = 0;
var g = [];
_group.all().forEach(function(d,i) {
cumulate += d.value;
g.push({key:d.key,value:cumulate})
});
return g;
}
};
for Trailing Twelve Month calculation:
var _group = dateDim.group().reduceSum(function(d) {return d.revenue;});
var group = {
all:function () {
var g = [];
_group.all().forEach(function(d,i) {
var cumulate = 0;
var monthcount =0;
var dt =new Date( d.key);
var ct = new Date(d.key);
ct.setFullYear(ct.getUTCFullYear() -1);
_group.all().forEach(function(d2,i) {
var dt2 = new Date(d2.key);
if(dt2 <= dt && dt2 > ct){
cumulate += d2.value;
monthcount++;
}
})
if(monthcount>=11){
console.log( ' Dt ' + dt + ' ' + cumulate + ' months ' + monthcount);
g.push({key:d.key,value:cumulate})
}
});
return g;
}
};