Best way to get max Id from multiple FK - entity-framework-6.1

ALBUM have songs and each song contains History. The History is auto-encrement. Multiple songs have a history but I want just one max Id value.
I treid this
item.LastHitId = item.sound_track.Select(s => s.SoundHistory.LastOrDefault().Id).FirstOrDefault();
But just take last value from first song. Need last value from any song.

long lastHitId = item.sound_track.Select(item2 => item2.SoundHistory.Max(m => m.Id)).Concat(new long[] { 0 }).Max();

Related

PowerBI: Ranking of songs based on number of votes

I do have a table songs with several fields; among them: songs[title]), with songs titles, obviously, and songs[votes], with the number of votes every song has received.
I'd like to create a measure using RANKX() in order to add it to a new table (a PowerBI widget, I mean, not a table from my data model) with those both fields (songs[title]) and songs[votes]) so it tells me the rank position of every song based on the number of votes it has.
I have tried:
songs_ranking = RANKX(ALL(songs), MAX(songs[votes]))
However, all songs end up ranked #1, as if ALL() were not able to remove row context for each song:
Any hint? Thanks in advance.
_rank:=RANKX(ALL('fact'),CALCULATE(MAX('fact'[Vote])),,ASC,Dense)

Django query ForeignKey Count() zero

I have 3 tables:
Truck with the fields: id, name....
Menu with the fields: id, itemname, id_foodtype, id_truck...
Foodtype with the fields: id, type...
I want to get a summary like:
id name total
10 Alcoholic drink 0
5 Appetizer 11
My problem is to return the results with 0 elements.
I tried an SQL query like this:
SELECT
ft.id, ft.name, COUNT(me.id) total
FROM
foodtype ft LEFT JOIN menu me
ON ft.id = me.id_foodtype
LEFT JOIN truck tr
ON tr.id = me.id_truck AND tr.id = 3
GROUP BY ft.id, ft.name
ORDER BY ft.name
or a query in Django
Menu.objects.filter(id_truck=3).values("id_foodtype").annotate(cnt=Count("id_foodtype"))
But, neither is displaying the results with Zero elements.
At the moment to convert this query to Python code, any of my queries return the exact result that I expected.
How can I return results with the Left Join including the foodtypes with zero elements in the menu?
The direction of LEFT JOIN depends on the object, where you start the query. If it start on Menu you will never see a FoodType unused by selected Menu items. Then is important to filter (by Truck in your case) such way that also null value Menu.id is allowed in order to can get Count == 0.
from django.db.models import Q
qs = (
FoodType.objects
.filter(Q(menu_set__id_truck=3) | Q(menu_set__id__isnull=True))
.values() # not necessary, but useful if you want a dict, not a Model object
.annotate(cnt=models.Count("menu_set__id"))
)
Verify:
>>> print(str(qs.query))
SELECT foodtype.id, foodtype..., COUNT(menu.id) AS cnt
FROM foodtype
LEFT OUTER JOIN menu ON (foodtype.id = menu.id_foodtype)
WHERE _menu.id_truck = 3 OR menu.id IS NULL)
GROUP BY foodtype.id
It works with the current newest and oldest Django 2.0b1 and 1.8.
The query is the same with or without the line .values(). The results are dictionaries or FoodType objects with a cnt attribute.
Footnotes:
The name menu_set should be replaced by the real related_name of foreign key id_foodtype if you have defined the related_name.
class Menu(models.Model):
id_foodtype = models.ForeignKey('FoodType', on_delete=models.DO_NOTHING,
db_column='id_foodtype', related_name='menu_set'))
...
If you start a new project I recommend to rename the foreign key to a name without "id" and the db_column field is with "id". Then menu_item.foodtype is a Food object and menu_item.id_foodtype its id.

Django: How to get count of a specific column according to two columns

