Sybase - Conditional Join on Columns based on value of one column - tsql

I have a situation where I would require to do a conditional join based on the value of the columns on one of the tables.
table_a ta
join table_b tb on
case
when ta.column_1 = 1 then ta.column_2 = tb.column_2
when ta.column_1 = 2 then ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3
when ta.column_1 = 3 then ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3 and ta.column_4 = tb.column_4
end
Please advise how I should go about it?
Tried searching and got some options to use a left join but I am not sure how to do it. :(
Please advise.

i think it's all can be formulated as single boelean expression
...
join table_b tb on
(ta.column_1 = 1 and ta.column_2 = tb.column_2) or
(ta.column_1 = 2 and ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3)
...

You may use left joins and put the case expression when selecting the columns:
select
case when ta.column_1 = 1 then b1.column
case when ta.column_1 = 2 then b2.column
case when ta.column_1 = 3 then b3.column
end
from table_a ta
left join table_b b1 on ta.column_2 = tb.column_2
left join table_b b2 on ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3
left join table_b b3 on ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3 and ta.column_4 = tb.column_4

Try a union
select * from tbla ta, tblb tb
where ta.column_1 = 1
and ta.column_2 = tb.column_2
union
select * from tbla ta, tblb tb
where ta.column_1 = 2
and ta.column_2 = tb.column_2
and ta.column_3 = tb.column_3
union
select * from tbla ta, tblb tb
where ta.column_1 = 3
and ta.column_2 = tb.column_2
and ta.column_3 = tb.column_3
and ta.column_4 = tb.column_4
tada

Related

Two columns next to each other from two queries in PostgreSQL

How do I get two columns goed and slecht side by side with the two following queries. They do work independently of each other.
1:
select count (*) as goed
from movie_info_idx mii
join title t
on mii.movie_id = t.id
join info_type it
on it.id = mii.info_type_id
join kind_type kt
on kt.id = t.kind_id
where kt.id = '1'
and it.id = '101'
and mii.info > '7,5'
2:
select count (*) as slecht
from movie_info_idx mii
join title t
on mii.movie_id = t.id
join info_type it
on it.id = mii.info_type_id
join kind_type kt
on kt.id = t.kind_id
where kt.id = '1'
and it.id = '101'
and mii.info <= '7,5'
But how do I merge both queries so I get two columns goed and slecht next to each other?
Conditional aggregation is likely what you're looking for. Here is an example:
SELECT COUNT(*) FILTER (WHERE mii.info > '7,5') AS goed
, COUNT(*) FILTER (WHERE mii.info <= '7,5') AS slecht
FROM movie_info_idx mii
JOIN title t ON mii.movie_id = t.id
JOIN info_type it ON mii.info_type_id = it.id
JOIN kind_type kt ON t.kind_id = kt.id
WHERE kt.id = '1'
AND it.id = '101'
;

TSQL IN and NOT IN

I have the below query that returns all diagnosis that do not have a '-829' value associated to them. The query does work but I think that I've made it harder than it should be. Is there a tidier way of doing this?
select distinct
c2.diagnosisn DiagnosisName,
a2.text CareLookup
from core_patdiagnosis c1
LEFT OUTER JOIN core_diagnosis c2 ON c1.diagnosis = c2.id
LEFT OUTER JOIN core_carecontext c3 ON c1.carecontex = c3.id
LEFT OUTER JOIN applookup_instance a1 ON c1.lkp_specialty = a1.id
LEFT OUTER JOIN core_diagnosis_taxonomyma c5 ON c2.id = c5.id
LEFT OUTER JOIN applookup_instance a3 ON c5.lkp_taxonomyna = a3.id
LEFT OUTER JOIN applookup_instance a2 ON c3.lkp_context = a2.id
where c2.id IN
(
select c11.id core_diagnosis_c1_id
from core_diagnosis c11
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE
c11.isactive = 1
and a11.id != -829 or a11.id is null
)
AND
c2.id NOT IN
(
select c12.id ProcID
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE
c12.isactive = 1
and a12.id = -829 or a12.id is null
)
AND
c1.sys_creation_datetime > '01 Dec 2017 00:00:00' AND a2.text like
'%Emergency%'
extra stuff not used
a2.text like '%Emergency%' breaks the outer join
select distinct c2.diagnosisn DiagnosisName, a2.text CareLookup
from core_patdiagnosis c1
JOIN core_diagnosis c2 ON c2.id = c1.diagnosis
JOIN core_carecontext c3 ON c3.id = c1.carecontex
JOIN applookup_instance a2 ON a2.id = c3.lkp_context
where c2.id IN
( select c11.id
from core_diagnosis c11
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE c11.isactive = 1 and a11.id != -829
or a11.id is null
)
AND
c2.id NOT IN
( select c12.id
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE c12.isactive = 1 and a12.id = -829
or a12.id is null
)
AND c1.sys_creation_datetime > '01 Dec 2017 00:00:00'
AND a2.text like '%Emergency%'
You could use a CTE (Common Table Expression - see msdn page):
WITH BufferTableCTE (id)
AS
(...)
SELECT ...
FROM ...
WHERE id in (SELECT id FROM BufferTableCTE WHERE id != -829)
AND NOT id in (SELECT id FROM BufferTableCTE WHERE id = -829)
AND ...
Another way would be to store an intermediate result in a temporary table and then use this temporary table later on (twice, once with id != -829 and once with id = 829)
Both ways would reduce your repeated sql declarations.

I receive conversion varchar to float error when insert **set rowcount=1** in first line of code

I receive an error
Coversion of varchar to float
when I write
set rowcount = 1
on first line of my code.
My script is:
select
vh.VchNum, ct.Val, r.RoutSheetNo, vi.FinalQty,
rh.RequestNo, vh.VchDate,
p.PartCode, d.Title, co.val
from
inv.InvVchHdr vh
join
acc.DL d on d.AccNum = vh.DLREF
join
inv.InvVchItm vi on vi.VchHdrRef = vh.VchHdrID
join
inv.InvVchItmCtrl ct on ct.VchItmRef = vi.VchItmID
join
QCS.QcsCertificateOfAnalysis q on q.Number = ct.Val
join
USR.kalaf_info_p kp on kp.Id = q.QcsCertificateOfAnalysisId
join
USR.coil_trace co on co.id = kp.coil_id
join
inv.Part p on p.Serial = vi.PartRef
join
inv.InvRqstItm rq on rq.RqstItmID = vi.RefNum
join
inv.InvRqstHdr rh on rh.RqstHdrID = rq.HdrRef
join
PRD.vwPrdOrderItemPlan pl on rh.OrdPlnBase = pl.OrdPlnId
join
prd.prdroutsheet r on r.OrdPlnRef = pl.OrdPlnId
where
pl.pPartRef not in (select pipe_code from usr.pipe_kalaf)
and pl.pPartRef not in (select Serial from inv.Part where PartName like '%لاف%')
and vi.VchType = 57
union
select vh.VchNum,ct.Val,pl.OrdPlnNo
,vi.FinalQty,
rh.RequestNo,vh.VchDate,
p.PartCode,d.Title,co.val from
inv.InvVchHdr vh
join acc.DL d
on d.AccNum=vh.DLREF
join
inv.InvVchItm vi
on vi.VchHdrRef=vh.VchHdrID
join inv.InvVchItmCtrl ct
on ct.VchItmRef=vi.VchItmID
join QCS.QcsCertificateOfAnalysis q
on q.Number=ct.Val
join USR.kalaf_info_p kp
on kp.Id=q.QcsCertificateOfAnalysisId
join USR.coil_trace co
on co.id=kp.coil_id
join
inv.Part p
on p.Serial=vi.PartRef
join inv.InvRqstItm rq
on rq.RqstItmID=vi.RefNum
join inv.InvRqstHdr rh
on rh.RqstHdrID=rq.HdrRef
join PRD.vwPrdOrderItemPlan pl
on rh.OrdPlnBase=pl.OrdPlnId
where pl.pPartRef in (select pipe_code from usr.pipe_kalaf) and vi.VchType=57
SET ROWCOUNT 0
i use sql server 2000 and when I remove setrowcount statement, problem resolve.
please help me
Remove the =(equal) sign
from
set rowcount = 1
To
SET ROWCOUNT 1

set value from select for few select

I have select, iside select have 2 column. This column must be filled from same select, but I don't want use select twice for it. Is it possoble use select 1 time and after that set second column value from first?
Example:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = (select aa from table1 where quantity > 5)
I need:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = {value from a}
Update. I wrote bad example, I need set to BalancePrediction1 and BalancePrediction2 value from Balance
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance -
(
SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
)
) as Balance,
Balance AS 'BalancePrediction1',
Balance AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
You could do an update to the table variable after the insert.
update #tmpBalances
set BalancePrediction1 = Balance,
BalancePrediction2 = Balance
Or you can use cross apply to calculate the sum.
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance - Mov.SumAmount) AS Balance,
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction1',
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
CROSS APPLY (SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
) Mov(SumAmount)
SELECT aa AS a, aa AS b
FROM table1
WHERE quantity > 5
One way;
;with T (value) as (
select aa from table1 where quantity > 5
)
insert into #temptable
select value, value from T

