I can not get this query in a symfony2 project that I have.
My Table:
id course datetime numOrden
---|-----|------------|--------
1 | 1º | 04/11/2016 | 1
2 | 2º | 04/11/2016 | 2
5 | 3º | 04/11/2016 | 5
3 | 4º | 03/11/2016 | 4
4 | 5º | 03/11/2016 | 3
I need to get the course whose value in the "numOrden" column is the maximum( in this case it would be the 3rd course). For this I have used the following query in Doctrine2:
public function findCourse()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:Curso c WHERE c.numOrden in (SELECT max(c.numOrden) FROM BackendBundle:Curso )')
->getResult();
}
Or
public function findCourse()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM Bundle:Course c WHERE c.numOrden=(SELECT max(c.numOrden) FROM Bundle:Course )')
->getResult();
}
But it shows the following error:
[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got end of string. (500 Internal Server Error)
Try using another alias in the subselect as:
public function findCourse()
{
return $this->getEntityManager()->createQuery(
'SELECT c FROM Bundle:Course c WHERE c.numOrden=(SELECT max(co.numOrden) FROM Bundle:Course co )')
->getResult();
}
Hope this help
Related
I'm struggling with the following problem in KQL,
let a = 1;
let b = 2;
let c = DeviceInfo
| take 3
| count
| project-rename c=Count;
let d = DeviceInfo
| take 4
| count
| project-rename d=Count;
c | extend a,b
This produce the following result
| c | a | b |
-------------
| 3 | 1 | 2 |
By changing the last line, I'm able to get a,b,d but I'm unable to get a,b,c,d in the same table. I get the
'extend' operator: Failed to resolve scalar expression named 'd'
Any clues ? How can we use multiples let variable who come from results in a single table ?
try this simplified and clearer version, using toscalar():
let a = 1;
let b = 2;
let c = toscalar(
DeviceInfo
| take 3
| count
);
let d = toscalar(
DeviceInfo
| take 4
| count
);
print a, b, d, c
I have a table called diary which includes columns listed below:
| id | user_id | custom_foods |
|----|---------|--------------------|
| 1 | 1 | {"56": 2, "42": 0} |
| 2 | 1 | {"19861": 1} |
| 3 | 2 | {} |
| 4 | 3 | {"331": 0} |
I would like to count how many diaries having custom_foods value(s) larger than 0 each user have. I don't care about the keys, since the keys can be any number in string.
The desired output is:
| user_id | count |
|---------|---------|
| 1 | 2 |
| 2 | 0 |
| 3 | 0 |
I started with:
select *
from diary as d
join json_each_text(d.custom_foods) as e
on d.custom_foods != '{}'
where e.value > 0
I don't even know whether the syntax is correct. Now I am getting the error:
ERROR: function json_each_text(text) does not exist
LINE 3: join json_each_text(d.custom_foods) as e
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
My using version is: psql (10.5 (Ubuntu 10.5-1.pgdg14.04+1), server 9.4.19). According to PostgreSQL 9.4.19 Documentation, that function should exist. I am so confused that I don't know how to proceed now.
Threads that I referred to:
Postgres and jsonb - search value at any key
Query postgres jsonb by value regardless of keys
Your custom_foods column is defined as text, so you should cast it to json before applying json_each_text. As json_each_text by default does not consider empty jsons, you may get the count as 0 for empty jsons from a separate CTE and do a UNION ALL
WITH empty AS
( SELECT DISTINCT user_id,
0 AS COUNT
FROM diary
WHERE custom_foods = '{}' )
SELECT user_id,
count(CASE
WHEN VALUE::int > 0 THEN 1
END)
FROM diary d,
json_each_text(d.custom_foods::JSON)
GROUP BY user_id
UNION ALL
SELECT *
FROM empty
ORDER BY user_id;
Demo
TABLE : **PROFILE**
RUN_ID| Type | code | gender | vacId
1 | A | biz | M | 110
2 | A | pro | M | 113
3 | A | tot | F | 114
Required to return the vacId, based on the input if I input, if code+type combination is not present then return only vacId which equals to given type
TYPE=A AND CODE=BIZ AND GENDER=M , then it should return 110
TYPE=A AND CODE=SYS then should return 110 & 113 , 114 there is no A+SYS combination so returned superset A's data
How can I write a query for this which should work in pgsql and oracle for now.
Is there a way that I can achieve this using COALESCE
You can use conditional where clause, e.g. ($ used for parameters):
select p.*
from profile p
where case
when exists (
select 1
from profile
where type = $type and code = $code and gender = $gender
)
then type = $type and code = $code and gender = $gender
else type = $type
end;
Update.
An alternative solution could be to get results in a single json object, what will enable you to use coalesce():
select coalesce(
(select jsonb_agg(to_jsonb(p))
from profile p
where type = $type and code = $code and gender = $gender),
(select jsonb_agg(to_jsonb(p))
from profile p
where type = $type)
);
Hello everyone i want to create a procedure that receives a int and a string with the ID's when they are like this:
Int CompeteID = 1
String TeamIDs = "1,8,9"
Meaning there are 3 TeamIDs, TeamID = 1, TeamID = 8 and TeamID = 9.
Here is my DBModel: https://i.gyazo.com/7920cca8000436cfe207353aaa7d172f.png
So what i want to do is to Insert on TeamCompete, the SportID and CompeteID when there are no equal SportID and CompeteID.
Like this:
TeamCompeteID TeamID CompeteID
1 1 1
4 8 1
5 9 1
6 8 1 <---- Can't do this
But i also want to delete from TeamCompete the TeamIDs i dont pass onto the procedure for example:
TeamCompeteID TeamID CompeteID
1 1 1
2 3 1 <---- Delete this
3 4 1 <---- Delete this
But I don't want to delete the TeamCompete's that are on the Event table...
Example:
EventID TeamCompeteID
5 3 <---- Can't delete TeamCompeteID 3
-- even though i didn't past it on TeamIDs
I hope you understanded my explanation.
First and foremost, passing data in this manner is very much a bad idea. You should really try to normalise your data and have one value in each field.
If however, you cannot avoid this, I would recommend you use a string splitting function such as Jeff Moden's if you are on a SQL Server version prior to 2016 (the string_split is built into SQL Server 2016) which returns a table you can join to from a given string and delimiter.
Using Jeff's function above:
select *
from dbo.DelimitedSplit8K('1,8,9',',')
Results in:
+------------+------+
| ItemNumber | Item |
+------------+------+
| 1 | 1 |
| 2 | 8 |
| 3 | 9 |
+------------+------+
So to use with your table:
declare #t table(CompeteID int,TeamID nvarchar(10));
insert into #t values(1,'1,8,9');
select t.CompeteID
,s.Item
from #t t
cross apply dbo.DelimitedSplit8K(t.TeamID,',') s
Results in:
+-----------+------+
| CompeteID | Item |
+-----------+------+
| 1 | 1 |
| 1 | 8 |
| 1 | 9 |
+-----------+------+
You can then use this table in the rest of your update/insert/delete logic.
I got those models (simplified) :
User(id: Int, name: String)
Restaurant(id: Int, ownerId: Int, name: String)
Employee(userId: Int, restaurantId: Int)
when I use this query :
for {
r <- Restaurants
e <- Employees
if r.ownerId === userId || (e.userId === userId && e.restaurantId === r.id)
} yield r
which is converted to :
select x2."id", x2."owner_id", x2."name" from "restaurants" x2, "employees" x3 where (x2."owner_id" = 2) or ((x3."user_id" = 2) and (x3."restaurant_id" = x2."id"))
So far no problems. But when I insert those data :
User(1, "Foo")
User(2, "Fuu")
Restaurant(1, 2, "Fuu")
Restaurant(2, 1, "Foo")
Restaurant(3, 1, "Bar")
Employee(2, 2)
Employee(2, 3)
then try to query, I get this result :
List(Restaurant(1, 2, "Fuu"), Restaurant(1, 2, "Fuu"), Restaurant(2, 1, "Foo"), Restaurant(3, 1, "Bar))
I do not understand why Restaurant(1, 2, "Fuu") is present 2 times.
(I am using org.h2.Driver with url jdbc:h2:mem:play)
Am I missing something ?
Why you are getting 4 rows back
Cross joins are hard; what you are asking for with your SQL query is:
-- A Cartesian product of all of the rows in restaurants and employees
Employee.user_id | Employee.restaurant_id | Restaurant.name | Restaurant.owner_id
2 | 2 | Fuu | 2
2 | 3 | Fuu | 2
2 | 2 | Foo | 1
2 | 3 | Foo | 1
2 | 2 | Bar | 1
2 | 3 | Bar | 1
-- Filtering out those where the owner != 2
Employee.user_id | Employee.restaurant_id | Restaurant.name | Restaurant.owner_id
2 | 2 | Fuu | 2
2 | 3 | Fuu | 2
-- And combining that set with the set of those where the employee's user_id = 2
-- and the restaurant's ID is equal to the employee's restaurant ID
Employee.user_id | Employee.restaurant_id | Restaurant.name | Restaurant.owner_id
2 | 2 | Foo | 1
2 | 2 | Bar | 1
How to fix it
Make it an explicit left-join instead:
for {
(r, e) <- Restaurants leftJoin Employees on (_.id = _.restaurantId)
if r.ownerId === userId || e.userId === userId
} yield r
Alternately, use exists to make it even clearer:
for {
r <- Restaurants
if r.ownerId === userId ||
Employees.filter(e => e.userId === userId && e.restaurantId === r.id).exists
} yield r