SQL Server : left join - check for right table column value is null - sql-server

I have a query as follows:
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo,
CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'
from
table1 tbl1
inner join
table2 tbl2 on tbl2.Id = tbl1.Id
left join -- This left join table gives me 5 records for one instance
(select
R.Id, C.Comments
from
tblC C
inner join
tblR R on R.Id = C.id) tbl3 on tbl3.Id = tbl2.Id
I want to write a CASE statement on the rows my left join is giving to check for null value as above and my final select query always return only 1 row. Is there a way to check if all five Comments Column values from my left join be checked for NULLs in the above query?

I would take a shortcut an use a COUNT() OVER PARTITION
CASE WHEN COUNT(*) OVER (PARTITION BY tbl3.Id) =0 THEN 0 ELSE 1 END AS 'Required'
You would have to DISTINCT your output above. Another option would be to GROUP BY and filter in the HAVING clause.
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo
From table1 tbl1
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
SELECT R.Id,
C.Comments
FROM tblC C
INNER JOIN tblR R on R.Id = C.id
) tbl3 on tbl3.Id = tbl2.Id
GROUP BY
Id, Name, Address, relNo
HAVING
COUNT(*) = 5

Is this what you're looking for?
(CASE WHEN (select count(tbl3.id) FROM tbl3 WHERE tbl3.Comments IS NULL) then 1 else 0 end) as 'RequiredVal'
select --this select should always give me 1 record
tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo,
CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'
, (CASE WHEN (select count(tbl3.id) FROM tbl3 WHERE tbl3.Comments IS NULL) then 1 else 0 end) as 'RequiredVal'
From table1 tbl1
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
SELECT R.Id,
C.Comments
FROM tblC C
INNER JOIN tblR R on R.Id = C.id
) tbl3 on tbl3.Id = tbl2.Id

Related

Query in getting multiple duplicate rows in SQL Server

I have 2 tables Table1 and Table2 in which I want to get the total count of duplicate rows:
Expected output:
Query tested:
SELECT
t1.name,
t1.duplicates,
ISNULL(t2.active, 0) AS active,
ISNULL(t3.inactive, 0) AS inactive
FROM
(SELECT
t1.name, COUNT(*) AS duplicates
FROM
(SELECT c.name
FROM table1 c
INNER JOIN table2 as cd on cd.id = c.id)) t1
GROUP BY
name
HAVING
COUNT(*) > 1) t1
LEFT JOIN
(SELECT c.name, COUNT(*) AS active
FROM table1 c
WHERE name IN (SELECT c.name FROM table1 c)
GROUP BY c.name AND status = 'Active'
GROUP BY name) t2 ON t1.name = t2.name
LEFT JOIN
(SELECT c.name, COUNT(*) AS inactive
FROM table1 c
WHERE name IN (SELECT c.name FROM table1 c GROUP BY c.name)
AND status = 'InActive'
GROUP BY name) t3 ON t1.name = t3.name
ORDER BY
name
It is still returning duplicate rows and I'm unable to get the id and creator column
If you would pardon subquery and left join, i'd suggest the following query:
select b.*,
count(creator) as creator_count
from
(select a.mainid,
a.name,
sum(case when a.status = "active"
then 1 else 0 end) as active_count,
sum(case when a.status = "inactive"
then 1 else 0 end) as inactive_count,
count(a.name) as duplicate_count
from table1 as a
group by a.name
having count(a.name) > 1) as b
left join table2 as c
on b.mainid = c.mainid
group by c.mainid
having count(c.creator) > 1
rather than forcing our way to join the two table directly. First, derive the information we can get from the Table1 then join it with the Table2 to get the creator count.
SQL Fiddle: http://sqlfiddle.com/#!9/4daa19e/28

SQL Server 2005 Select Data From Table1 and Table2 but if Table2 column1 value is null Select Data From Table3

