Combining INSERT and CASE SQL Server Queries - sql

Here are a couple of SQL queries that I am trying to either write as a single query or two queries. I have tried various possibilities that I could think of but non worked.
I have a blank table tbl_Z. I am trying to LEFT JOIN tbl_A and tbl_B and load the result into tbl_Z plus update the Status column in tbl_Z from tbl_A based on criteria in the 2 SQL statements shown here:
INSERT INTO tbl_Z
SELECT a.*
FROM tbl_A a
LEFT JOIN tbl_B b ON a.AccountNumber = b.AccountNumber
WHERE a.Period = '09/30/2021'
AND b.AccountNumber IS NULL
UPDATE Z
SET Status = (SELECT
f.ContractDate, f.BK_Date, f.Period,
CASE
WHEN ISNULL(f.ContractDate, '1/1/1900') < ISNULL(f.BK_Date, '1/1/1900') AND f.BK_Date < ISNULL(f.Period, '1/1/1900')
THEN 'Bankrupt.Attrit'
ELSE 'Attrit'
END AS Status
FROM
tbl_A f
WHERE
Period = '09/30/2021')
Any help will be greatly appreciated.

I don't know about fields name, just add fields name in select put the case statement in write order of fields.
INSERT INTO tbl_Z
SELECT -- please write your all tbl_A fields here and then place below case in write order of selection
,
CASE
WHEN ISNULL(f.ContractDate, '1/1/1900') < ISNULL(f.BK_Date, '1/1/1900')
AND f.BK_Date < ISNULL(f.Period, '1/1/1900')
THEN 'Bankrupt.Attrit'
ELSE 'Attrit'
END AS Status
FROM tbl_A a
LEFT JOIN tbl_B b ON a.AccountNumber = b.AccountNumber
WHERE a.Period = '09/30/2021'
AND b.AccountNumber IS NULL;

Related

Selecting ONLY Duplicates from a joined tables query

I have the following query that I'm trying to join two tables matching their ID so I can get the duplicated values in "c.code". I've tried a lot of queries but nothing works. I have a 500k rows in my database and with this query I only get 5k back, which is not right. Im positive it's at least 200K. I also tried to use Excel but it's too much for it to handle.
Any ideas?
Thanks in advance, everyone.
SELECT c.code, c.name as SCT_Name, t.name as SYNONYM_Name, count(c.code)
FROM database.Terms as t
join database.dbo.Concepts as c on c.ConceptId = t.ConceptId
where t.TermTypeCode = 'SYNONYM' and t.ConceptTypeCode = 'NAME_Code' and c.retired = '0'
Group by c.code, c.name, t.name
HAVING COUNT(c.code) > = 1
Order by c.code
with data as (
select c.code, c.name as SCT_Name, t.name as SYNONYM_Name
from database.Terms as t inner join database.dbo.Concepts as c
on c.ConceptId = t.ConceptId
where
t.TermTypeCode = 'SYNONYM'
and t.ConceptTypeCode = 'NAME_Code'
and c.retired = '0'
)
select *
--, (select count(*) from data as d2 where d2.code = data.code) as code_count
--, count(*) over (partition by code) as code_count
from data
where code in (select code from data group by code having count(*) > 1)
order by code
If you want just duplicates of c.code, your Group By is wrong (and so is your Having clause). Try this:
SELECT c.code
FROM database.Terms as t
join database.dbo.Concepts as c on c.ConceptId = t.ConceptId
where t.TermTypeCode = 'SYNONYM' and t.ConceptTypeCode = 'NAME_Code' and c.retired = '0'
Group by c.code
HAVING COUNT(c.code) > 1
This will return all rows where you have more than one c.code value.
You need to use INTERSECT instead of JOIN. Basically you perform the select on the first table then intersect with the second table. The result is the duplicate rows.
Only select the id column, though, otherwise the intersect won't work as expected.

Display Y/N column if record found in detail table

