how to perform Two select query in one stored procedure in sql server - sql

I am trying to perform two select query in one stored procedure. But its not giving me any output. There is no error but records are not being displayed.
First I tried this stored Procedure
CREATE PROCEDURE [dbo].[Sp_PriceList_Die_Wise]
#DieNo As Nvarchar(15),
#MetalCode As Int
AS
BEGIN
Select CP.BatchQty,CP.CastingPrice,U.UNITName As 'Unit',MachPrice,U.UNITName As 'M/C Unit' from CustomerPriceList As CP Left Outer Join UNITMaster As U On CP.MUNITID=U.UNITID where MOULDCODE=#DieNo And METALCODE=#MetalCode
SELECT TOP (10) SubOADetail.OANO, SubOADetail.ID, SubOADetail.QTY, SubOADetail.RATE, UNITMaster.UNITName As Unit, OATest.MachPrices, UNITMaster_1.UNITName AS Unit FROM UNITMaster AS UNITMaster_1 RIGHT OUTER JOIN OATest ON UNITMaster_1.UNITID = OATest.MachUnitID RIGHT OUTER JOIN SubOADetail LEFT OUTER JOIN UNITMaster ON SubOADetail.UNIT = UNITMaster.UNITID ON OATest.ID = SubOADetail.ID AND OATest.OANO = SubOADetail.OANO LEFT OUTER JOIN OADetails ON SubOADetail.OANO = OADetails.OANO WHERE SubOADetail.MOULDCODE = #DieNo AND SubOADetail.METALCODE =#MetalCode ORDER BY OADetails.OADATE DESC
END
This gives me output like this
but I want the output in single table so I created this stored procedure
CREATE PROCEDURE [dbo].[Sp_PriceList_Die_Wise]
#DieNo As Nvarchar(15),
#MetalCode As Int
AS
BEGIN
WITH main AS
(
Select CP.BatchQty,CP.CastingPrice,U.UNITName As 'Unit',
MachPrice,U.UNITName As 'M/C Unit' from CustomerPriceList As CP
Left Outer Join UNITMaster As U On CP.MUNITID=U.UNITID
where MOULDCODE=#DieNo And METALCODE=#MetalCode
), sub AS
(
SELECT TOP (10) SubOADetail.OANO, SubOADetail.ID, SubOADetail.QTY, SubOADetail.RATE,
UNITMaster.UNITName As Unit, OATest.MachPrices, UNITMaster_1.UNITName AS MCUnit
FROM UNITMaster AS UNITMaster_1 RIGHT OUTER JOIN OATest ON UNITMaster_1.UNITID = OATest.MachUnitID
RIGHT OUTER JOIN SubOADetail LEFT OUTER JOIN UNITMaster ON SubOADetail.UNIT = UNITMaster.UNITID
ON OATest.ID = SubOADetail.ID AND OATest.OANO = SubOADetail.OANO LEFT OUTER JOIN OADetails
ON SubOADetail.OANO = OADetails.OANO WHERE SubOADetail.MOULDCODE = #DieNo
AND SubOADetail.METALCODE =#MetalCode ORDER BY OADetails.OADATE DESC
)
SELECT *
FROM main m join sub s
ON m.MachPrice = s.MachPrices
END
But this gives me blank record like this

You are using INNER JOIN, and your first table (main) don't have any records, so you will not get any output.
If you want to select from other table even if matching records are not there in the main, you need to change your JOIN to RIGHT JOIN like following.
SELECT *
FROM main m right join sub s
ON m.MachPrice = s.MachPrices
EDIT:
RIGHT JOIN will work for the provided sample data, in case if you have data where left CTE don't have matching records in right CTE or vise versa and you still want to select the records, for such scenario you need a combination of LEFT JOIN and RIGHT JOIN, for this you can use FULL OUTER JOIN like following.
SELECT *
FROM main m full outer join sub s
ON m.MachPrice = s.MachPrices

Related

Passing different column values to where clause

SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid = pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890'
which gives me the following output
Now I want to use the above output values to select the rows from the table "YesNoAnswerWithObservation"
I imagine it should look something like this Select * from YesNoAnswerWithObservation Where Id in (22,27,26,...23)
Only instead of typing the values inside IN clause I want to use the values in each column resulting from above-mentioned query.
I tried the below code but it returns all the rows in the table rather than rows mentioned inside the In
SELECT pims.yesnoanswerwithobservation.observation,
graphitegtccore.yesnoquestion.description,
pims.yesnoanswerwithobservation.id ObservationId
FROM pims.yesnoanswerwithobservation
INNER JOIN graphitegtccore.yesnoquestion
ON pims.yesnoanswerwithobservation.yesnoanswerid =
graphitegtccore.yesnoquestion.id
WHERE EXISTS (SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.pelvicorgandiseaseid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.gynocologicalscanid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid =
pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890')
Any help or a nudge in the right direction would be greatly appreciated
Presumably you want the ids from the first query:
SELECT awo.observation, ynq.description, ynq.id as ObservationId
FROM pims.yesnoanswerwithobservation awo JOIN
graphitegtccore.yesnoquestion ynq
ON awo.yesnoanswerid = ynq.id
WHERE ynq.id = (SELECT mer.id
FROM pims.pimscase c JOIN
pims.digitization d
ON c.digitizationid = d.id JOIN
pims.medicalexaminerreport mer
ON d.medicalexaminerreportid = mer.id JOIN
pims.icicimedicalexaminerreport imer
ON mer.id = imer.id JOIN
pims.icicimerfemaleapplicant ifa
ON imer.id = ifa.id
WHERE c.tiannumber = 'ICICI1234567890'
) ;
Notice that table aliases make the query much easier to write and to read.

Postgresql - Conditional Join if data exist

My current query show the data from the table called "Buque" and has some references from another tables. The problem is when i execute the query it never shows the result because it consumes too much memory i guess.
The current query i have
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq, publico.mae_tipbuque as tbu, publico.mae_pais as pai,
publico.mae_puerto as pue, publico.mae_linea as lin, publico.mae_trafico as tra
where buq.tbu_codigo = tbu.tbu_codigo or
buq.pai_codigo = pai.pai_codigo or
buq.pto_codigo = pue.pto_codigo or
buq.lin_codigo = lin.lin_codigo or
buq.tra_codigo = tra.tra_codigo
I also tried with inner joins but the problem is it returns me the data that meets the conditions of the joins. In other words, if the join has data to compare, returns the name, if not, show the null data.
The query must return me 611 records, with inner joins returns 68 records.
Concerning your desired result, use left outer joins, which fill up any non-existing rows of the right hand side table with null-values;
Concerning the out of memory issue, note that you used or to connect your tables; this actually leads to the fact that almost every record of the involved tables is connected to almost every other record (almost a cross join / cartesian product); This can get very large if you connect 6 tables...
select buq.buq_codigo, tbu.tbu_codigo, tbu.tbu_nombre, pai.pai_codigo, pai.pai_nombre,
pue.pto_codigo, pue.pto_nombre, lin.lin_codigo, lin.lin_nombre, tra.tra_codigo,
tra.tra_nombre, buq.buq_nombre, buq.buq_des, buq.num_trb, buq.num_eslora,
buq.max_tons, buq.reg_lloyd, buq.buq_codigo1, buq.codigo_omi,
case buq.buq_estado when 'A' then 'Activo' else 'Inactivo' end as buq_estado
from publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on buq.tbu_codigo = tbu.tbu_codigo
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo)
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo)
You have to use left outer join:
select *
from
publico.mae_buque as buq
left outer join publico.mae_tipbuque as tbu on (buq.tbu_codigo = tbu.tbu_codigo)
left outer join publico.mae_pais as pai on (buq.pai_codigo = pai.pai_codigo)
left outer join publico.mae_puerto as pue on (buq.pto_codigo = pue.pto_codigo )
left outer join publico.mae_linea as lin on (buq.lin_codigo = lin.lin_codigo)
left outer join publico.mae_trafico as tra on (buq.tra_codigo = tra.tra_codigo);

Cannot get both records with SQL/Bigquery JOINs

I've got a query that returns order details, I want information from the briisk table for deals it has found. I also want it to display orders even if the briisk table has nothing.
If I add the final line (and flostream.briisk.master = "") my query only returns one result instead of two.
SELECT *
FROM (SELECT orderno,ifnull(dealid,sales_rule) as DealIDCombo from flostream.orders left join mobileheads.surveys on mobileheads.surveys.order_number = flostream.orders.externalreference) as first
INNER JOIN flostream.orders on first.orderno = flostream.orders.orderno
LEFT JOIN flostream.briisk on first.dealidcombo = flostream.briisk.uniquereference
WHERE first.orderno in (359692,359683)
//AND flostream.briisk.master = ""
When you use a left outer join, then you need to include filter conditions on the second table in the on clause. So try this:
SELECT *
FROM (SELECT orderno,ifnull(dealid,sales_rule) as DealIDCombo
from flostream.orders left join
mobileheads.surveys
on mobileheads.surveys.order_number = flostream.orders.externalreference
) as first INNER JOIN
flostream.orders
on first.orderno = flostream.orders.orderno LEFT JOIN
flostream.briisk
on first.dealidcombo = flostream.briisk.uniquereference AND
flostream.briisk.master = ""
WHERE first.orderno in (359692, 359683)
Conditions on the first table should go in the WHERE clause.

How to write subquery inside the OUTER JOIN Statement

