Hi James, I think your SQL
SELECT DISTINCT ContactName, ContactEmail,
(SELECT COUNT(*)
FROM TicketDeliveryNote
WHERE ContactName = CDN.ContactName AND ContactEmail = CDN.ContactEmail) AS Occurances
FROM TicketDeliveryNote CDN
WHERE (ContactName LIKE '%patel%')
ORDER BY Occurances DESC
could be rewritten as follows
SELECT DISTINCT ContactName, ContactEmail, COUNT(*) Occurances
FROM TicketDeliveryNote
WHERE (ContactName LIKE '%patel%')
GROUP BY ContactName, ContactEmail
ORDER BY Occurances DESC
So, you dont need the subquery here.
Well, now the Aggregate Sort stuff:
Here is a example in Northwind (sorry, is in C#
):
Statement: I want the Number of ORDERS shipped in Brazil with the Customer-Employee combination, ordering by the NumberOfOrders Descending.
// define fields
ResultsetFields fields = new ResultsetFields(3);
fields.DefineField(OrdersFields.CustomerId, 0, "CustomerID");
fields.DefineField(OrdersFields.EmployeeId, 1, "EmployeeID");
fields.DefineField(OrdersFields.OrderId, 2, "NumberOfOrders", AggregateFunction.Count);
// grouping (CustomerID and EmployeeID)
GroupByCollection groupBy = new GroupByCollection();
groupBy.Add(fields[0]);
groupBy.Add(fields[1]);
// filter (only orders shipped in Brazil)
IRelationPredicateBucket filter = new RelationPredicateBucket();
filter.PredicateExpression.Add(OrdersFields.ShipCountry == "Brazil");
// sorting on NumerOfOrders(here is the really good stuff)
SortExpression sortBy = new SortExpression();
sortBy.Add(new SortClause(fields[2], null, SortOperator.Descending));
// retrieve
DataTable results = new DataTable();
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchTypedList(fields, results, filter, 0, sortBy, false, groupBy);
}
The above produce this SQL:
SELECT DISTINCT [Northwind].[dbo].[Orders].[CustomerID], [Northwind].[dbo].[Orders].[EmployeeID], COUNT([Northwind].[dbo].[Orders].[OrderID]) AS [NumberOfOrders]
FROM [Northwind].[dbo].[Orders]
WHERE ( ( [Northwind].[dbo].[Orders].[ShipCountry] = 'Brazil'))
GROUP BY [Northwind].[dbo].[Orders].[CustomerID], [Northwind].[dbo].[Orders].[EmployeeID]
ORDER BY NumberOfOrders DESC
Enjoy