My Query IS
SELECT TblPharmacyBillingDetails.UPBNo, TblMasterBillingData.IPDNo, InPatRegistration.PatTitle+PatientName, TblPharmacyBillingDetails.InvoiceNo, TblPharmacyBillingDetails.InvoiceDateTime, TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
but if TblMasterBillingData.IPDNo value is NULL select Data From TblMasterBillingData.OPDNo and
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.IPDNo
Method #1: Using UNION
SELECT * FROm
(
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.IPDNo,
InPatRegistration.PatTitle+PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
WHERE TblMasterBillingData.IPDNo IS NOT NULL
UNION ALL
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.OPDNo,
OutPatRegistration .PatTitle + PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.OPDNo
WHERE TblMasterBillingData.OPDNo IS NOT NULL
)Tmp
ORDER BY TblPharmacyBillingDetails.UPBNo
Method #2 Using ISNULL and LEFT JOIN
SELECT TblPharmacyBillingDetails.UPBNo,
ISNULL(TblMasterBillingData.IPDNo,TblMasterBillingData.OPDNo),
ISNULL(IP.PatTitle + IP.PatientName, OP.PatTitle + OP.PatientName),
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
LEFT JOIN InPatRegistration IP ON TblMasterBillingData.IPDNo = IP.IPDNo
LEFT JOIN outPatRegistration OP ON TblMasterBillingData.OPDNo = OP.OPDNo
ORDER BY TblPharmacyBillingDetails.UPBNo
You can write either case statement or ISNULL() function as shown below in the demo query.
SELECT
Orders.OrderID,
Case when Customers1.CustomerName is null then Customers2.CustomerName else Customers1.CustomerName
end as CustomerName, --way 1
ISNULL(Customers1.CustomerName, Customers2.CustomerName) as Customer, --way 2
Orders.OrderDate
FROM Orders
INNER JOIN Customers1 ON Orders.CustomerID = Customers1.CustomerID
INNER JOIN Customers2 ON Orders.CustomerID = Customers2.CustomerID
-- where your condition here
-- order by your column name
You can also check whether data is available or not in the table and join the table accordingly using if exists as shown below.
if exists(select 1 from tablename where columnname = <your values>)

how to Join five Tables with one another dependency in SQL

I want to join five tables in SQL server. The sequence as given below. Logic should be
Table1 >>>>Key : ID >>>> Table_A & Table_B (If Table1.Status = ABC then Table_A else Table_B ) >>> Key : NUMBER >>> Table2 >>> Key : Number + Item_No >>> Table3
Please help if below code could work.
SELECT * FROM
TABLE1
LEFT JOIN (CASE WHEN status = 'ABC' THEN Table_A ELSE Table_B END ) X ON (Table1.ID = X.ID)
LEFT JOIN Table2 ON (X.NUMBER = Table2.NUMBER)
LEFT JOIN Table3 ON (Table3.CONCAT(NUMBER + Item_No) = Table2.CONCAT(NUMBER + Item_No))
SELECT Q.*, T2.ItemNo, T2.Product, T3.Connection
FROM (
SELECT T1.ID, CASE WHEN T1.Status = 'ABC'
THEN TA.Number
ELSE TB.Number
END as Number
FROM Table1 T1
LEFT JOIN TableA TA
ON T1.ID = TA.ID
LEFT JOIN TableB TB
ON T1.ID = TB.ID
) as Q
JOIN Table2 T2
ON Q.Number = T2.Number
JOIN Table3 T3
ON T2.ItemNo = T3.ItemNo

Number of execution is equal to the number of rows in SQL Server