I want to join two table CUSTMR and DEPRMNT.
My needed is: LEFT OUTER JOIN OF two or more Tables with subquery inside the LEFT OUTER JOIN as shown below:
Table: CUSTMR , DEPRMNT
Query as:
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
dp.DEPID
,dp.DEPNAME
FROM
DEPRMNT dp
WHERE
dp.DEPADDRESS = 'TOKYO'
)
ON (
dp.DEPID = cs.CUSID
AND cs.CUSTNAME = dp.DEPNAME
)
WHERE
cs.CUSID != ''
Here the subquery is:
SELECT
dp.DEPID, dp.DEPNAME
FROM
DEPRMNT dp
WHERE
dp.DEPADDRESS = 'TOKYO'
Is it possible to write such subquery inside LEFT OUTER JOIN?
I am getting an error when running this query on my DB2 database.
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

How can I get all the rows from master table and relevent row from the detail table in MS-SQL?

I am using MS-SQL and I am trying to write a query which fetches rows from the master table and related rows from the detail table. Now, the thing I want is that it must only fetch the first row from the master table and related field from the detail tables should be blank in that first row, now if there are related rows found in the detail tables, they must be shown in the separate rows. I have been trying using the following query but it is not giving the desired result.
SELECT
DISTINCT
ProductMaster.ProductMasterID, ProductMaster.ProductName,
ProductMaster.SubCategoryID, SubCategory.SubCategoryName,
ProductBrandAndType.ProductBranAndTypeID, ProductBrandAndType.ProductType,
ProductBrandAndType.Brand, ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductBrandAndType
RIGHT OUTER JOIN
Inward
ON ProductBrandAndType.ProductBranAndTypeID = Inward.ProductBrandAndTypeID
RIGHT OUTER JOIN
ProductMaster
ON Inward.ProductID = ProductMaster.ProductMasterID
LEFT OUTER JOIN
SubCategory
ON ProductMaster.SubCategoryID = SubCategory.SubCategoryID
ORDER BY
ProductMaster.ProductName,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand;
Can anyone help me on this?
Regards
Sikandar
Following query worked.
SELECT dbo.ProductMaster.ProductMasterID, dbo.ProductMaster.ProductName, dbo.ProductMaster.SubCategoryID, dbo.ProductMaster.ProductDesc,
dbo.ProductMaster.ReOrderLevel, null as ProductBrandAndTypeID,
null AS Type, null as Brand
FROM dbo.ProductBrandAndType RIGHT OUTER JOIN
dbo.Inward ON dbo.ProductBrandAndType.ProductBranAndTypeID = dbo.Inward.ProductBrandAndTypeID RIGHT OUTER JOIN
dbo.ProductMaster ON dbo.Inward.ProductID = dbo.ProductMaster.ProductMasterID LEFT OUTER JOIN
dbo.SubCategory ON dbo.ProductMaster.SubCategoryID = dbo.SubCategory.SubCategoryID
UNION
SELECT dbo.ProductMaster.ProductMasterID, dbo.ProductMaster.ProductName, dbo.ProductMaster.SubCategoryID, dbo.ProductMaster.ProductDesc,
dbo.ProductMaster.ReOrderLevel, dbo.ProductBrandAndType.ProductBranAndTypeID,
dbo.ProductBrandAndType.ProductType, dbo.ProductBrandAndType.Brand
FROM dbo.ProductBrandAndType RIGHT OUTER JOIN
dbo.Inward ON dbo.ProductBrandAndType.ProductBranAndTypeID = dbo.Inward.ProductBrandAndTypeID RIGHT OUTER JOIN
dbo.ProductMaster ON dbo.Inward.ProductID = dbo.ProductMaster.ProductMasterID LEFT OUTER JOIN
dbo.SubCategory ON dbo.ProductMaster.SubCategoryID = dbo.SubCategory.SubCategoryID
ORDER BY ProductName;
If you just what the first row from the ProductMaster. Then you can do something like this:
;WITH CTE
(
SELECT
ROW_NUMBER() OVER(ORDER BY ProductMaster.ProductMasterID) AS RowNbr,
ProductMaster.ProductName,
ProductMaster.SubCategoryID,
ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductMaster
)
SELECT
ProductMaster.ProductMasterID,
ProductMaster.ProductName,
ProductMaster.SubCategoryID,
SubCategory.SubCategoryName,
ProductBrandAndType.ProductBranAndTypeID,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand,
ProductMaster.ProductDesc,
ProductMaster.ReOrderLevel
FROM
ProductBrandAndType
RIGHT OUTER JOIN Inward
ON ProductBrandAndType.ProductBranAndTypeID = Inward.ProductBrandAndTypeID
RIGHT OUTER JOIN CTE AS ProductMaster
ON Inward.ProductID = ProductMaster.ProductMasterID
AND RowNbr=1
LEFT OUTER JOIN SubCategory
ON ProductMaster.SubCategoryID = SubCategory.SubCategoryID
ORDER BY
ProductMaster.ProductName,
ProductBrandAndType.ProductType,
ProductBrandAndType.Brand;