SQL Server query using Union - any good alternate possible? - sql-server

I have a SQL Server query as:
SELECT top 1 vConsentInfo FROM
(
SELECT cons.vConsentInfo,cons.dTimeStamp ,logs.iPartnerProfileID
FROM H_OutMessageLog logs INNER JOIN H_OutMessageConsent cons on cons.iOutMessageQID = logs.iOutQueueID
WHERE logs.iPatID = 65686 and logs.iPracID = 4
UNION
SELECT cons.vConsentInfo,cons.dTimeStamp,Q.iPartnerProfileID
FROM H_OutMessageQueue Q INNER JOIN H_OutMessageConsent cons on cons.iOutMessageQID = Q.iOutQueueID
WHERE Q.iPatID = 65686 and Q.iPracID = 4
) A
WHERE A.iPartnerProfileID = Prof.IPartnerProfileID
Order BY dTimeStamp DESC
The table works as : a record get inserted into H_OutMessageQueue at the begining; then its inserted into H_OutMessageConsent...
Now there is a seperate worker process that processes records from H_OutMessageQueue and log them into H_OutMessageLog....
Can I get rid of this UNION thing ? Please note that this is a sub Query of a larger CTE query.

Yes, but it may not be better. You'll have to work this into your bigger query
SELECT TOP 1
cons.vConsentInfo,
ISNULL(logs.iPartnerProfileID , Q.iPartnerProfileID) AS iPartnerProfileID
FROM
H_OutMessageConsent cons
LEFT JOIN
H_OutMessageLog logs ON cons.iOutMessageQID = logs.iOutQueueID AND
logs.iPatID = 65686 and logs.iPracID = 4
LEFT JOIN
H_OutMessageQueue Q ON cons.iOutMessageQID = Q.iOutQueueID AND
Q.iPatID = 65686 and Q.iPracID = 4
WHERE
ISNULL(logs.iPartnerProfileID , Q.iPartnerProfileID) IS NOT NULL
ORDER BY
cons.dTimeStamp DESC

In addition to gbn reply. This will remove the extra burden from your query:).
SELECT top 1 vConsentInfo FROM
(
SELECT cons.vConsentInfo,cons.dTimeStamp ,logs.iPartnerProfileID
From
(
Select iPartnerProfileID FROM H_OutMessageLog logs
WHERE logs.iPatID = 65686 and logs.iPracID = 4
)logs
Left JOIN H_OutMessageConsent cons on cons.iOutMessageQID = logs.iOutQueueID
UNION
SELECT cons.vConsentInfo,cons.dTimeStamp,Q.iPartnerProfileID
From
(
Select iPartnerProfileID FROM H_OutMessageQueue Q
WHERE Q.iPatID = 65686 and Q.iPracID = 4
)Q
Left JOIN H_OutMessageConsent cons on cons.iOutMessageQID = Q.iOutQueueID
) A
WHERE A.iPartnerProfileID = Prof.IPartnerProfileID
Order BY dTimeStamp DESC

Related

Compare and identify new records in Select query for different dates