i want to get the count of the user id of this table according to the columns approval_transaction_type and approval_type.
the expected result of this would be.
Approval Transaction Type ID (60)
Approval Type ID (65) = 2 Users
Approval Type ID (64) = 2 Users
Approval Type ID (63) = 2 Users
Approval Type ID (62) = 2 Users
Approval Type ID (61) = 2 Users
My current code to achieve is this, but it overwrites the sub list and returns the incorrect result(Which i don't understand why the last array will overwrite all the array):
for transaction in transaction_types:
# Initial Array
transaction["approval_types"] = []
for approval_type in approval_types:
# Get Count of Users
approval_type["count"] = Model.objects.filter(approval_transaction_type=transaction['id'],approval_type=approval_type['id']).values().count()
# Assign this sub list to main list
transaction["approval_types"].append(approval_type)
How do i get the count without looping and use the queryset?
Let me know if something is not clear about this. Thanks!
It can be done in one query. Based on this Django equivalent for count and group by
Model.objects.values('approval_type').annotate(Count('user'))

Combine and flatten many key/value tuples into a single tuple in pig

I am using Pig 0.8.1. I am somewhat new to Pig but I know there must be a reasonable and re-usable solution for how I want to work with my tuples. I have the following format (similar to triples):
Schema: (uuid, key, val)
Data:
(id1, 'name', 'Corey')
(id1, 'location', 'USA')
(id1, 'carsOwned', 5)
(id2, 'name', 'Paul')
(id2, 'location', 'CANADA')
(id2, 'carsOwned', 10)
The reason I'm representing this data in triples is because it's possible to have multi-valued keys, so pushing the data into a map is out of the question.
What I need to be able to do is find the ids, names and locations of the people with the top 10 cars owned. I'd like it if my output format could be this when sorted in descending order:
Schema: (uuid, name, location, carsOwned)
Data:
(id2, 'Paul', 'CANADA', 10)
(id1, 'Corey', 'USA', 5)
I have tried filtering my input into 3 different aliases (one where key == 'name', one where key == 'location' and one where key == 'carsOwned') so that I can use JOIN and bring them back into one tuple, but it appears that Pig ends up loading from the inputFormat 3 times instead of one. Maybe I'm doing that wrong?
I also tried grouping by id but then I can't seem to find a reasonable way to work with the bag of the actual triple key/values since they all have the exact same schema.
What I really want is to group by the id field and then flatten each of the keys but rename the alias to the actual name of the key.
Any ideas? Thanks in advance!
This solution is a bit sloppy, because your data is not organized in a way that Pig is really set up for -- i.e., conceptually each id show be a row key, with the fields named by what you have in the second column. But this can still be done, as long as your data is all reasonable. If you erroneously wind up with multiple rows with the same id and field name, but different values, this will get complicated.
Use a nested foreach to pick out the values for the three fields you're interested in.
keyedByID =
/* Gather the rows by ID, then process each one in turn */
FOREACH (GROUP Data BY id) {
/* Pull out the fields you want. If you have duplicate rows,
you'll need to use a LIMIT statement to ensure just a single record */
name = FILTER Data BY field == 'name';
location = FILTER Data BY field == 'location';
carsOwned = FILTER Data BY field == 'carsOwned';
GENERATE
/* Output each field you want. You'll need to use FLATTEN since
the things created above in the nested foreach are bags. */
group AS id,
FLATTEN(name) AS name,
FLATTEN(locatioN) AS location,
FLATTEN(carsOwned) AS carsOwned;
};
Now you've got a relation that puts all the information for an ID on a single row, and you can do with it whatever you want. For example, you said wanted to pull out the top 10 car owners:
ordered = ORDER keyedByID BY carsOwned DESC;
top10 = LIMIT ordered 10;

Django both filtered and total number of a certain field

I have such model and query
class Employer(Models.model)
name = ...
class JobTitle(Models.model)
name = ...
employer = models.ForeignKey(Employer)
and query is
Employer.objects.select_related('jobtitle')
.filter(jtt__activatedate__range=[startdate,enddate])
.annotate(jtt_count=Count('jobtitle'))
.order_by('-jtt_count')[:5]
As you see it returns 5 employer list which has maximum number of jobtitles which are related to that employer and whose activation date is in some certain range.
However, I also want to get the total number of jobtitles of each employer in that query.
Of course I may loop over each employer and make such query JobTitle.objects.filter(employer = emp) and taking length of that query but it is bad solution.
How can I achive this in that query?
Although it may not be possible to get both total number and filtered number of job titles, I may get the jobttiles of each emplyoer such that len(emp.jobtitle) however it also didn't work.
Thanks
Try the extra lookup. So, in your case it may be like this:
.extra(
select={
'jobtitle_count': 'SELECT COUNT(*) FROM YOURAPP_jobtitle WHERE YOURAPP_jobtitle.employer_id = YOURAPP_employer.id'
},
)