I am having a query in which number of execution is equal to the number of rows in the table.
Anyone knows any possible reason for that as a result the clustered index seek %age is very high.
I have update the Stats for the Tables.But still no benefit.
select #AdditionalBillToNumericValue = cast(ab_vnum as int) from #table1
inner join table4 on ab_btid = ay_bt and ab_type = 'SRVGRP'
if(#AdditionalBillToNumericValue is not null or #AdditionalBillToNumericValue <> '')
begin
select distinct
fs.sv_pkey
, fs.sv_id
, fs.sv_desc
,ISNULL( fs.sv_ehr,0) as sv_ehr
,ISNULL( fs.sv_emn,0) as sv_emn
,ISNULL( fs.sv_lhr,0) as sv_lhr
,ISNULL( fs.sv_lmn,0) as sv_lmn
,(case when #table1.fh_sv = fs.sv_id then 1 else 0 end) IsDefault
from table3 fr
inner join table4 ab on ab.ab_vnum = fr.sr_sgpkey
inner join table5 fs on fr.sr_svpkey = fs.sv_pkey or fs.sv_pkey = #ServiceWindowKey
inner join #table1 on ab.ab_btid = #table1.ay_bt
AND ab.ab_type = 'SRVGRP'
end
else
begin
select
fs.sv_pkey
, fs.sv_id
, fs.sv_desc
,ISNULL(sv_ehr,0) as sv_ehr
,ISNULL(sv_emn,0) as sv_emn
,ISNULL(sv_lhr,0) as sv_lhr
,ISNULL(sv_lmn,0) as sv_lmn
,(case when #table1.fh_sv = fs.sv_id then 1 else 0 end) IsDefault
from table3 fr
inner join table4 ab on ab.ab_vnum = fr.sr_sgpkey
inner join table5 fs on fr.sr_svpkey = fs.sv_pkey or fs.sv_pkey = #ServiceWindowKey
LEFT join #table1 with(nolock) on ab.ab_btid = #table1.ay_bt
where ab.ab_type = 'SRVGRP'
Please Verify where we are having the join with table5 it is getting the issue.
In Join Both are having int datatype.

insert query with subqueries

I am trying to insert some values (CIID and AID) taken from another tables, but as not an expert, I couldn't manage to do it.
Insert query :
INSERT INTO INST_ACTIVE_ACTIONS act
(act.CIID, act.AID, act.STEPNUM, act.CREATEDATE)
VALUES
(CIID , ,0,GETDATE())
The CIID Query is :
SELECT C.CIID FROM INST_COURSE C
LEFT JOIN INST_ACTIVE_ACTIONS AA ON (AA.CIID = C.CIID)
LEFT JOIN INST_TASKS T ON (T.CIID = C.CIID)
LEFT JOIN SYS_SCH_ACTION SCH ON (SCH.CIID = C.CIID)
LEFT JOIN SYS_SUB_STACK SUB ON (SUB.RETURN_CIID=C.CIID)
WHERE C.COMPLETED IS NULL AND AA.AID IS NULL AND T.AID IS NULL AND SCH.AID IS NULL AND SUB.RETURN_AID IS NULL
AID Query is :
SELECT TOP 1 ca.AID
FROM INST_COMPLETE_ACTIONS CA
INNER JOIN TMPL_ACT_MASTER TAM ON CA.AID=TAM.AID
WHERE ca.CIID =c.CIID ORDER BY TSTAMP DESC
act.CIID = C.CIID = ca.CIID and CA.AID = act.AID
Edited :
the last query is
INSERT INTO INST_ACTIVE_ACTIONS (CIID,AID,stepnum,CREATEDATE
)
VALUES
(
(SELECT c.CIID
FROM INST_COURSE C
LEFT JOIN INST_ACTIVE_ACTIONS AA
ON (
aa.CIID = c.CIID)
LEFT JOIN INST_TASKS T
ON (
t.CIID = c.CIID)
LEFT JOIN SYS_SCH_ACTION SCH
ON (
sch.CIID = c.CIID)
LEFT JOIN sys_sub_stack SUB
ON (
sub.RETURN_CIID = c.CIID)
WHERE c.completed IS NULL
AND aa.AID IS NULL
AND t.AID IS NULL
AND sch.AID IS NULL
AND sub.return_AID IS NULL),
(
SELECT TOP 1
ca.AID
FROM INST_COMPLETE_ACTIONS CA
INNER JOIN tmpl_act_master TAM
ON ca.AID=tam.AID
ORDER BY tstamp DESC
),
0,
Getdate() )
but i get an error as
Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1
value. This is not permitted when the subquery follows =, !=, <, <= ,
, >= or when the subquery is used as an expression. The statement has been terminated.
Just condensed though its real busy if you ask me.
INSERT INTO INST_ACTIVE_ACTIONS
(CIID, AID, STEPNUM, CREATEDATE)
--OUTPUT INSERTED.* --if you want to see what was inserted uncomment this
(SELECT C.CIID,
(SELECT TOP 1 CA.AID
FROM INST_COMPLETE_ACTIONS CA
INNER JOIN TMPL_ACT_MASTER TAM ON CA.AID=TAM.AID
WHERE CA.CIID =C.CIID ORDER BY TSTAMP DESC)
, 0,GETDATE())
FROM INST_COURSE C
LEFT JOIN INST_ACTIVE_ACTIONS AA ON (AA.CIID = C.CIID)
LEFT JOIN INST_TASKS T ON (T.CIID = C.CIID)
LEFT JOIN SYS_SCH_ACTION SCH ON (SCH.CIID = C.CIID)
LEFT JOIN SYS_SUB_STACK SUB ON (SUB.RETURN_CIID=C.CIID)
WHERE C.COMPLETED IS NULL AND AA.AID IS NULL AND T.AID IS NULL AND SCH.AID IS NULL AND SUB.RETURN_AID IS NULL)
Revised. tested, and working on my end. I still think if you have control on these tables you might look into the concept of Normalizing your database tables.
You can always perform something like this, and use as many sub queries as needed. Make sure that the types are matching on both sides.
Insert into table1 (value1, value2) Select val1,val2 from table2 ...
edit
INSERT INTO INST_ACTIVE_ACTIONS act (act.CIID, act.AID,
act.STEPNUM, act.CREATEDATE) Select
(SELECT C.CIID FROM INST_COURSE C LEFT JOIN INST_ACTIVE_ACTIONS AA ON (AA.CIID = C.CIID) LEFT JOIN INST_TASKS T ON
(T.CIID = C.CIID) LEFT JOIN SYS_SCH_ACTION SCH ON (SCH.CIID = C.CIID)
LEFT JOIN SYS_SUB_STACK SUB ON (SUB.RETURN_CIID=C.CIID) WHERE
C.COMPLETED IS NULL AND AA.AID IS NULL AND T.AID IS NULL AND SCH.AID
IS NULL AND SUB.RETURN_AID IS NULL), (SELECT TOP 1 ca.AID FROM
INST_COMPLETE_ACTIONS CA INNER JOIN TMPL_ACT_MASTER TAM ON
CA.AID=TAM.AID WHERE ca.CIID =c.CIID ORDER BY TSTAMP DESC act.CIID
= C.CIID = ca.CIID and CA.AID ),0,GETDATE()

Resources