error incorporating a select within a IFNULL in MariaDB - sql

I'm creating a view in MariaDB and i'm having trouble making it work for a couple of fields. Currently this is working:
( SELECT DISTINCT IFNULL(grades.`grade`,'No Grade')
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
But i need to add a select where the 'No grade' is, in the following form
( SELECT DISTINCT IFNULL( grades.`grade`,
SELECT IF( EXISTS
( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id`
AND grades.`Item Name` = 'SOMEINFO'
) 'SOMENAME',
i know that
SELECT IF( EXISTS( SELECT *
FROM `another_table`
WHERE userid = 365
AND courseid = 2
),
'Enrolled', 'Not enrolled'
)
is working too, but now the whole thing it's giving me an error, so any suggestions would be greatly appreciated
Thanks

This looks like a subquery:
(SELECT DISTINCT IFNULL(grades.`grade`,
SELECT IF( EXISTS (SELECT *
FROM `another_table`
WHERE userid = 365 AND courseid = 2
), 'Enrolled', 'Not enrolled'
)
)
FROM `table` grades
WHERE userinfo.`id` = grades.`id` AND
grades.`Item Name` = 'SOMEINFO'
) as SOMENAME,
You are using a subquery that returns two columns in a position where a scalar subquery is expected. A scalar subquery returns one column in at most one row.
Unfortunately, there is no easy way to do what you want in MySQL, because of the restrictions on views. I would advise you to rewrite the logic so the exists is handled using a left join in the from clause.

Related

ORACLE SQL Pivot Issue

I am trying to pivot a sql result. I need to do this all in the one query. The below is telling me invalid identifier for header_id. I am using an Oracle database.
Code
Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr
from item_history ih, item ci, contract ppd,
header ch, group g, cd_std_type ct, cd_hos h,
cd_std_hospital_cat ht
where ih.item_id = ci.item_id
and ih.header_id = ch.header_id
and ci.hos_id = h.hos_id
and ih.item_id = ci.item_id
and ch.user_no = ppd.user_no
and ppd.group_id = g.group_id
and ch.header_type = ct.header_type_id
and ci.hos_id = h.hos_id
and h.cat_id = ht.cat_id
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)
Your inner query doesn't have header_id in its projection, so the pivot clause doesn't have that column available to use. You need to add it, either as:
Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr,ih.header_id
---------------------------------------------------------------^^^^^^^^^^^^^
from ...
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)
or:
Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr,ch.header_id
---------------------------------------------------------------^^^^^^^^^^^^^
from ...
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)
It doesn't really matter which, since those two values must be equal as they are part of a join condition.
You could achieve the same thing with simpler aggregation instead of a pivot, but presumably you are doing more work in the pivot really.

SQL need to add outerjoin to the query below

In the below SQL:
I need to add two columns in the result
1) Local_code
2)Local_CPTY_SYS_ID,
which are in HSBC_LOCAL_INVOL_PARTY table.
So far I have tried to add
select local_code from HSBC_LOCAL_INVOL_PARTY
h join t_cdr T2
on T2.counterparty_new = h.entity_code
but that doesn't work. It needs an explicit outer join in the end. Please help
SELECT
T2.counterparty_new,
T2.bis_entity_type_original,
T2.counterparty_new_desc,
T2.counterparty_new_attribute_6,
T2.method_original,
T2.netting_agreement_reference,
T2.internal_rating_new,
T2.counterparty_type_original,
T2.obligor_grade_new,
T2.pd_pre_floor_new,
T2.pd_new,
T2.lgd,
T2.rwa
from t_cdr T2,
(
SELECT * FROM (
SELECT
FINAL.FILTER_MARKER,
FINAL.entity_code
FROM (
SELECT
FILTER_POP.entity_code,
FILTER_POP.FILTER_MARKER
FROM (
SELECT
CASE
WHEN CONCAT(Dlgd,unfloored_lgd) IS NOT NULL
THEN 'EXCLUDE'
WHEN CONCAT(Dlgd,unfloored_lgd) IS NULL
THEN 'INCLUDE'
END AS FILTER_MARKER,
entity_code,
Dlgd,
unfloored_lgd
FROM
HSBC_LOCAL_INVOL_PARTY
WHERE
((HSBC_LOCAL_INVOL_PARTY.entity_code) NOT LIKE '%DUM%')
AND
((HSBC_LOCAL_INVOL_PARTY.entity_code) NOT LIKE '%HSBC%')
) FILTER_POP
GROUP BY
FILTER_POP.entity_code,
FILTER_POP.FILTER_MARKER) FINAL
GROUP BY
FINAL.FILTER_MARKER,
FINAL.entity_code
ORDER BY
FINAL.entity_code)
PIVOT
(
COUNT(FILTER_MARKER)
FOR FILTER_MARKER IN ('INCLUDE' AS INCLUDE,'EXCLUDE' AS EXCLUDE)
)
WHERE INCLUDE = 1 AND EXCLUDE = 0
) ENTITY_FILTER
WHERE ENTITY_FILTER.entity_code = T2.counterparty_new
AND T2.method_original = 'ADV'
ORDER BY T2.rwa DESC
Solved it: Look at the last few lines. Took a while but optimized it as well for performance.
SELECT
T2.counterparty_new,
T2.bis_entity_type_original,
T2.counterparty_new_desc,
T2.counterparty_new_attribute_6,
T2.method_original,
T2.netting_agreement_reference,
T2.internal_rating_new,
T2.counterparty_type_original,
T2.obligor_grade_new,
T2.pd_pre_floor_new,
T2.pd_new,
T2.lgd,
HSBC_LOCAL_INVOL_PARTY.local_code,
T2.rwa
from t_cdr T2,
(
SELECT * FROM (
SELECT
FINAL.FILTER_MARKER,
FINAL.entity_code
FROM (
SELECT
FILTER_POP.entity_code,
FILTER_POP.FILTER_MARKER
FROM (
SELECT
CASE
WHEN CONCAT(Dlgd,unfloored_lgd) IS NOT NULL
THEN 'EXCLUDE'
WHEN CONCAT(Dlgd,unfloored_lgd) IS NULL
THEN 'INCLUDE'
END AS FILTER_MARKER,
entity_code,
Dlgd,
unfloored_lgd
FROM
HSBC_LOCAL_INVOL_PARTY
WHERE
((HSBC_LOCAL_INVOL_PARTY.entity_code) NOT LIKE '%DUM%')
AND
((HSBC_LOCAL_INVOL_PARTY.entity_code) NOT LIKE '%HSBC%')
) FILTER_POP
GROUP BY
FILTER_POP.entity_code,
FILTER_POP.FILTER_MARKER) FINAL
GROUP BY
FINAL.FILTER_MARKER,
FINAL.entity_code
ORDER BY
FINAL.entity_code)
PIVOT
(
COUNT(FILTER_MARKER)
FOR FILTER_MARKER IN ('INCLUDE' AS INCLUDE,'EXCLUDE' AS EXCLUDE)
)
WHERE INCLUDE = 1 AND EXCLUDE = 0
) ENTITY_FILTER,HSBC_LOCAL_INVOL_PARTY
WHERE ENTITY_FILTER.entity_code = T2.counterparty_new
AND ENTITY_FILTER.entity_code = HSBC_LOCAL_INVOL_PARTY.entity_code(+)
AND T2.method_original = 'ADV'
ORDER BY T2.rwa DESC

simple subquery not working DB2

hey guys this is a very simple sql query that is not giving me the correct result.
subquery:
SELECT NEODB2ADMIN.ORDERS.MEMBER_ID
FROM NEODB2ADMIN.ORDERS
WHERE NEODB2ADMIN.ORDERS.ORDERS_ID = 6371043
this subquery successfully returns a correct value 627809
simple query:
SELECT *
FROM NEODB2ADMIN.ADDRESS
WHERE MEMBER_ID IN (627809)
this query executes properly and returns 4 rows.(4 addresses for a member)
but if I try to combine these queries in 1 query as follows:
SELECT *
FROM NEODB2ADMIN.ADDRESS
WHERE MEMBER_ID IN (
SELECT NEODB2ADMIN.ORDERS.MEMBER_ID
FROM NEODB2ADMIN.ORDERS
WHERE NEODB2ADMIN.ORDERS.ORDERS_ID = 6371043
)
then the query returns 0 rows. why is this happening?
Thanks
Your query looks OK, the only I can think is maybe you mistake the value on the result.
can you try this:
SELECT *
FROM NEODB2ADMIN.ADDRESS
WHERE MEMBER_ID IN (
SELECT 627809
FROM NEODB2ADMIN.ORDERS
WHERE NEODB2ADMIN.ORDERS.ORDERS_ID = 6371043
)
and this
SELECT *
FROM NEODB2ADMIN.ADDRESS
WHERE MEMBER_ID IN (
SELECT 627809
FROM NEODB2ADMIN.ORDERS
)
Since your Order (presumably) can only carry a single Member_ID -- can you please try your full query without the "IN", rather try an equal join as follows:
SELECT *
FROM NEODB2ADMIN.ADDRESS
WHERE MEMBER_ID = (
SELECT NEODB2ADMIN.ORDERS.MEMBER_ID
FROM NEODB2ADMIN.ORDERS
WHERE NEODB2ADMIN.ORDERS.ORDERS_ID = 6371043
)

Have a subquery return a row instead of a column

I have this query:
SELECT
[Address]=e.Address,
[LastEmail] =
(
SELECT TOP 1 [Email]
FROM Email innerE
WHERE e.UserID = innerE.UserID
AND innerE.Contact = #emailId
AND (IsSent is null OR isSent = 0)
ORDER BY Timestamp DESC
)
FROM Emails e
This works fine, but now, I realized i'd like to get the entire row containing that lastemail column, if this is possible, any ideas on how it could be done?
You can do this:
;WITH LastEmails
AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY Timestamp DESC) rownum
FROM Emails
WHERE Contact = #emailId
AND (IsSent is null OR isSent = 0)
)
SELECT * FROM LastEmails
WHERE rownum = 1;
If your DBMS supports it you can use APPLY (which I think it does as it looks like SQL-Server Syntax)
SELECT [Address]=e.Address,
[LastEmail] = ie.Email
FROM Emails e
OUTER APPLY
( SELECT TOP 1 *
FROM Email innerE
WHERE e.UserID = innerE.UserID
AND innerE.Contact = #emailId
AND (IsSent is null OR isSent = 0)
ORDER BY Timestamp DESC
) ie
This works similar a correlated subquery but allows mulitple rows and multiple columns.

SQL Server : convert sub select query to join

I have 2 two tables questionpool and question where question is a many to one of question pool. I have created a query using a sub select query which returns the correct random results but I need to return more than one column from the question table.
The intent of the query is to return a random test from the 'question' table for each 'QuizID' from the 'Question Pool' table.
SELECT QuestionPool.QuestionPoolID,
(
SELECT TOP (1) Question.QuestionPoolID
FROM Question
WHERE Question.GroupID = QuestionPool.QuestionPoolID
ORDER BY NEWID()
)
FROM QuestionPool
WHERE QuestionPool.QuizID = '5'
OUTER APPLY is suited to this:
Select *
FROM QuestionPool
OUTER APPLY
(
SELECT TOP 1 *
FROM Question
WHERE Question.GroupID = QuestionPool.QuestionPoolID
ORDER BY NEWID()
) x
WHERE QuestionPool.QuizID = '5'
Another example of OUTER APPLY use http://www.ienablemuch.com/2012/04/outer-apply-walkthrough.html
Live test: http://www.sqlfiddle.com/#!3/d8afc/1
create table m(i int, o varchar(10));
insert into m values
(1,'alpha'),(2,'beta'),(3,'delta');
create table x(i int, j varchar, k varchar(10));
insert into x values
(1,'a','hello'),
(1,'b','howdy'),
(2,'x','great'),
(2,'y','super'),
(3,'i','uber'),
(3,'j','neat'),
(3,'a','nice');
select m.*, '' as sep, r.*
from m
outer apply
(
select top 1 *
from x
where i = m.i
order by newid()
) r
Not familiar with SQL server, but I hope this would do:
Select QuestionPool.QuestionPoolID, v.QuestionPoolID, v.xxx -- etc
FROM QuestionPool
JOIN
(
SELECT TOP (1) *
FROM Question
WHERE Question.GroupID = QuestionPool.QuestionPoolID
ORDER BY NEWID()
) AS v ON v.QuestionPoolID = QuestionPool.QuestionPoolID
WHERE QuestionPool.QuizID = '5'
Your query appears to be bringing back an arbitrary Question.QuestionPoolId for each QuestionPool.QuestionPoolId subject to the QuizId filter.
I think the following query does this:
select qp.QuestionPoolId, max(q.QuestionPoolId) as any_QuestionPoolId
from Question q join
qp.QuestionPoolId qp
on q.GroupId = qp.QuestionPoolId
WHERE QuestionPool.QuizID = '5'
group by qp.QuestionPoolId
This returns a particular question.
The following query would allow you to get more fields:
select qp.QuestionPoolId, q.*
from (select q.*, row_number() over (partition by GroupId order by (select NULL)) as randrownum
from Question q
) join
(select qp.QuestionPoolId, max(QuetionPool qp
on q.GroupId = qp.QuestionPoolId
WHERE QuestionPool.QuizID = '5' and
randrownum = 1
This uses the row_number() to arbitrarily enumerate the rows. The "Select NULL" provides the random ordering (alternatively, you could use "order by GroupId".
Common Table Expressions (CTEs) are rather handy for this type of thing...
http://msdn.microsoft.com/en-us/library/ms175972(v=sql.90).aspx