I need to fetch the records based on the optional parameters.
Ex Database: MySql
Tables:
Hotel-> hotel_id, name, group_id, status, brand_id, no_rooms, region_id
Region -> region_id, region_name, region_code, region_manager
Region to Hotel having one to many relationship.
I can fetch the hotel records using this type of query
Select * from MyDB.Hotel h where h.group_id = 2 and h.brand_id = "ABC" and h.status = "Available" and h.region_id in (select region_id from MyDB.Region r where r.region_code = "13" and r.region_name = "ABC");
Similarly I created an api endpoint to get the hotel details by passing group_id, brand_id, status, region_code, region_name as required parameters and able to fetch the records.
I am using Spring CRUD repository.
#Query(value="from Hotel h where (h.group =:group) and (h.brand = :brand) and (h.status = :status) and h.region in (from Region r where (r.regionCode =:regionCode) and (r.regionName =:regionName))")
Page<Hotels> findAllHotels (#Param("group") Group group,
#Param("brand") Brand brand,
#Param("status") String status,
#Param("regionCode") EnumProductGroup regionCode,
#Param("regionName") EnumProductType regionName,
Pageable pageable);
Now I need to send the request to same endpoint as optional parameters.
If one parameter is missing still needs to fetch the records based on other parametes. Means the missing parameters should removed from the where conditon dynamically.
I tried to pass the dynamic querystring to the repository query #Query but failed. I don't know is this possible.
request->controller->service->repository extends CrudRepository.
Is there anyway to generate dynamic query based on available parameters or is there any otherway which different than what I am trying.
Related
We have three table
table 1- app ( id , name )
table 2- appPlayer ( id , name )
table 3- appPlayerSession ( id , appId , appPlayerId , version)
my Current query is:
SELECT (select name from app k where k.id= aps.appId) AS appName,version,appId,count(version) FROM appPlayerSession aps GROUP BY appId,version,appName
we need to count the session users for each game with same version, and also woth the object of all users data using single mysql query.
Current Result using my query, but we also need players for each app..
As you havent given your expected result and on basis of your requirement you can do something this.it may be enhanced as per your requirement.
SELECT (select name from app k where k.id= aps.appId) AS appName,version,appId,(select P.name from appPlayer P where P.id=aps.appPlayerid) as appPlayerName, count(version) FROM appPlayerSession aps GROUP BY appId,version,appName,appPlayerName
Also check fiddle as per your requirement created as you havent given any data set and its on my assumption.
http://sqlfiddle.com/#!9/30fe4f/1
New Sql as per your new added requirement-
select X.appname,X.version,X.appid,GROUP_CONCAT(distinct X.appPlayerName order by X.appPlayerName) as Users ,
sum(X.vercount)
from (SELECT (select name from app k where k.id= aps.appId)
AS appName,version,appId,
(select P.name from appPlayer P where P.id=aps.appPlayerid)
as appPlayerName, count(version)as vercount
FROM appPlayerSession aps
GROUP BY appId,version,appName,appPlayerName) X
group by X.appname,X.version,X.appid
New fiddle -http://sqlfiddle.com/#!9/13646c/5
You can use JOIN in sql to connect with multiple tables and fetch result
Below is the format :
SELECT t1.col,
t3.col
FROM table1
JOIN table2
ON table1.primarykey = table2.foreignkey
JOIN table3
ON table2.primarykey = table3.foreignkey
In your case :
SELECT app.col,
appPlayer.col,
appPlayerSession.col
FROM app
JOIN appPlayer
ON app.id = appPlayer.appId
JOIN appPlayerSession
ON appPlayer.id = appPlayerSession.appPlayerId
Hope this is helpful.
One suggestion . It is not a standard to use camelCase for table and column names. snake_case is preferred widely.
I have a table which contains different flight class names along with prices. Now my query result shows all of the results, flight names with corresponding classes and corresponding prices. Here is the query:
$sql = "SELECT f.dCity, f.aCity, f.date, f.flight_code, f.route, f.timeLeaving, f.timeLanding, f.price, f.class, i.airline_name ,
(SELECT location FROM iataairportcodes where iata_code='$fromm') as dLocation,
(SELECT airport_name FROM iataairportcodes where iata_code='$fromm') as dAirport,
(SELECT location FROM iataairportcodes where iata_code='$too') as aLocation,
(SELECT airport_name FROM iataairportcodes where iata_code='$too') as aAirport
FROM flights_test AS f, iataairlinescodes AS i
WHERE f.airline_code = i.iata_code
AND f.dCity = '$fromm'
AND f.aCity = '$too'
AND f.date='$newDate'";
But I want to find and display only that class, which contains minimum price; i.e., all data of that class only which contains minimum price.
(Forget about php variables please, those are from other sources)
I am trying to write a query where two different UIDs need to lookup a Resource Name for both, but separately.
In other words, for each Task, there are resources assigned and one status manager. This converts in SQl to an Assignment, unique to a resource, but with the same status manager. However, no where in the database can one see the Status Manager's Name on a given assignment.
The assignment does have "TaskStatusManagerUID" available. The name of the Status Manager can be determined by tying it back to MSP_EPMResource table where TaskStatusManagerUID = ResourceUID.
The catch is, for my report, I need to be able to look at the ResourceUID and TaskstatusManagerUID and determine the names of each on the same assignment.
While I have been successful with a join to display the name for one or the other, I have not been able to determine how to show the name for both the Resource and TaskStatusManager.
This is an example of what I am trying to display (parentheses added for readability):
(AssignmentUID) (Task Name) (Resource Name) (Task Status Manager Name)
See more info below:
This is the code I have been working with, but have been unsuccessful:
Select top 100
c.[assignmentuid],
a.[taskname],
c.[resourceuid],
b.[resourcename],
a.[taskstatusmanageruid],
d.[StatusManager]
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmAssignment] c
join [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmTask_UserView] a
on a.[TaskUID] = c.[TaskUID]
join [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b
on b.[ResourceUID] = c.[ResourceUID]
join (select b.resourcename StatusManager
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b) d
on d.[StatusManager] = a.[taskstatusmanageruid]
group by
c.[assignmentuid],
a.[taskname],
c.[resourceuid],
b.[resourcename],
a.[taskstatusmanageruid],
d.[StatusManager]
Currently, I am getting "Conversion failed when converting from a character string to uniqueidentifier."
On your joins you have on a.[TaskUID] = c.[TaskUID], on b.[ResourceUID] = c.[ResourceUID], and on d.[StatusManager] = a.[taskstatusmanageruid], of which, I am assuming that the last one is causing you the issue. Try instead
join (select b.resourcename StatusManager
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b) d
on d.[StatusManager] = CONVERT(CHAR, a.[taskstatusmanageruid])
This will convert the GUID contained in taskstatusmanageruid to a char string, allowing it to compare successfully.
You could also, instead of converting the value, cast the value CAST(a.[taskstatusmanageruid] AS CHAR
EDIT
Due to the nature of the GUID, you may not be able to convert/cast it to a char value, in which case you would need to convert/cast both fields to either varchar or nvarchar:
join (select b.resourcename StatusManager
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b) d
on CONVERT([N]VARCHAR, d.[StatusManager]) = CONVERT([N]VARCHAR, a.[taskstatusmanageruid])
OR
join (select b.resourcename StatusManager
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b) d
on CAST(d.[StatusManager] AS [N]VARCHAR) = CAST( a.[taskstatusmanageruid] AS [N]VARCHAR)
Thanks to Jeff Beese's extra set of eyes, it was enough for me to get the last piece in place!
Select top 100
c.[assignmentuid],
a.[taskname],
c.[resourceuid],
b.[resourcename],
a.[taskstatusmanageruid],
d.[StatusManager]
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmAssignment] c
join [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmTask_UserView] a
on a.[TaskUID] = c.[TaskUID]
join [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b
on b.[ResourceUID] = c.[ResourceUID]
join (select b.resourcename as StatusManager,
b.ResourceUID
from [PRJPROD_ProjectWebApp].[dbo].[MSP_EpmResource] b) d
on d.[resourceuid] = a.[taskstatusmanageruid]
group by
c.[assignmentuid],
a.[taskname],
c.[resourceuid],
b.[resourcename],
a.[taskstatusmanageruid],
d.[StatusManager]
I want to find only failed user details, but the below query is giving duplicate records. I am not able to find a proper solution.
To find failed job details I'm using the below query:
select * from executionlog e
join catalog c on e.reportid = c.itemid
where c.name like '%reportname%'
and timestart>= '2013-04-15 09:00:00.000'
and status <> 'rsSuccess'
However, the above query is giving duplicate values for a particular report.
How can I get unique details?
Note: we cannot apply distinct or group by because the table contains columns of ntext and image data types
If you want only "failed user details" then don't select the ntext or image columns at all. That way you can do a DISTINCT normally:
SELECT DISTINCT
--Parameters,
--Content,
--Property,
--Parameter,
InstanceName, ReportID, UserName, RequestType, Format, TimeStart, TimeEnd,
TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount,
[RowCount], ItemID, Path, Name, ParentID, Type, Intermediate, SnapshotDataID,
LinkSourceID, Description, Hidden, CreatedByID, CreationDate, ModifiedByID,
ModifiedDate, MimeType, SnapshotLimit, PolicyID, PolicyRoot, ExecutionFlag,
ExecutionTime
FROM executionlog e
JOIN catalog c ON e.reportid = c.itemid
WHERE c.name LIKE '%reportname%'
AND timestart>= '2013-04-15 09:00:00.000'
AND status <> 'rsSuccess'
You can even trim many more columns. Note that doing SELECT * is a bad practice for many cases anyway.
If you're interested in the corresponding ntext and/or image values you can always join the catalog against the above subquery again.
I'm stuggling to replicate a SQL query into LINQ.
Can any one help?
SQL:
SELECT tblInvoice.lngID AS InvoiceID,
tblInvoice.dtTimeStamp AS InvoiceDate,
tblInvoice.strReference,
tblInvoice.fltTotalValue,
max(Project.ProjectID) AS ProjectID,
max(Project.ProjectName) AS ProjectName,
max(Project.Location) AS ProjectLocation
FROM tblInvoice INNER JOIN
tblInvoiceLine ON tblInvoice.lngID = tblInvoiceLine.lngInvoiceID
WHERE (tblInvoice.intStatus != 0)
AND (tblInvoice.lngPersonID = #PersonID)
GROUP BY tblInvoice.lngID, tblInvoice.dtTimeStamp, strReference, fltTotalValue
ORDER BY tblInvoice.lngID DESC
LINQ so far:
var invoices = from inv in db.TblInvoices
join invLine in db.TblInvoiceLines on inv.LngID equals invLine.LngInvoiceID
where inv.IntStatus != 0
where inv.LngPersonID == personID
group inv by new {inv.LngID,inv.DtTimeStamp,inv.StrReference,inv.FltTotalValue} into newInv
Part of the problem is that I want to do a
select new Invoice(){
}
and build up my custom Invoice object but, I cant see any of the properties in newInv.
Can any one advise?
I don't have time for a full answer now, but:
To get at properties of the key, use newInv.Key.StrReference etc
To get at aggregates (e.g. max values) use newInv.Max(x => x.ProjectId) etc
Hopefully that'll be enough to get you going. Basically, newInv will be a group of entries, with an associated key (which is what you grouped by).