MAX FROM COUNT in HQL - count

I have Doctor and Patient classes, where every doctor has some patients (1:m).
How do I find the doctor (or doctors) with the most patients in HQL?
Here the SQL query:
SELECT D.doctorName, count(D.patientId) AS tot
FROM Doctors AS D GROUP BY D.doctorName HAVING count(D.patientId)=
(SELECT max(A.pid) FROM( SELECT count(D.patientId) AS pid FROM Doctors AS D
GROUP BY D.doctorName) AS A)
The main issue is that I cannot write a sub-query in FROM place.
Many thanks.
R

Solved! I've created a CRITERIA function to replace the subquery. Not elegant but works!
def myList = []
String tempName = ""
int patPosition = 0
int myListPosition = -1
int find = 0
int maxOcc = 0
def c = Doctor.createCriteria()
def pat = c.list {
patients {
}
}
while(patPosition<pat.size()){
find=0
tempName=pat[patPosition].lastName //Some constraints to add
find=pat.lastName.count(tempName)
if(find>maxOcc){
maxOcc=find
}
myListPosition=myListPosition+1
myList[myListPosition]=find
patPosition=patPosition+find
}
print "\n\nLIST -> "+myList
print "MAX -> "+maxOcc
String queryToDo= "SELECT d.name, count(p) "+
"FROM Doctor as d INNER JOIN d.patients as p "+
"GROUP BY d.name "+
"HAVING count(p) = $maxOcc"
def query = Doctor.executeQuery(queryToDo)
render query

More synthetic:
pat.eachWithIndex{item, index->
if (index.equals(index2)){
patCount=0
patCount=pat.count(item)
index2=index2+patCount
if(patCount>maxOcc){
maxOcc=patCount
}
}
}

Related

CosmosDb search datetime with millisecond precision not working when ms is .0000000Z

