VB LINQ: Order By doesn't work when used with Distinct - vb.net

I know this is supposed to be a solved issue but I cannot get the documented solutions to work for me. The code below is suppose to do the order by after the distinct but it does not. I referred to this post: LINQ to SQL does not generate ORDER BY when DISTINCT is used?
fyMonth = (From f In DbContext.FYMonth
Select f.Month).Distinct().OrderBy(Function(n) n).ToList()
I get an error when I try:
OrderBy(Function(n) n.SortOrder)
Any ideas?

Your query is selecting months and you're getting the distinct months. A month does not contain a SortOrder property, you no longer have access to that property on your FYMonth objects. You'll need to include the SortOrder into your projection, distinct then sort it, then project back to the month.
fyMonth = DbContext.FYMonth
.Select(Function(x) New With { x.Month, x.SortOrder })
.Distinct
.OrderBy(Function(x) x.SortOrder)
.Select(Function(x) x.Month)
This assumes that the SortOrder for each month will be the same across all months.

Related

Running Sum Query

I'm new to Access and I'm trying to develop my own Inventory Management Database.
I'm trying to make a query that could display a running total of the Inventory on Hand as of a specific date. This is how my table looks:
It's sorted according to ITEM_ID then TRANDATE in ascending order. I'd like to add a calculated field beside the NET field that would show a running total of the specific ITEM_ID after a specific date. Negative numbers in the NET field represent a sale while the positive ones represent a purchase. I tried using the DSUM function as it is widely recommended in creating a running sum field. My expression is this
DSum([NET],"InvtyTransT", "[ITEM_ID]=" & [ITEM_ID] And "[TRANDATE]<=#" & [TRANDATE] & "#"). But it only shows the total of the NET field (6827) in each record like this:
What I needed is like this:
(I used an IF function in excel to compute this)
Please help. I think I might have missed something in my expression. I've tried revising it several times and it would always give me the same wrong answer in every record.
Thanks in advance.
Try correlated sub-query.
SELECT t.*, (SELECT SUM(t2.NET)
from InvtyTransT as t2
WHERE (t2.TRANDATE <= t.TRANDATE AND t2.ITEM_ID = t.ITEM_ID)
) AS rSUM
FROM InvtyTransT AS t;

GROUP BY/SELECT DISTINCT issues

I have gone through dozens of questions on this site and others, but am still having issues adding a GROUP BY to my code. One came close, but not sure I fully understand it:
SQL/mysql - Select distinct/UNIQUE but return all columns?
I'm working on a program that tracks tracking numbers for orders shipped, but need each sales order only listed once as I need to assign a status to each order. PackageReferenceNo1 contains the sales order numbers, but I only need one tracking number for each order. The following code pulls all tracking numbers and their sales orders. My thought was if I could SELECT DISTINCT, or GROUP BY, I could resolve this issue but haven't had any luck with either option.
My working code is:
SELECT tblImportUPS.ManifestDate,
tblImportUPS.TrackingNumber,
tblImportUPS.PackageReferenceNo1,
tblImportUPS.PackageReferenceNo2,
tblImportUPS.STATUS,
tblTrackingLinks.Notes,
tblImportUPS.ShipToName,
tblTrackingLinks.PGId,
tblTrackingLinks.BBReleased,
tblTrackingLinks.BBReleaseDate,
tblTrackingLinks.SRFNumber,
tblImportUPS.ShipToCity,
tblImportUPS.[ShipToState/Province],
tblImportUPS.ShipToCountry,
tblImportUPS.ShipperName,
tblImportUPS.NumberofPieces,
tblImportUPS.Weight,
tblImportUPS.ScheduledDelivery,
tblImportUPS.DateDelivered
FROM tblTrackingLinks
INNER JOIN tblImportUPS ON (tblTrackingLinks.TrackingNumber = tblImportUPS.TrackingNumber)
AND (tblTrackingLinks.TrackingNumber = tblImportUPS.TrackingNumber)
WHERE (((tblImportUPS.PackageReferenceNo1) LIKE "*56*")
AND ((tblImportUPS.STATUS) <> "Void"))
ORDER BY tblImportUPS.ManifestDate DESC;
This works fine, but repeats multiple tracking numbers for each order. I try to add GROUP BY tblImportUPS.PackageReferenceNo1 before the ORDER BY line and receive an aggregate error.
Can anyone advise the correct way to proceed and why? I'd prefer to understand and not just receive the solution.

Getting row count with other columns

