I need find out the number of times a persons name string appears in a DataTable.. Im trying to find out who has resolved the most tickets in 24 hours. I've been able to accomplish this using SQL below but I um un familiar with how to do to this using LINQ. The three columns from the SELECT statement are all varchar(MAX types)
SQL CODE
SELECT Assigned_Individual,Data_Output_Type,assigned_group, count(Assigned_Individual)
FROM [DATABASE].[DBO].[TABLENAME]
GROUP BY Assigned_Individual, Data_Output_Type, assigned_group
ORDER BY count(1) desc
This will produce a result that will have an additional column telling me how many times the persons name "Assigned_Individual" has occurred in this table
It's a bit tricky in LINQ, but you can do it using the below code. I hope you like the sql style syntax:
var query = from table in tablename
group by new { table.Assigned_Individual, table.Data_Output_Type, table.assigned_group }
into grp
select new
{
grp.Key.AssignedIndividual,
grp.Key.Data_Output_Type,
grp.Key.assigned_group,
Count = grp.Count()
};
Related
I'm programming a C# Windows Forms Application in Visual Studio and I'm trying to get data about prices of products and the amount a user has added a product to its shopping list from my local MySQL-database into a List(int).
What I do is following:
If a user has added a product 4 times to their shopping list, I'm adding the barcode of the product 4 times to my List(int).
This is working but when I'm reading out all items of the List with the String.Join()-method into the IN-clause of my query and execute it, it only returns a row one time altough the IN-operator has the same barcode multiple times.
The following is how I'm adding barcodes to my List(int)
int count = 0;
List<int> barcodes = new List<int>();
MySqlCommand cmd = new MySqlCommand("SELECT product_barcode, amount FROM shopping_list_items WHERE shopping_list_id = " + current_shoppingListID + ";", db.connection);
cmd.ExecuteNonQuery();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
do
{
barcodes.Add(Int32.Parse(reader["product_barcode"].ToString()));
count++;
} while (count < Int32.Parse(reader["amount"].ToString()));
}
reader.Close();
This is how I'm executing my query and assign the values to variables:
MySqlCommand cmdSum = new MySqlCommand("SELECT sum(price) AS 'total', supermarket_id FROM prices WHERE barcode IN (" + String.Join(", ", barcodes) + ") GROUP BY supermarket_id;", db.connection);
cmdSum.ExecuteNonQuery();
var readerSum = cmdSum.ExecuteReader();
while (readerSum.Read())
{
switch (double.Parse(readerSum["supermarket_id"].ToString()))
{
case 1:
sumSupermarket1 = double.Parse(readerSum["total"].ToString());
break;
case 2:
sumSupermarket2 = double.Parse(readerSum["total"].ToString());
break;
case 3:
sumSupermarket3 = double.Parse(readerSum["total"].ToString());
break;
}
}
A simplified query just to make it simple may look like this:
SELECT name FROM products WHERE barcode IN (13495, 13495, 13495);
If the above one is my query then I want it to return 3 the same rows.
So my question now is, how can I get multiple rows altough I use a same value multiple times in the IN-clause of a MySQL-query?
Q: how can I get multiple rows altough I use a same value multiple times in the IN-clause of a MySQL-query?
A: We don't. That's not how IN () works.
Note that
WHERE foo IN ('fee','fi','fi','fi')`
Is shorthand for
WHERE ( foo = 'fee'
OR foo = 'fi'
OR foo = 'fi'
OR foo = 'fi'
)
Understand what's happening here. MySQL is going to examine each row, and for each row it checks to see if this condition returns TRUE or not. If the row satisfies the condition, the row gets returned. Otherwise the row is not returned.
It doesn't matter that a row with foo value of 'fi' satisfies multiple conditions. All MySQL cares about is that the condition inside the parens ultimately evaluates to TRUE.
As an illustration, consider:
WHERE ( t.picked_by = 'peter piper'
OR t.picked_amount = 'peck'
OR t.name LIKE '%pickled%'
OR t.name LIKE '%pepper%'
)
There could be a row that satisfies every one of these conditions. But the WHERE clause is only asking if the entire condition evaluates to TRUE. If it does, return the row. If it doesn't, then exclude the row. We don't get four copies of a row because more than one of the conditions is satisfied.
So how do we get a set with multiple copies of a row?
As one possible option, we could use separate SELECT statements and combine the results with UNION ALL set operator. Something like this:
SELECT p1.name FROM product p1 WHERE p1.barcode IN (13495)
UNION ALL
SELECT p2.name FROM product p2 WHERE p2.barcode IN (13495)
UNION ALL
SELECT p3.name FROM product p3 WHERE p3.barcode IN (13495)
Note that the result from this query is significantly different than the result from the original query.
There are other query patterns that can return an equivalent set.
FOLLOWUP
Without an understanding of the use case, the specification, I'm just guessing at what we are attempting to achieve. Based on the two queries shown in the code (which follows a common pattern we see in code that is vulnerable to SQL Injection),
The shopping list:
SELECT i.product_barcode
, i.amount
FROM shopping_list_item i
WHERE i.shopping_list_id = :id
What is amount? Is that the quantity ordered? We want two cans of this, or three pounds of that? Seems like we would want to multiply the unit price by the quantity ordered to get the cost. (Two cans is going to cost twice as much as one can.)
If what we are after is the total cost of the items on the shopping list from multiple stores, we could do something like this:
SELECT SUM(p.price * s.amount) AS `total`
, p.supermarket_id
FROM ( SELECT i.product_barcode
, i.amount
FROM shopping_list_item i
WHERE i.shopping_list_id = :id
) s
JOIN price p
ON p.barcode = s.product_barcode
GROUP
BY p.supermarket_id
Note that if a particular product_barcode is not available for particular supermarket_id, that item on the list will be excluded from the total, i.e. we could get a lower total for a supermarket that doesn't have everything on our list.
For performance, we can eliminate the inline view, and write the query like this:
SELECT SUM(p.price * i.amount) AS `total`
, p.supermarket_id
FROM shopping_list_item i
JOIN price p
ON p.barcode = i.product_barcode
WHERE i.shopping_list_id = :id
GROUP
BY p.supermarket_id
If we absolutely have to rip through the shopping list query, and then use the rows from that to create a second query, we could form a query that looks something like this:
SELECT SUM(p.price * i.amount) AS `total`
, p.supermarket_id
FROM ( -- shopping_list here
SELECT '13495' AS product_barcode, '1'+0 AS amount
UNION ALL SELECT '13495', '1'+0
UNION ALL SELECT '13495', '1'+0
UNION ALL SELECT '12222', '2'+0
UNION ALL SELECT '15555', '5'+0
-- end shopping_list
) i
JOIN price p
ON p.barcode = i.product_barcode
WHERE i.shopping_list_id = :id
GROUP
BY p.supermarket_id
You would probably be better off investigating LINQ to SQL rather than using direct SQL and injection.
You can use an inline table join to accomplish what you want:
"SELECT sum(price) AS 'total', supermarket_id
FROM (select "+barcodes[0]+"as bc union all select "+String.Join(" union all select ", barcodes.Skip(1).ToArray())+") w
JOIN prices p ON p.barcode = w.bc
GROUP BY supermarket_id;"
Note: If you can name the column with the inline table alias (I couldn't test that) you could simplify the inline table generation.
I need to get the distinct row values from a table using LINQ. The query i used is
var results = (from statename in dsobject.dbo_statetable select statename).Distinct();
It is giving all the rows of the table named "dbo_statetable" but i need only the distinct statename. What should be the query to achieve this?
Its sql equivalent is select distinct statename from dbo_statetable
You need to specify the property:
var results = (from x in dsobject.dbo_statetable select x.Statename).Distinct();
// ^^^^^^^^^^
The variable after from does not specify the column. It is like a table alias in SQL. Your LINQ statement is roughly equivalent to this SQL:
SELECT DISTINCT * FROM dbo_statetable AS statename
dsobject.dbo_statetable.Select(s => s.statename).Distinct()
I have the following query in SQL which I would like to convert to LINQ:
select profile_id from t
where child_id in (1, 2 ,3, ...) //this will be a list of integers CHILDREN
group by profile_id
having count(distinct child_id) = 3
I am having a difficulty how to write the last line in my sql query into linq. The following is my work so far:
public IQueryable<ProfileChildRelationship> GetPCRelByCids(List<int> children)
{
var query = from pcr in this._entities.ProfileChildRelationships
where children.Contains(pcr.pcChildIDF)
group pcr by pcr.pcProfileIDF into g
??? having ...?
select pcr;
return query;
}
I think that may main problem is that many convert a having sql statement into a where linq statement, but in my case i do not think it is possible to write another where after the group by linq statement!
Update:
The situation: I have a number of children, each of which has many different profiles, (some may be the same). A user will select a number of children, from which I would like to derive their common profiles. That is, if profile X is found for EVERY child, than I will get it, if profile Y is found for every child except one, than it would be invalid!
Sounds like you want a where clause here...
var query = from pcr in this._entities.ProfileChildRelationships
where children.Contains(pcr.pcChildIDF)
group pcr by pcr.pcProfileIDF into g
where g.Select(x => x.ChildId).Distinct().Count() == 3
select g.Key; // This is the profile ID
"select count(salary) from employee where employeeID = 10 group by salary" --- Its a SQL Query.
I need Linq Query which would retrieve me same output..?
Please Help me out i am new to Linq
You should also check :
Full aricle : SQL to LINQ ( Visual Representation )
from e in employee
where e.employeeid=10
group e by e.Salary
into grp
select new
{
Salary = grp.Key,
Count = grp.Count()
};
Your query puzzles me from the functional perspective: You want to count the number of different salaries for one employee?
Anyway, i think something like this would do also work (untested)
db.Employees.Where(e=>e.id == 10).Select(s=>s.salary).Distinct().Count()
I have a database table that holds information for received files. One of the columns is a DateTime that specifies when the file was received. I need to get a distinct list of months with the year (MM/YYYY) for files received. I need to get it out of this table. There can be thousands of records in this table so the way I have done it, in Oracle, is in my select statement I format the datetime as MM/YYYY and do a sort desc with a distinct clause on it. This give me a list of just the months that a file was received. Very fast and efficient.
Now I need to do this using EFv4....here's the query I used in Oracle. Anyone know how I can translate it using one of EFs ways of querying?
select distinct
to_char( i.date_received, 'MMYYYY')) MonthAndYear
from table1
order by MonthAndYear desc
Well, don't do it like Oracle. Do it like LINQ.
var q = (from i in Context.Table1
select new
{
Month = i.date_received.Month,
Year = i.date_received.Year
}).Distinct();
To get a DateTime out:
var r = q.AsEnumerable().Select(d => new DateTime(d.Year, d.Month, 1));