Have the following test data in CosmosDB.
{
"LastSuccessfulDeployment": "2022-10-08T01:30:30.0000000Z",
},
{
"LastSuccessfulDeployment": "2022-10-08T01:30:30.3816486Z",
}
Searching '2022-10-08T01:30:30.0000000Z' returns no records whereas when searching for '2022-10-08T01:30:30.3816486Z' records are being returned.
protected override IQueryable<Component> ApplyFiltersOnQueryInternal(IQueryable<Component> query, IFilter<Component> filter)
{
if (filter == null)
return query;
var componentFilter = (filter as ComponentFilter)!;
if (componentFilter.LastSuccessfulDeployment.HasValue)
query = query.Where(x => x.LastSuccessfulDeployment == componentFilter.LastSuccessfulDeployment);
return query
.Skip((componentFilter.CurrentPage - 1) * componentFilter.PageSize)
.Take(componentFilter.PageSize);
}
EntityQueryable DebugView:
-- #__componentFilter_LastSuccessfulDeployment_0='08/10/2022 01:30:30'
SELECT c
FROM root c
WHERE ((c["Discriminator"] = "Component") AND (c["LastSuccessfulDeployment"] = #__componentFilter_LastSuccessfulDeployment_0))
-- #__componentFilter_LastSuccessfulDeployment_0='12/10/2022 15:18:14'
SELECT c
FROM root c
WHERE ((c["Discriminator"] = "Component") AND (c["LastSuccessfulDeployment"] = #__componentFilter_LastSuccessfulDeployment_0))
```Code

Get Category Based On Amount Value from Date In sql

I have a very simple table
ID| Category| Amount
------------------------
1 | Size 1 | 50000.00
2 | Size 2 | 100000.00
3 | Size 3 | 500000.00
I want to return category "Size 1" when the amount passed is less than or equal to 50000.00
"Size 2" when the amount passed is less than or equal to 100000.00 but greater than "Size 1"
"Size 3" when the amount passed is less than or equal to 500000.00 but greater than "Size 2"
One obvious way to do this is to simply use if conditions but this is just an example , there can be any number of categories. So I cant just hardcode it.
See the code below
public class TesteStackOverflow
{
public TesteStackOverflow(decimal amout)
{
List<testTable> list = new List<testTable>();
list.Add(new testTable { Id = 1, Category = "Size 1", Amount = 50000 });
list.Add(new testTable { Id = 2, Category = "Size 2", Amount = 100000 });
list.Add(new testTable { Id = 3, Category = "Size 3", Amount = 500000 });
var r = (from n in list where amout <= n.Amount select n).First();
if(r != null)
System.Diagnostics.Debug.Print(r.Category);
else
System.Diagnostics.Debug.Print("Category not found");
}
}
public class testTable
{
public int Id { get; set; }
public string Category { get; set; }
public decimal Amount { get; set; }
}
One simple way...
SELECT CATEGORY
FROM YourTable
WHERE AMOUNT = (SELECT MAX(AMOUNT)
FROM YourTable
WHERE AMOUNT <= YourValue)
You could put the limits In a table and then join with it.
How about something like
SELECT TOP 1 *
FROM #Table
WHERe Amount >= #Val
ORDER BY Amount
SQL Fiddle DEMO
if not exists(
SELECT TOP 1 *
FROM tbl_TicketSizeMst
WHERe Amount >= #amt
ORDER BY Amount
)
begin
select top 1 * FROM tbl_TicketSizeMst
end
else
begin
SELECT TOP 1 *
FROM tbl_TicketSizeMst1
WHERe Amount >= #amt
ORDER BY Amount
end
Create a view with the following definition:
; WITH x AS (
SELECT id
, category
, amount
, Row_Number() OVER (ORDER BY amount) As sequence
FROM your_table
)
SELECT x.id
, x.category
, Coalesce(prev.amount, 0) As lower_amount
, x.amount As upper_amount
FROM x
LEFT
JOIN x As prev
ON prev.sequence + 1 = x.sequence
This view will return a resultset like so:
id category lower_amount upper_amount
-- -------- ------------ ------------
1 Size 1 0.00 50000.00
2 Size 2 50000.00 100000.00
3 Size 3 100000.00 500000.00
Then you can query this view like so:
SELECT category
FROM that_view
WHERE #your_value > lower_amount
AND #your_value <= upper_amount
tell me for which sample data it do not work (where it fail)
Declare #t table(ID int, Category varchar(50), Amount float)
insert into #t
select 1 , 'Size 1', 50000.00 union all
select 2 , 'Size 2' , 100000.00 union all
select 3 , 'Size 3' , 500000.00
Declare #input float=50000
select id,category ,amount from #t a
where a.Amount-#input=(select min(a.Amount-#input) from #t a where a.Amount-#input>=0 )

Entity Framework query joins and group by issue

Please correct the query
IN PL/SQL
SELECT a.MENU_ID, a.menu_label, a.menu_value
FROM tbl_ims_menu a, TBL_IMS_ROLE_ASSIGNED_MENU b,TBL_IMS_USER_ROLE_PRIVILEGES c
WHERE a.menu_id = b.menu_id AND b.urole_id = c.granted_role
AND c.user_id = '3' AND a.menu_master <> '0'
AND a.menu_status = 'Active'
GROUP BY a.menu_id, a.menu_label, a.menu_value
query is working fine there is some issue when rewrite in Entity framework
check the following query
List<TBL_IMS_MENU> listSubMenu = (from m in db.TBL_IMS_MENU
join ra in db.TBL_IMS_ROLE_ASSIGNED_MENU on m.MENU_ID
equals ra.MENU_ID
join rp in db.TBL_IMS_USER_ROLE_PRIVILEGES on ra.UROLE_ID
equals rp.GRANTED_ROLE
where rp.USER_ID == UserID
group m by m.MENU_ID
into g select g).ToList();
if I used Var instead of List then how to fire loop?
I think you need to remove your join statements - and just use the where like you do in raw SQL query:
var qry = (from a in db.TBL_IMS_MENU
from b in db.TBL_IMS_ROLE_ASSIGNED_MENU
from c in db.TBL_IMS_USER_ROLE_PRIVILEGES
where c.USER_ID == UserID
where b.UROLE_ID == c.GRANTED_ROLE
where a.MENU_ID == b.MENU_ID
where a.menu_status == "Active"
where a.menu_master != "0"
select a)
.GroupBy(c => c.menu_id)
.ThenBy(c => c.menu_label)
.ThenBy(c => c.menu_value)
.ToList();
Try something like this:
var listSubMenu = (from m in db.TBL_IMS_MENU
join ra in db.TBL_IMS_ROLE_ASSIGNED_MENU on m.MENU_ID
equals ra.MENU_ID
join rp in db.TBL_IMS_USER_ROLE_PRIVILEGES on ra.UROLE_ID
equals rp.GRANTED_ROLE
where rp.USER_ID == UserID
group m by new { m.MENU_ID, m.menu_label, m.menu_value }
into g select g).ToList();
foreach(var groupItem in listSubMenu)
{
// go through groups like this - groupItem.Key.MENU_ID
foreach(var menuItem in grouItem)
{
//go through each item in group like this - menuItem.GRANTED_ROLE
}
}

Count resulted records using linq to sql

i use linq to sql query for retrive records from database.
i use a query,for binding a gridview.
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
where y.ClientID==x.EventID
select x.EventID).Count();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events = z,
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
EventID = b.EventID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
catch
{
throw;
}
}
and i recieve this output for that,
i recieve this output for this query but i don't want this output ,
i want like this output.
clientname events
ketan 18
monika 12
and others records so on means i recieve here client name 9 times and he created events but i want some of events and client name only one time
means i want only one name of client and total number of events,i am new to linq to sql.
so what is the changes in code..?
when you are using join syntax in query you do not need to use 'where'
then change your query to :
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
select x.EventID).Count();
i found solution .here
ans also use with this.useful link
here is my solution.
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID into z
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events =z.Where(b =>b.ClientID==a.ClientID).Count(),
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();

How To KnowTable Count in Sqlite Black Berry

Can any one tell me how to count table records in black berry sqlite.
Thank You
Actually Count(0) also doing a trick, and to get a result, it's the first and only row in cursor, first field, type int:
public static int selectRecordsCount(String dbUrl, String tableName)
throws DatabaseException, DataTypeException,
IllegalArgumentException, MalformedURIException {
int result = -1;
URI myURI = URI.create(dbUrl);
Database d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT COUNT(0) FROM "
+ String.valueOf(tableName));
st.prepare();
Cursor c = st.getCursor();
c.next();
result = c.getRow().getInteger(0);
st.close();
d.close();
return result;
}

Resources