I'm trying to create a query so that I can have a column show Y/N if a particular item was ordered for a group of orders. The item I'm looking for would be OLI.id = '538'.
So my results would be:
Order#, Customer#, FreightPaid
12345, 00112233, Y
12346, 00112233, N
I cannot figure out if I need to use a subquery or the where exists function ?
Here's my current query:
SELECT distinct
OrderID,
Accountuid as Customerno
FROM [SMILEWEB_live].[dbo].[OrderLog] OL
inner join Orderlog_item OLI on OLI.orderlogkey = OL.[key]
inner join Account A on A.uid = OL.Accountuid
where A.GroupId = 'X9955'
and OL.CreateDate >= GETDATE() - 60
I would suggest an exists clause instead of a join:
select ol.OrderID, ol.Accountuid as Customerno,
(case when exists (select 1
from Orderlog_item OLI join
Account A
on A.uid = OL.Accountuid
where OLI.orderlogkey = OL.[key] and A.GroupId = 'X9955'
)
then 1 else 0
end) as flag
from [SMILEWEB_live].[dbo].[OrderLog] OL
where OL.CreateDate >= GETDATE() - 60;
This prevents a couple of problems. First, duplicate rows which are caused when there are multiple matching rows (and select distinct add unnecessary overhead). Second, missing rows, which happen when you use inner join instead of an outer join.

Insert into table with multiple joins under a unique condition based off time

I have an insert statment that incorporates multiple joins. However, the last join (table ItemMulitplers) doesnt really have anything "tied" to the other tables. They are just multipliers in this table with no unique identification or connection with others. the only thing is a timestamp from this table.
I have 5 rows in this table and my script is taking all five rows. I need it to select only one and to base it off of the closest time from the table called ItemsProduced. They get executed at the same time but not on the same millisecond level. any help is most appreciated thank you
insert into KLNUser.dbo.ItemLookup (ItemNumber, Cases, [Description], [Type], Wic, Elc, totalelc, Shift, [TimeStamp])
select a.ItemNumber, b.CaseCount,b.ItemDescription, b.DivisionCode, b.WorkCenter, b.LaborPerCase, a.CaseCount* b.LaborPerCase* c.IaCoPc, a.shift, a.TimeStamp from ItemsProduced a
inner join MasterItemList b on a.ItemNumber = b.itemnumber
inner join ItemMultipliers c on c.MultiplyTimeStamp <=a.Timestamp Interval 1 seconds
where not exists (select * from ItemLookup where ItemNumber = a.ItemNumber and Cases = b.CaseCount and [TimeStamp] = a.TimeStamp)
I think the easiest way is with cross apply:
select a.ItemNumber, b.CaseCount,b.ItemDescription, b.DivisionCode, b.WorkCenter, b.LaborPerCase, a.CaseCount* b.LaborPerCase* c.IaCoPc, a.shift, a.TimeStamp
from ItemsProduced a inner join
MasterItemList b
on a.ItemNumber = b.itemnumber cross apply
(select top 1 *
from ItemMultipliers c
where c.MultiplyTimeStamp < a.Timestamp
order by c.MultiplyTimeStamp desc
) c
where not exists (select * from ItemLookup where ItemNumber = a.ItemNumber and Cases = b.CaseCount and [TimeStamp] = a.TimeStamp)

SQL: Select A when in A and not B or select B when in A and B

SQL is not my strong point and I am struggling to find a solution to this issue. I am trying to figure out how I can get a result set based on the following logic. Select record A when A is not in B OR select B if the record appears in B and A. I tried the following union which returns me all the records that match from the current day in the two tables but I cannot figure out how to pull the data I need from the two tables.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate())
You can do a left outer join, and use a ISNULL or CASE statement in the select to return the required values.
I'll demonstrate:
SELECT
CASE WHEN b.iPurchaseOrderLineId IS NOT NULL THEN 'b' ELSE 'a' END AS [Source],
a.iPurchaseOrderLineId,
ISNULL(b.sProductDescription, a.sProductDescription) AS [sProductDescription]
FROM PurchaseOrderLine AS a
LEFT JOIN GoodsIn AS b ON a.iPurchaseOrderLineId = b.iPurchaseOrderLineId
AND b.dDateDelivered = GETDATE()
WHERE b.iPurchaseOrderLineId IS NOT NULL
OR a.dRequiredDate = CONVERT(DATE, GETDATE())
Hope that helps!
Hope This will help You: Just an example similar to you.
create table A(id int , name char(12))
go
create table B(id int , name char(12))
go
insert into A values (1,'ABC'),(3,'WXY')
insert into B values (1,'ABC'),(2,'AAA')
SELECT a.id,a.name FROM A EXCEPT SELECT * FROM B
UNION
SELECT a.id,a.name FROM A inner join b on a.id=b.id and a.name=b.name
Thanks!!!
If I understand you correctly, assuming GoodsIn=B, you may try something in this fashion.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
LEFT JOIN GoodsIn
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
AND GoodsIn.iPurchaseOrderLineId IS NULL
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate());
You could also try literally as you described (assuming sProductDescription is in PurchaseOrderLine):
"Select record A when A is not in B"
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE iPurchaseOrderLineId NOT IN(SELECT iPurchaseOrderLineId FROM GoodsIn)
or in this way:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE NOT EXISTS(SELECT * FROM GoodsIn
WHERE GoodsIn.iPurchaseOrderLineId=PurchaseOrderLine.iPurchaseOrderLineId)
or using EXCEPT:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
EXCEPT
SELECT 'a', iPurchaseOrderLineId, sProductDescription
FROM GoodsIn;
Just hints, tailor them to your needs.