I have a query as part of a stored procedure and the results are correct. I do however need to add code to compare the results to the results of the same query when it last ran e.g. 2 days ago. I then need any new records that was not on the results from 2 days ago to appear on top (first) in the results. I tried using the Except clause, but the results are wrong.
Any help will be appreciated how to identify any new records compared to the records from GETDATE()-1. Thank you
SELECT distinct rt.sPortfolio, CAST(rt.iRuleId AS VARCHAR(15)) AS iRuleId, sDescription, sComment, rt.sPortfolio AS BlankRow
FROM thinktank..ruletests AS rt
INNER JOIN thinktank..rules AS r
ON r.id = rt.iruleid
AND dttest > getdate()-0.5
AND iresult <> 4
AND ichecktype = 3
AND r.iCategory = 0
AND sRuleSet <> 'NOTIFY'
INNER JOIN thinktank..GroupPortfolios AS gp
ON rt.sPortfolio = gp.sPortfolioId
AND sGroupID = 'EC'
LEFT OUTER JOIN thinktank..RuleUCs AS ruc
ON r.id = ruc.iruleid
AND ruc.icategory = '636'
WHERE ISNULL(ruc.sValue,'N') <> 'Y'
EXCEPT
SELECT distinct rt.sPortfolio, CAST(rt.iRuleId AS VARCHAR(15)) AS iRuleId, sDescription, sComment, rt.sPortfolio AS BlankRow
FROM thinktank..ruletests AS rt
INNER JOIN thinktank..rules AS r
ON r.id = rt.iruleid
AND dttest > getdate()-1
AND iresult <> 4
AND ichecktype = 3
AND r.iCategory = 0
AND sRuleSet <> 'NOTIFY'
INNER JOIN thinktank..GroupPortfolios AS gp
ON rt.sPortfolio = gp.sPortfolioId
AND sGroupID = 'EC'
LEFT OUTER JOIN thinktank..RuleUCs AS ruc
ON r.id = ruc.iruleid
AND ruc.icategory = '636'
WHERE ISNULL(ruc.sValue,'N') <> 'Y'

Converting Oracle Query into T-SQL query using WITH

