How to append rows to result from SELECT query in SQL? - sql

I have a query which gives me desired result. Column names are like this(which I am getting from the query):
RXID |DrName |SBOID |SBOName |RxHonoredDate |RxnHonoured |CallRecievedFrom |MobileNo
Now I have one table named 'SampleRepeat'. This have following columns
DrID | CallRecievedFrom | Mobile | SBOID |RxnHonoured
(Here we'll fetch DrName through DrID from table TblDr and SBOName through SBOID)
This is my query:
select G.RXID, NoOfRx, DrName,HospitalName,G.EmpCode AS SBOID ,TM_Name AS SBOName,CONVERT(DATETIME,H.CreatedDate) AS RxHonoredDate, DrSpeciality AS Speciality,
convert(DATETIME, G.CreatedDate) AS [RxGeneratedDate],COALESCE(H.rows, 0) AS RxnHonoured,
CallRecievedFrom,MobileNo ,G.HQ
from(
select RXID,SUM(RxGenerate) as NoOfRx, DrName,HospitalName,RX.EmpCode,TE.TM_Name, DrSpeciality,convert(DATE,RX.CreatedDate)as CreatedDate,TE.Territory AS HQ
from tbl_rx RX
left join tblEmployee TE on TE.TM_Emp_Id=RX.EmpCode
GROUP BY RX.EmpCode,RX.DrName,RX.HospitalName,RX.CreatedDate,RX.DrSpeciality,TE.TM_Name,RX.RXID,TE.Territory
)G
left join
( SELECT EmpCode,DrID,CreatedDate, SUM(MedToPCount) AS rows,CallRecievedFrom,MobileNo FROM tbl_MedicinToPatient WHERE Status = 'Delivered' GROUP BY EmpCode,DrID,CreatedDate,CallRecievedFrom,MobileNo
)H
on H.DrID=G.RXID ORDER BY TM_Name, H.CreatedDate ASC
I want to append this table values to end of query result and all other columns will be null.
I have tried Union all but no success. How do I do that? Any help would be much appreciated.

UNION with a calculated column or UNION ALL should work.
SELECT
*
FROM
(
SELECT
OrderID = 1
RXID,
DrName,
SBOID,
SBOName,
RxHonoredDate,
RxnHonoured,
CallRecievedFrom,
MobileNo
FROM
Query Q
UNION
SELECT
OrderID = 2
RXID = NULL,
DrName = DrID,
SBOID = NULL,
SBOName = SBOID,
RxHonoredDate = NULL,
RxnHonoured,
CallRecievedFrom,
MobileNo = Mobile
FROM
SampleRequest) AS X
ORDER BY
OrderID

Make sure that the order and data type of each column from both SELECT match.
SELECT
RXID,
DrName,
SBOID,
SBOName,
RxHonoredDate,
RxnHonoured,
CallRecievedFrom,
MobileNo
FROM
YourFirstTable AS T
UNION ALL
SELECT
RXID = NULL,
DrName = NULL,
SBOID = T.SBOID,
SBOName = NULL,
RxHonoredDate = NULL,
RxnHonoured = T.RxnHonoured,
CallRecievedFrom = T.CallRecievedFrom,
MobileNo = T.Mobile
FROM
YourSecondTable AS T

Related

How to return a value with COALESCE when a SELECT statement returns nothing?

Hello Stackoverflow community !
I got this code :
(SELECT COALESCE(id, 0) FROM members WHERE user_id = 1225282512438558720)
UNION ALL
(SELECT COALESCE(id, 0) FROM channels WHERE channel_id = 720694686028791971)
UNION ALL
(SELECT COALESCE(id, 0) FROM guilds WHERE guild_id = 831900150115991605);
Each statement could or not could return a value (because nothing corresponds to the WHERE Clause)
My problem is that if for example the first statement returns nothing then Postgres is going to return me this
coalesce
----------
6
1
but i want that Postgres returns me this :
coalesce
----------
NULL
6
1
How can i do that ?
This query returns nothing because no rows satisfy filter criteria. To return rows from the empty result set you need to do aggregation. So you need:
(SELECT max(id) FROM members WHERE user_id = 1225282512438558720)
UNION ALL
(SELECT max(id) FROM channels WHERE channel_id = 720694686028791971)
UNION ALL
(SELECT max(id) FROM guilds WHERE guild_id = 831900150115991605);
For multiple columns or results, you can left-join an unary row table to each of your inputs
WITH dual AS (select 1)
(SELECT COALESCE(id, 0) FROM dual LEFT JOIN members ON user_id = 1225282512438558720)
UNION ALL
(SELECT COALESCE(id, 0) FROM dual LEFT JOIN channels ON channel_id = 720694686028791971)
UNION ALL
(SELECT COALESCE(id, 0) FROM dual LEFT JOIN guilds ON guild_id = 831900150115991605);

How to combine two queries to get one result?

I need two combine two queries to get one result only. Here's the first code.
SELECT FKLTI_KTRGN, COUNT(DISTINCT VIEW_PELAJAR_ENROLL.MB_NAMA) AS BIL_UG
FROM VIEW_PELAJAR_ENROLL, KOD_BANGSA, KOD_NEGERI, JANTINA, KOD_AGAMA, KOD_CACAT, TARAF_KAHWIN
WHERE KOD_KTRGN_PROGRAM = 'SARJANA MUDA'
AND MS_SESI = '2015/2016'
AND MB_BANGSA = KOD_BANGSA
AND KOD_NEGERI = MB_ASAL
AND MB_JANTINA = JAN_KOD
AND KOD_AGAMA = MB_AGAMA
AND KOD_CACAT = MB_CACAT
AND KOD_TARAF = MB_TARAF_KAHWIN
AND MS_STATUS_SEMASA IN
(SELECT SP_KOD
FROM STATUS_PELAJAR
WHERE STATUS_ENROLL = 'Y'
AND SP_TAMAT IS NULL
AND SP_KOD = MS_STATUS_SEMASA)
GROUP BY FKLTI_KTRGN
And this is the second code.
SELECT FKLTI_KTRGN, COUNT(DISTINCT PELAJAR_BIODATA.MBUT_NAMA) AS BIL_PG
FROM PELAJAR_BIODATA,KOD_NEGERI,FAKULTI,KOD_IJAZAH,PELAJAR_BUTIR_PENGAJIAN,STATUS_PENGAJIAN A,
KOD_STATUS_PELAJAR_IPS, KOD_CACAT, KOD_BANGSA, E_KOD_PENGAJIAN, JANTINA, KOD_PROGRAM
WHERE A.STAT_STATUS IN (SELECT KOD_STATUS
FROM KOD_STATUS_PELAJAR_IPS
WHERE STATUS_ENROLL='Y'
AND KOD_STATUS=STAT_STATUS)
AND A.STAT_NOMKPB=MBUT_NOMKPB
AND PBP_PROGRAM IN ('5','6')
AND MBUT_ASAL=KOD_NEGERI(+)
AND SUBSTR(A.STAT_KOD_IJAZAH,1,1)=FKLTI_KOD
AND PBP_PROGRAM=KOD_PROGRAM.KOD_PROGRAM
AND A.STAT_KOD_IJAZAH=KOD_IJAZAH_UM
AND A.STAT_NODAFTAR=PBP_NODAFTAR
AND MBUT_CACAT=KOD_CACAT
AND KOD_BANGSA=MBUT_BANGSA
AND PBP_JENIS_PENGAJIAN=KOD_JNS_PENGAJIAN
AND MBUT_JANTINA=JAN_KOD
AND MBUT_WARGA IS NOT NULL
AND MBUT_BANGSA IS NOT NULL
AND MBUT_JANTINA IS NOT NULL
AND MBUT_NEGERI IS NOT NULL
AND PBP_PROGRAM IS NOT NULL
AND A.STAT_STATUS=KOD_STATUS
AND PBP_KOD_IJAZAH IS NOT NULL
AND A.STAT_SESI||A.STAT_SEMESTER IN (SELECT MAX(B.STAT_SESI||B.STAT_SEMESTER) FROM STATUS_PENGAJIAN B
WHERE B.STAT_NODAFTAR=A.STAT_NODAFTAR
AND B.STAT_NOMKPB=A.STAT_NOMKPB
AND A.STAT_SESI||A.STAT_SEMESTER=B.STAT_SESI||B.STAT_SEMESTER)
AND A.STAT_SESI = '2015/2016'
group by FKLTI_KTRGN
This is the expected result:
This is what i get:
I've tried to use UNION but it doesn't work. Anyone can help me? I really need your help. Thank you in advance!
In order to use union, you need to have the same number of fields and the same field name of both query.
as in both queries of yours, the second field has different name: BIL_PG, BIL_UG
Try this
select * from
(SELECT FKLTI_KTRGN, COUNT(DISTINCT VIEW_PELAJAR_ENROLL.MB_NAMA) AS BIL_UG
FROM VIEW_PELAJAR_ENROLL, KOD_BANGSA, KOD_NEGERI, JANTINA, KOD_AGAMA, KOD_CACAT, TARAF_KAHWIN
WHERE KOD_KTRGN_PROGRAM = 'SARJANA MUDA'
AND MS_SESI = '2015/2016'
AND MB_BANGSA = KOD_BANGSA
AND KOD_NEGERI = MB_ASAL
AND MB_JANTINA = JAN_KOD
AND KOD_AGAMA = MB_AGAMA
AND KOD_CACAT = MB_CACAT
AND KOD_TARAF = MB_TARAF_KAHWIN
AND MS_STATUS_SEMASA IN
(SELECT SP_KOD
FROM STATUS_PELAJAR
WHERE STATUS_ENROLL = 'Y'
AND SP_TAMAT IS NULL
AND SP_KOD = MS_STATUS_SEMASA)
GROUP BY FKLTI_KTRGN)
union
select * from (SELECT FKLTI_KTRGN, COUNT(DISTINCT PELAJAR_BIODATA.MBUT_NAMA) AS BIL_PG
FROM PELAJAR_BIODATA,KOD_NEGERI,FAKULTI,KOD_IJAZAH,PELAJAR_BUTIR_PENGAJIAN,STATUS_PENGAJIAN A,
KOD_STATUS_PELAJAR_IPS, KOD_CACAT, KOD_BANGSA, E_KOD_PENGAJIAN, JANTINA, KOD_PROGRAM
WHERE A.STAT_STATUS IN (SELECT KOD_STATUS
FROM KOD_STATUS_PELAJAR_IPS
WHERE STATUS_ENROLL='Y'
AND KOD_STATUS=STAT_STATUS)
AND A.STAT_NOMKPB=MBUT_NOMKPB
AND PBP_PROGRAM IN ('5','6')
AND MBUT_ASAL=KOD_NEGERI(+)
AND SUBSTR(A.STAT_KOD_IJAZAH,1,1)=FKLTI_KOD
AND PBP_PROGRAM=KOD_PROGRAM.KOD_PROGRAM
AND A.STAT_KOD_IJAZAH=KOD_IJAZAH_UM
AND A.STAT_NODAFTAR=PBP_NODAFTAR
AND MBUT_CACAT=KOD_CACAT
AND KOD_BANGSA=MBUT_BANGSA
AND PBP_JENIS_PENGAJIAN=KOD_JNS_PENGAJIAN
AND MBUT_JANTINA=JAN_KOD
AND MBUT_WARGA IS NOT NULL
AND MBUT_BANGSA IS NOT NULL
AND MBUT_JANTINA IS NOT NULL
AND MBUT_NEGERI IS NOT NULL
AND PBP_PROGRAM IS NOT NULL
AND A.STAT_STATUS=KOD_STATUS
AND PBP_KOD_IJAZAH IS NOT NULL
AND A.STAT_SESI||A.STAT_SEMESTER IN (SELECT MAX(B.STAT_SESI||B.STAT_SEMESTER) FROM STATUS_PENGAJIAN B
WHERE B.STAT_NODAFTAR=A.STAT_NODAFTAR
AND B.STAT_NOMKPB=A.STAT_NOMKPB
AND A.STAT_SESI||A.STAT_SEMESTER=B.STAT_SESI||B.STAT_SEMESTER)
AND A.STAT_SESI = '2015/2016'
group by FKLTI_KTRGN)

Distinct keyword not fetching results in Oracle

I have the following query where I unique records for patient_id, meaning patient_id should not be duplicate. Each time I try executing the query, seems like the DB hangs or it takes hours to execute, I'm not sure. I need my records to load quickly. Any quick resolution will be highly appreciated.
SELECT DISTINCT a.patient_id,
a.study_id,
a.procstep_id,
a.formdata_seq,
0,
(SELECT MAX(audit_id)
FROM audit_info
WHERE patient_id =a.patient_id
AND study_id = a.study_id
AND procstep_id = a.procstep_id
AND formdata_seq = a.formdata_seq
) AS data_session_id
FROM frm_rg_ps_rg a,
PATIENT_STUDY_STEP pss
WHERE ((SELECT COUNT(*)
FROM frm_rg_ps_rg b
WHERE a.patient_id = b.patient_id
AND a.formdata_seq = b.formdata_seq
AND a.psdate IS NOT NULL
AND b.psdate IS NOT NULL
AND a.psresult IS NOT NULL
AND b.psresult IS NOT NULL) = 1)
OR NOT EXISTS
(SELECT *
FROM frm_rg_ps_rg c
WHERE a.psdate IS NOT NULL
AND c.psdate IS NOT NULL
AND a.psresult IS NOT NULL
AND c.psresult IS NOT NULL
AND a.patient_id = c.patient_id
AND a.formdata_seq = c.formdata_seq
AND a.elemdata_seq! =c.elemdata_seq
AND a.psresult != c.psresult
AND ((SELECT (a.psdate - c.psdate) FROM dual)>=7
OR (SELECT (a.psdate - c.psdate) FROM dual) <=-7)
)
AND a.psresult IS NOT NULL
AND a.psdate IS NOT NULL;
For start, you have a cartesian product with PATIENT_STUDY_STEP (pss).
It is not connected to anything.
select *
from (select t.*
,count (*) over (partition by patient_id) as cnt
from frm_rg_ps_rg t
) t
where cnt = 1
;

SQL select statement in where clause

Hi there I am trying to execute a query but cannot seem to get it right.
SELECT *
FROM table
WHERE id IN (SELECT *
FROM table
WHERE description = 'A')
AND description = 'B'
Above is the query that I have got, the select * from table where description = A works as expected when ran alone I just need to make the where clause to work so I can see any id that has a description of A and B.
You will be getting multiple columns from the sub query when I assume you only want the id column:
SELECT *
FROM table
WHERE id IN (SELECT id
FROM table
WHERE description = 'A')
AND description = 'B'
No need for the select in the where clause
SELECT *
FROM table
WHERE id IN ('A', 'B')
Try this:
SELECT *
FROM table
WHERE description IN ('A', 'B')
it should be:
select * from table where id in (select id from table where description = 'A') and description = 'B'
but this query will give you zero result as you select records with description = 'A' and description = 'B', if you want to get records with either description of A or B, then you should write as
select * from table where description = 'A' or description = 'B'
or
select * from table where description in ('A','B')
SELECT distinct AnaTablo.Id , AnaTablo.FirmaAdi , AnaTablo.FirmaId , AnaTablo.KayitTarihi ,
users.Email Personel, (SELECT top 1 sabitler.Ayar from tblSabitAyarlar sabitler WHERE sabitler.Tur = 29 and sabitler.Deger in
(SELECT top 1 IslemId from tblEFaturaTakipIslem Islem WHERE AnaTablo.Id = Islem.EFaturaTakipId order by KayitTarihi desc))YapilanIslem,
AnaTablo.Eposta , AnaTablo.Aciklama
from tblEFaturaTakip AnaTablo left join AspNetUsers users on AnaTablo.PersonelId = users.Id

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.