Creating a view in SQL with a case statement in the select

I know something must be wrong with my syntax but I can't seem to figure it out.
I want to populate this column prop_and_cas_dtl_prdct_desc from either expir_prop_and_cas_dtl_prdct_cd or ren_prop_and_cas_dtl_prdct_cd depending on the value in type_indicator but before it goes into prop_and_cas_dtl_prdct_desc it should look up the prop_and_cas_dtl_prdct_desc from pc_ref_detail_product_cd and select the one corresponding to its expir_prop_and_cas_dtl_prdct_cd or ren_prop_and_cas_dtl_prdct_cd.
I apologize for the terrible indenting, I know it is difficult to read but this is the best way I know how to put it.
select
,ren_prop_and_cas_dtl_prdct_cd
...
,p_and_c_cd
,case when type_indicator in ('R','C') then
select prop_and_cas_dtl_prdct_desc
from pc_ref_detail_product_cd a inner join op_pif_coverage_rpc_new b
on a.prop_and_cas_dtl_prdct_cd = b.expir_prop_and_cas_dtl_prdct_cd
else when type_indicator in ('N','O') then
select prop_and_cas_dtl_prdct_desc
from pc_ref_detail_product_cd a inner join op_pif_coverage_rpc_new b
on a.prop_and_cas_dtl_prdct_cd = b.ren_prop_and_cas_dtl_prdct_cd
else NULL
END
AS prop_and_cas_dtl_prdct_desc
FROM dbo.op_pif_coverage_rpc_new
Here is the code I used to create my reference table
create table pc_ref_detail_product_cd(
prop_and_cas_dtl_prdct_cd char(2),
prop_and_cas_dtl_prdct_desc char(30)
)
insert into pc_ref_detail_product_cd (prop_and_cas_dtl_prdct_cd, prop_and_cas_dtl_prdct_desc)
values ('01', 'CORE'),
('02', 'FORECLOSED'),
('04', 'TRUST'),
('06', 'MORTGAGE HOLDERS E&O'),
('07', 'SECURITY INTEREST E&O')
If you need to select column from different table depending on value in additional column you need to include all tables in query, with appropriate JOIN and than use case statement like so
SELECT CASE WHEN a.MyColumn = 0 THEN b.SomeColumn
WHEN a.MyColumn = 1 THEN a.SomeColumn
END AS SomeColumn
FROM MyTableA AS a
JOIN MyTableB AS b
ON a.ID = b.ID
Instead of select statement in case statement, you just going to select column from ether table that you need for each particular case.
I got it figured out. Here is the SQL I used. Sorry if it wasn't apparent what I wanted to do from my horrible code in the original question.
select
,ren_prop_and_cas_dtl_prdct_cd
...
,p_and_c_cd
,case when type_indicator in ('R','C') then
(select prop_and_cas_dtl_prdct_desc
from pc_ref_detail_product_cd a where expir_prop_and_cas_dtl_prdct_cd = prop_and_cas_dtl_prdct_cd)
when type_indicator in ('N','O') then
(select prop_and_cas_dtl_prdct_desc
prop_and_cas_dtl_prdct_desc
from pc_ref_detail_product_cd a where ren_prop_and_cas_dtl_prdct_cd = prop_and_cas_dtl_prdct_cd)
else NULL
END
AS prop_and_cas_dtl_prdct_desc
FROM dbo.op_pif_coverage_rpc_new