T-SQL Nested Subquery

I want to place this working code within a SQL Statement, OR do I need to perform a UDF.
The result set is a one line concatenation, and I want it to be place in every one of the overall result set lines.
----
MAIN QUERY
SELECT
H.CONNECTION_ID,
H.SEQUENTIAL_NO,
H.INVOICE_NUMBER,
H.INVOICE_DATE,
H.LAST_INVOICE_NUMBER,
H.LAST_INVOICE_DATE,
CAST(CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN '-'
ELSE CAST(H.PAYMENT_DUE_DATE AS NVARCHAR(20))
END AS SMALLDATETIME) AS PAYMENT_DUE,
H.JOB_NUMBER,
H.CUST_JOB_NUMBER,
HDR.SALES_PERSON,
H.INSIDE_SALES_PERSON,
H.IS_LAST_INVOICE,
CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN 'CASH'
ELSE H.PAYMENT_TERMS_DESCRIPTION
END AS PAYMENT_TERMS,
H.PRINTED,
H.NOTES,
CUR.ID,
CUR.CODE,
CASE CUR.CODE
WHEN 'USD' THEN '001-106624-211'
WHEN 'EUR' THEN '001-106624-101'
WHEN 'GBP' THEN '001-106624-100'
ELSE '001-106624-001'
END AS BANK_ACCT,
CUR.EXCHANGE_RATE,
H.BILL_CONTACT,
H.CUST_ACCOUNT,
H.CUST_NAME,
H.CUST_ADDR1,
H.CUST_ADDR2,
H.CUST_CITY,
H.CUST_STATE,
H.CUST_ZIP,
H.CONTACT_PHONE_NUMBER,
H.CONTACT_PHONE_NUMBER2,
H.ORDERED_BY_CONTACT,
H.SHIP_TO_NAME,
H.SHIP_TO_ADDR1,
H.SHIP_TO_ADDR2,
H.SHIP_TO_CITY,
H.SHIP_TO_STATE,
H.SHIP_TO_ZIP,
H.SITE_PHONE_NUMBER,
H.SITE_PHONE_NUMBER2,
H.OFFICE_NAME,
H.OFFICE_ADDR1,
H.OFFICE_ADDR2,
H.OFFICE_CITY,
H.OFFICE_STATE,
H.OFFICE_ZIP,
H.OFFICE_PHONE_NUMBER,
H.OFFICE_FAX_NUMBER,
H.DELIVERY_TICKET_NUMBER,
H.PO_NUMBER,
H.DUMMY_INVOICE_TEXT,
(SELECT MESSAGE FROM REPORT_MESSAGES WHERE CODE = 'INVOICE') ADVERT_MESSAGE,
(SELECT MAX(DISCOUNT_PERCENTAGE) FROM PRTINVITEM I2 WHERE I2.CONNECTION_ID = H.CONNECTION_ID AND I2.INVOICE_NUMBER = H.INVOICE_NUMBER) AS MAX_DISCOUNT,
I.ITEM,
I.DESCRIPTION,
I.QUANTITY,
I.UNIT_OF_MEASURE,
I.MINIMUM_CHARGE,
I.WEEKLY_CHARGE,
I.MONTHLY_CHARGE,
I.START_OF_BILLING_PERIOD,
I.END_OF_BILLING_PERIOD,
I.DAYS_USED,
I.WEEKS_USED,
I.DISCOUNT_PERCENTAGE,
I.TAX_CODE_FOR_ITEM,
I.INVENTORY_TYPE,
I.BILLING_LOGIC_TYPE,
I.ACTUAL_WEEKLY_CHARGE_USED,
I.DAYS_IN_ACTUAL_WEEKLY_CHARGE,
II.CHARGEABLE_DAYS,
II.CHARGEABLE_WEEKS,
II.CHARGEABLE_MONTHS,
II.FREE_DAYS_THIS_INVOICE,
CNV.TOTAL_NET_VALUE,
CNV.TOTAL_TAX_VALUE,
CNV.TOTAL_GROSS_VALUE,
CNV.TOTAL_GROSS_VALUE_NS,
CNV.NET_LINE_VALUE,
CMP.EMAIL_ADDRESS
FROM (PRTINVHDR H INNER JOIN PRTINVITEM I ON H.CONNECTION_ID = I.CONNECTION_ID AND H.INVOICE_NUMBER = I.INVOICE_NUMBER)
INNER JOIN INVOICEHDR HDR ON I.INVOICE_NUMBER = HDR.INVNO
INNER JOIN CUSTOMERS CST ON H.CUST_ACCOUNT = CST.CUSTNUM
INNER JOIN JOB JOB ON H.JOB_NUMBER = JOB.JOBNUM
INNER JOIN CURRENCY CUR ON HDR.CURRENCY_ID = CUR.ID
INNER JOIN VWCURRENCYCONVERSION CNV ON I.CONNECTION_ID = CNV.CONNECTION_ID AND I.INVC_UCOUNTER = CNV.INVC_UCOUNTER
INNER JOIN COMPANY CMP ON H.OFFICE_CODE = CMP.OFFICE
INNER JOIN INVOICEITEM II ON I.INVOICE_NUMBER = II.INVNO AND I.INVC_UCOUNTER = II.INVC_UCOUNTER
ORDER BY
H.SEQUENTIAL_NO,
I.PRINT_SEQUENCE
ASC
----
COALESCE QUERY
DECLARE
#DTICKET NVARCHAR(20),
#PUMPCATEGORYNAME NVARCHAR(3999)
SET #DTICKET = ''
SET #PUMPCATEGORYNAME = NULL
(SELECT
#DTICKET = DTICKET,
#PUMPCATEGORYNAME = COALESCE(#PUMPCATEGORYNAME + ', ', '' ) + PUMPCATEGORYNAME
FROM (SELECT
BHDR.DTICKET,
SCD.PUMPCATEGORYNAME
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
WHERE SCD.PUMPCATEGORYNAME IS NOT NULL)
SUBCATEGORYDESCRIPTION)
SELECT #DTICKET, #PUMPCATEGORYNAME
Not really sure what you are asking for but you can doing something along the lines of
Select col1 + ', ' + col2 + ', ' + col3 etc....