I need to get some columns which are LinkID, ReplyCount and the most important one is TotalRowCount.
This is my code:
SELECT
TOP(10) link.LinkID, mesaj.ReplyCount
FROM
TBL_UserIcerikler AS link
INNER JOIN
TBL_UserMesajlar AS mesaj ON link.FromUserID = mesaj.UserID
WHERE
link.PublishDate >='2013-03-12 19:46:45.000'
ORDER BY
link.PublishDate DESC
It is not running anymore when I add Count(*) AS a".
I get this message instead. How can I get row count? Does anyone have any information about this topic?
Msg 208, Level 16, State 1, Line 1
Invalid object name 'TBL_UserIcerikler'
Count(*) is an aggregate function which returns the number of rows which have been summarised (not the number of rows returned by the query), so you must GROUP BY something and specify only the fields by which you group (or just return COUNT(*)).
It doesn't make a lot of sense to mix COUNT() and TOP().
For example :
SELECT link.LinkID, mesaj.ReplyCount, COUNT(*)
FROM TBL_UserIcerikler AS link
INNER JOIN TBL_UserMesajlar AS mesaj ON link.FromUserID = mesaj.UserID
WHERE link.PublishDate >='2013-03-12 19:46:45.000'
GROUP BY link.LinkID, mesaj.ReplyCount;
I know it's not quite what you want, but you haven't given quite enough explanation as to what you want to get out of your database.
That said, I think you might have forgotten a comma in the expression list.
Why not post your modified query.
Please read this MSDN explanation of group by, you will understand why you need it to get your total count.

Group by SQL statement

So I got this statement, which works fine:
SELECT MAX(patient_history_date_bio) AS med_date, medication_name
FROM biological
WHERE patient_id = 12)
GROUP BY medication_name
But, I would like to have the corresponding medication_dose also. So I type this up
SELECT MAX(patient_history_date_bio) AS med_date, medication_name, medication_dose
FROM biological
WHERE (patient_id = 12)
GROUP BY medication_name
But, it gives me an error saying:
"coumn 'biological.medication_dose' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.".
So I try adding medication_dose to the GROUP BY clause, but then it gives me extra rows that I don't want.
I would like to get the latest row for each medication in my table. (The latest row is determined by the max function, getting the latest date).
How do I fix this problem?
Use:
SELECT b.medication_name,
b.patient_history_date_bio AS med_date,
b.medication_dose
FROM BIOLOGICAL b
JOIN (SELECT y.medication_name,
MAX(y.patient_history_date_bio) AS max_date
FROM BIOLOGICAL y
GROUP BY y.medication_name) x ON x.medication_name = b.medication_name
AND x.max_date = b.patient_history_date_bio
WHERE b.patient_id = ?
If you really have to, as one quick workaround, you can apply an aggregate function to your medication_dose such as MAX(medication_dose).
However note that this is normally an indication that you are either building the query incorrectly, or that you need to refactor/normalize your database schema. In your case, it looks like you are tackling the query incorrectly. The correct approach should the one suggested by OMG Poinies in another answer.
You may be interested in checking out the following interesting article which describes the reasons behind this error:
But WHY Must That Column Be Contained in an Aggregate Function or the GROUP BY clause?
You need to put max(medication_dose) in your select. Group by returns a result set that contains distinct values for fields in your group by clause, so apparently you have multiple records that have the same medication_name, but different doses, so you are getting two results.
By putting in max(medication_dose) it will return the maximum dose value for each medication_name. You can use any aggregate function on dose (max, min, avg, sum, etc.)

NHibernate How to Select distinct objects based on specific property using HQL?

How can HQL be used to select specific objects that meet a certain criteria?
We've tried the following to generate a list of top ten subscribed RSS feeds (where SubscriptionCount is a derived property):
var topTen = UoW.Session.CreateQuery( #"SELECT distinct rss
FROM RssFeedSubscription rss
group by rss.FeedUrl
order by rss.SubscriptionCount DESC
")
.SetMaxResults(10)
.List<RssFeedSubscription>();
Where the intention is only to select the two unique feed URLs in the database, rather than the ten rows int the database instantiated as objects. The result of the above is:
Column 'RssSubscriptions.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
It's possible just to thin out the results so that we take out the two unique feed URLs after we get the data back from the database, but there must be a way to do this at the DB level using HQL?
EDIT: We realise it's possible to do a Scalar query and then manually pull out values, but is there not a way of simply specifying a match criteria for objects pulled back?
If you change your HQL a bit to look like that:
var topTen = UoW.Session.CreateQuery( #"SELECT distinct rss.FeedUrl
FROM RssFeedSubscription rss
group by rss.FeedUrl
order by rss.SubscriptionCount DESC
")
.SetMaxResults(10)
.List();
the topTen variable will be an object[] with 2 elements in there being the 2 feed URLs.
You can have this returned as strongly typed collection if you use the SetResultTransformer() method of the IQuery interfase.
You need to perform a scalar query. Here is an example from the NHibernate docs:
IEnumerable results = sess.Enumerable(
"select cat.Color, min(cat.Birthdate), count(cat) from Cat cat " +
"group by cat.Color"
);
foreach ( object[] row in results )
{
Color type = (Color) row[0];
DateTime oldest = (DateTime) row[1];
int count = (int) row[2];
.....
}
It's the group by rss.FeedUrl that's causing you the problem. It doesn't look like you need it since you're selecting the entities themselves. Remove that and I think you'll be good.
EDIT - My apologies I didn't notice the part about the "derived property". By that I assume you mean it's not a Hibernate-mapped property and, thus doesn't actually have a column in the table? That would explain the second error message you received in your query. You may need to remove the "order by" clause as well and do your sorting in Java if that's the case.