Using FetchXML in CRM 2011 - dynamics-crm

I am using FetchXML and I am grouping and using count for two of the entities but the rest of the entities I don't need grouped I just need the data to be pulled down. For example this is my code:
string groupby1 = #"
<fetch distinct='false' mapping='logical' aggregate='true'>
<entity name='opportunity'>
<attribute name='name' alias='opportunity_count' aggregate='countcolumn' />
<attribute name='ownerid' alias='ownerid' groupby='true' />
<attribute name='createdon' alias='createdon' />
<attribute name='customerid' alias='customerid' />
</entity>
</fetch>";
EntityCollection groupby1_result = orgProxy.RetrieveMultiple(new FetchExpression(groupby1));
foreach (var c in groupby1_result.Entities)
{
Int32 count = (Int32)((AliasedValue)c["opportunity_count"]).Value;
string OwnerID = ((EntityReference)((AliasedValue)c["ownerid"]).Value).Name;
DateTime dtCreatedOn = ((DateTime)((AliasedValue)c["createdon"]).Value);
string CustomerName = ((EntityReference)((AliasedValue)c["customerid"]).Value).Name;
}
But I get this error:
EXCEPTION: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: An attribute can not be requested when an aggregate operation has been specified and its neither groupby nor aggregate. NodeXml : (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
How do you use aggregates on some values and not others?

The error message is giving you the answer - this isn't possible with FetchXML. You'll need to make two FetchXML calls; one for your aggregates and one for your data.

So, there are a few things going on here. The problem isn't so much that your query is not achievable with FetchXML as it is it's not achievable in any query language, including SQL. The SQL of your FetchXML above is as follows:
SELECT ownerID, createdon, customerid
FROM dbo.Opportunity
GROUP BY ownerID
If you try to run this SQL against your database, you'd get the standard Column 'dbo.Opportunity.CreatedOn' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. error, which is exactly what your exception is trying to tell you. To solve this, you need to also group by every non-aggregated column (in this case, createdon and customerid) by including the groupby='true' attribute in each respective attribute element.
Secondly, grouping by the create date of each opportunity is more or less a fruitless grouping, as opportunities are generally created on different datetimes, so this grouping would just return the whole table. Microsoft rightly recognizes this, so if you fix the grouping issue above, you will encounter another exception related to the datetime column. If you continue reading the article I'd previously shared, there is an example that address the different ways you can group by different date intervals (year, month, quarter, etc.) using the dategrouping attribute.
But, I get the feeling that even after fixing the general grouping issues, and then the dategrouping issue, the result set might still not be what you want. If it's not, it might help to post an example of a result set that you'd expect to see and then address whether FetchXML has the power to deliver that set to you.

Related

Rails compare same object's 1 field with another + addition of string in Active Record

I've two string fields which contains dates in string like field_1 = "2003.11.14" and I use them in ORM and they are working just fine. Now I want to compare 1 field value with another field's - 18.months. Here is a example
User.where("users.field_1 > '#{Date.today - 18.months}' AND users.field_2 > (users.fields_1 - 18.months)")
something like. Can anyone help me?
Thanks in advance
Most databases support data calculations in SQL. Something like this should work.
query = User.where("users.field_1 > ?", 18.months.ago)
query.where("users.field_2 > users.field_1 - :time", time: 18.months.ago)
edit: Just saw that the values are stored as strings, then you can not use SQL.
can not do that because the table has millions of records
I don't really understand why the size of the table limits to use the correct data type?

Tableau - Filter Measure Based on Different Variables of the Same Dimension

I have the following dimensions: Patients and Collection Type (Blood or Tissue). Measure: Collections.
I am counting how many blood and tissue collections for each patient have been made.
Here is my table: Collections per Patient by Collection Type
Now I want to filter this table: I want to display only those Patients who have more then 2 Blood Collections and more then 2 Tissue Collections.
So, I want to see only Patient B, D, and E.
How can I do this?
There are a variety of ways you could accomplish your desired result. Probably one of the easier ways would be to unpivot your data such that 'blood collections' and 'tissue collections' are separate columns instead of one. I don't believe Tableau natively supports this while importing a data source currently; however, you can created two additional calculated fields to replicate an unpivot.
Blood Field:
IF [Collection_Type] = 'Blood'
THEN [Collection]
ELSE Null
END
Tissue Field:
IF [Collection_Type] = 'Tissue'
THEN [Collection]
ELSE Null
END
EDIT: Create a Calculated field that contains your desired condition for filtering, Ex.:
(SUM([Blood_field]) > 2 AND SUM([Tissue Field]) > 2)
Calculated field will evaluate to TRUE or FLASE. Filter for records for TRUE on this field

PowerBi DAX equivalent for SUMIFS with current row value as filter

In Excel I could, if I was in a table called 'Sales' that had four columns
Sales
Month, CustomerId, ProductId, TotalQuantity
Jan,1, CAR,
Feb,1, CAR,
I could add a formula:
=SUMIFS(Sales[Quantity],Sales[CustomerId],[#[CustomerId]])
That would go to the Sales table and sum the CustomerID column filtered by the CustomerID of the current row where the formula has been entered.
I am attempted to replicate this in a PowerBI Calculated Row but I can't get the # working for a row reference. It comes across like
TotalQuantity = CALCULATE(SUM(Sales[Quantity]),Sales[CustomerId] = Sales[CustomerId]))
Any idea how to get the equivalent # working?
I think the key function you are missing is EARLIER. That is not surprising because it has a misleading name - it really means "Current Row". You also need a FILTER function in the Filter parameter of CALCULATE, to reset the filter context to the entire table.
So your New Column function might look like this:
TotalQuantity = CALCULATE(SUM(Sales[Quantity]), FILTER(Sales, Sales[CustomerId] = EARLIER (Sales[CustomerId])))
Here's a neat example, from the most accessible source site for DAX formulas:
http://www.powerpivotpro.com/2013/07/writing-a-subtotal-calc-column-aka-the-simplest-use-of-the-earlier-function/
And FWIW here is the official doco on EARLIER:
https://msdn.microsoft.com/en-us/library/ee634551.aspx

Play Framework: How to render a table structure from plain SQL table

I would be happy to get a good way to get the "table" structure from a plain SQL table.
In my specific case, I need to render JSON structure used by Google Visualization API "datatable" object:
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable
However, having an example in HTML would help either.
My "source" is a plain SQL table of "DailySales": its columns are "Day" (date), "Product" and "DailySaleTotal" (daily sale for that product). Please recall that my "model" reflects the 3-column table above.
The table columns should be "products" (suppose we have very small number of such). Each row should represent a specific date, and the row data are the actual sales for that day.
Date Product1 Product2 Product3
01/01/2012 30 50 60
01/02/2012 35 3 15
I was trying to use nested #{list} tags in a template, but unfortunately I failed to find a natural way to provide a template with a "list" to represent the "row data".
Of course, I can build a "helper object" in Java that will build a list of the "sales data" items per date - but this looks very weird to me.
I would be thankful to anyone who can provide an elegant solution.
Max
When you load your model order it by date and product name. Then in your controller build a map with date as index and list of model objects that have the same date as value of the map
Then in your template you have a first list iteration on map keys for the rows and a second list iteration on the list value for the columns.
Something like
[
#{list modelMap.keys, as: 'date'}
[${date},#{list modelMap.get(date), as: 'product'}${product.dailySaleTotal}#{ifnot product_isLast},#{/ifnot}#{/list}]#{ifnot date_isLast},#{/ifnot}
#{/list}
]
you can then adapt your json rendering to the exact structure you want to have. Here it is an array of arrays.
Instead of generating the JSON yourself, like Seb suggested, you can generate it:
private static Result queryToJsonResult(String sql) {
SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
return ok(Json.toJson(sqlQuery.findList()));
}

Is it possible to limit the amount of results returned in a response when using a QueryExpression in CRM 4

Basically I have a QueryExpression that returns over 3000 results. I only need to use between 50 and 200 of these. If I was using normal sql I could use SELECT TOP 200.....
Is there a way to do this in CRM using the QueryExpression or FetchXML?
In a QueryExpression:
QueryExpression query = new QueryExpression();
query.PageInfo = new PagingInfo();
query.PageInfo.Count = 200; // or 50, or whatever
query.PageInfo.PageNumber = 1;
In Fetch XML:
<fetch mapping='logical' page='1' count='200'>
...
#Matt basically said everything right.
This article expands on his answer.
What you essentially want to do is use PageInfo prop of QueryExpression.
That way you can limit the results, or, even better fetch more than 5000 rows (default limit). PageInfo is used as a paging indicator. How many rows does a page have, how many pages and most important, PagingCookie used for recursive read of more data (more than 5k rows)
https://msdn.microsoft.com/en-us/library/mt269606.aspx

Resources