I have a query from an old database that we converting into T-SQL, but having issues using CTE:
Original Query in Oracle:
select company_name, display_name, active_flag, naic_code, group_number, alien_code, fein,
status_desc, status_detail_desc, due_to_merger_flag, co_code, to_char(status_date, 'MM/DD/YYYY')
Inactive_Date, active_flag from
(select nm.COMPANY_NAME, cmp.recordid_number, orgtp.display_name, cmp.active_flag,
cmp.naic_code, grpnm.group_number, cmp.alien_code, cmp.fein, st.status_desc, stdt.status_detail_desc,
storgjn.due_to_merger_flag, storgjn.co_code, storgjn.status_date, st.active_flag as activestatus,
max(storgjn.status_date) over (partition by cmp.recordid_number, orgtp.display_name) max_status_date
from aip.co_company cmp join aip.CO_NAME nm on cmp.COMPANY_ID = nm.company_id and nm.active_flag = 1
left outer join aip.co_company_group_jn cmpgrpjn on nm.COMPANY_ID = cmpgrpjn.company_id and cmpgrpjn.active_flag = 1
left outer join aip.co_group_name grpnm on cmpgrpjn.group_id = grpnm.group_id and grpnm.active_flag = 1
join aip.co_org org on cmp.COMPANY_ID = org.company_id
join aip.co_org_type orgtp on org.org_type_id = orgtp.org_type_id
join aip.co_status_org_jn storgjn on org.org_id = storgjn.org_id
join aip.co_status_detail stdt on storgjn.status_detail_id = stdt.status_detail_id
join aip.co_status st on stdt.status_id = st.status_id
WHERE cmp.recordid_number = '10632' AND
stdt.status_detail_desc <> 'Record Begin Date')
WHERE status_date = max_status_date
And converting into T-SQl im using:
WITH YOURCTE(WHATEVA) AS
(
SELECT nm.COMPANY_NAME, cmp.recordid_number, orgtp.display_name, cmp.active_flag,
cmp.naic_code, grpnm.group_number, cmp.alien_code, cmp.fein, st.status_desc, stdt.status_detail_desc,
storgjn.due_to_merger_flag, storgjn.co_code, storgjn.status_date, st.active_flag as activestatus,
max(storgjn.status_date) over (partition by cmp.recordid_number, orgtp.display_name) max_status_date
from aip.co_company cmp join aip.CO_NAME nm on cmp.COMPANY_ID = nm.company_id and nm.active_flag = 1
left outer join aip.co_company_group_jn cmpgrpjn on nm.COMPANY_ID = cmpgrpjn.company_id and cmpgrpjn.active_flag = 1
left outer join aip.co_group_name grpnm on cmpgrpjn.group_id = grpnm.group_id and grpnm.active_flag = 1
join aip.co_org org on cmp.COMPANY_ID = org.company_id
join aip.co_org_type orgtp on org.org_type_id = orgtp.org_type_id
join aip.co_status_org_jn storgjn on org.org_id = storgjn.org_id
join aip.co_status_detail stdt on storgjn.status_detail_id = stdt.status_detail_id
join aip.co_status st on stdt.status_id = st.status_id
WHERE cmp.recordid_number = '10632' AND
stdt.status_detail_desc <> 'Record Begin Date'
)
select company_name, display_name, active_flag, naic_code, group_number, alien_code, fein,
status_desc, status_detail_desc, due_to_merger_flag, co_code, CONVERT(VARCHAR(10),status_date,120) AS Inactive_Date,
active_flag
FROM YOURCTE
WHERE status_date = max_status_date
But I get the following error :
Msg 8158, Level 16, State 1, Line 2
'YOURCTE' has more columns than were specified in the column list.
The reason i have more columns in my cte is because I'm using the recordid_number column to bring other data for where conditioning. I will appreciate some help, thank you.
Either replace "WHATEVA" with a complete list of the column aliases you want to use, or remove it and let the original column names stand.
Inherit
;WITH YOURCTE AS
(...
Explicit
;WITH YOURCTE (COMPANY_NAME, recordid_number, ...) AS
(...

T-Sql How to get Max dated records?

I want max dated rows for per GroupCode
I wrote this.
SELECT FH.BelgeNo AS FaturaNo
,FHD.UrunId
,FH.Tarih
,UG.Grup AS GrupKodu
,FHD.Kodu
,FHD.UrunAdi
,FHD.BirimFiyat
FROM FirmaHareketDetayi FHD
LEFT JOIN FirmaHareketleri FH ON FH.ID = FHD.HareketId
LEFT JOIN Urunler U ON U.UrunId = FHD.UrunId --and U.Kodu = FHD.Kodu
LEFT JOIN UrunGruplari UG ON UG.GrupId = U.GrupId
WHERE FHD.Kodu = '2S619H307CF'
AND FH.FirmaId = 2610
ORDER BY Tarih DESC
and results are like this
There are 2 PIERBURG rows.
is it possible to get only one PIERBURG ?
I mean max dated one (Tarih: Date column, GrupKodu: Group Code)
Notes: Table UrunGrupları: ProductGroups
Table FirmaHareketleri: FirmMovements
Table FirmaHareketDetayi: FirmMovementDetails (Connected with FirmMovements by HareketId (Foreign Key))
Sorry about my english :(
You can use window functions for this
;with cte as (
SELECT FH.BelgeNo AS FaturaNo
,FHD.UrunId
,FH.Tarih
,UG.Grup AS GrupKodu
,FHD.Kodu
,FHD.UrunAdi
,FHD.BirimFiyat
, row_number() over(partition by UG.Grup order by FH.Tarih desc) as rownum
FROM FirmaHareketDetayi FHD
LEFT JOIN FirmaHareketleri FH ON FH.ID = FHD.HareketId
LEFT JOIN Urunler U ON U.UrunId = FHD.UrunId --and U.Kodu = FHD.Kodu
LEFT JOIN UrunGruplari UG ON UG.GrupId = U.GrupId
WHERE FHD.Kodu = '2S619H307CF'
AND FH.FirmaId = 2610
)
select *
from cte
where rownum = 1

sql query assistance

I have a sql that is as under:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on p.item_code = ib.item_code
WHERE ib.on_hand <> 0
This SQL returns only those branch_no that have on_hand <> 0.
I am trying to get all the branch_nos irrespective of the on_hand field, but while still using the where on_hand clause.
Taking the on_hand clause away solves my problem, but gives me large amount of un-needed rows with 0's.
I am using SQL SERVER 2008 R2.
Thanks in advance for any guidance. Please apologize if I am missing any information.
------------------------------------------ENTIRE SQL QUERY (Updated)---------------------------------------------
select
ib.branch_no,
p.weighted_av,
p.item_code,
p.x_value,
p.y_value,
ib.on_hand,
p.on_hand as PhysicalOH,
ip.price,
i.item_code as StyleCode,
i.description,
i.cat1,
i.cat2,
i.cat3,
i.cat4,
np.is_style_yn,
si.supplier_code ,
ysv.sort as YSort
from physical as p
left outer JOIN
item_branch as ib on p.item_code = ib.item_code -- and ib.on_hand <> 0
INNER JOIN
item_price as ip on p.item_code = ip.item_code and ip.price_type = 'P1'
INNER JOIN
style_values as sv on p.style_code = sv.style_code and p.x_value = sv.value
INNER JOIN
style_values as ysv on p.style_code = ysv.style_code and p.y_value = ysv.value and ysv.axis = 'Y'
INNER JOIN
ITEM as i on p.style_code = i.item_code
INNER JOIN
NON_PHYSICAL as np ON i.item_code = np.item_code and np.is_style_yn = 1
INNER JOIN
supplier_item as si ON i.item_code = si.item_code and si.pref_supp_no = 1
where --ib.on_hand <> 0 and
sv.axis = 'X' and
i.item_code in
(SELECT ITEM.item_code
FROM ITEM
INNER JOIN
NON_PHYSICAL ON ITEM.item_code = NON_PHYSICAL.item_code
LEFT JOIN
supplier_item ON Item.item_code = supplier_item.item_code and pref_supp_no = 1
WHERE NON_PHYSICAL.is_style_yn = 1 and ITEM.cat1 = 'Verge Sportswear Ltd' )
order by
si.supplier_code,
i.cat4,
i.cat3,
i.cat2,
i.cat1,
sv.sort
Try this:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on (p.item_code = ib.item_code AND ib.on_hand <> 0)

JOIN codition in SQL Server

After applying join condition on two tables I want records which is maximum among records of left table
My query
SELECT a1.*,
t.*,
( a1.trnratefrom - t.trnratefrom )AS minrate,
( a1.trnrateto - t.trnrateto ) AS maxrate
FROM (SELECT a.srno,
trndate,
b.trnsrno,
Upper(Rtrim(Ltrim(b.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(b.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(b.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(b.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(b.trnunit))) AS trnunit,
b.trnratefrom,
b.trnrateto,
a.remark,
entdate
FROM mstprodrates a
INNER JOIN trnprodrates b
ON a.srno = b.srno)a1
INNER JOIN (SELECT c.srno,
trndate,
d.trnsrno,
Upper(Rtrim(Ltrim(d.trnstate))) AS trnstate,
Upper(Rtrim(Ltrim(d.trnarea))) AS trnarea,
Upper(Rtrim(Ltrim(d.trnquality))) AS trnquality,
Upper(Rtrim(Ltrim(d.trnlength))) AS trnlength,
Upper(Rtrim(Ltrim(d.trnunit))) AS trnunit,
d.trnratefrom,
d.trnrateto,
c.remark,
entdate
FROM mstprodrates c
INNER JOIN trnprodrates d
ON c.srno = d.srno) AS t
ON a1.trnstate = t.trnstate
AND a1.trnquality = t.trnquality
AND a1.trnunit = t.trnunit
AND a1.trnlength = t.trnlength
AND a1.trnarea = t.trnarea
AND a1.remark = t.remark
WHERE t.srno = (SELECT MAX(srno)
FROM a1
WHERE srno < a1.srno)
If you mean to say,
you want Records exist in Left table but not in right then use LEFT OUTER JOIN.

Resources