How to use Order By and With clause - sql

I am using following SQL query to fetch set of records.
;WITH SFPIPELINE AS (
SELECT
PIPELINE_STRING,
PACKET_NUMBER,
PIPELINE_NUMBER
FROM
[RTMASTER].[DBO].[SF_PIPELINE]
WHERE
PIPELINE_STRING IN (
'SOLUTION_TEST',
'2018.01_SVC_SANDBOX',
'2018.01_SVC_ENG'
)
AND PACKET_NUMBER IN (98, 1090, 1092)
),
PROJ_INST_PIPELINE AS (
SELECT
DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID,
PIP.PROJECT_INSTANCE_ID,
PIP.PACKET_NUMBER,
PIP.PROJECT_NUMBER,
PIP.SOURCE_SET_INSTANCE,
SFP.PIPELINE_STRING
FROM
PROJECT_INSTANCE_PIPELINE PIP
INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER
AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER
AND PIP.ACTIVE = 1
AND PIP.PROJECT_INSTANCE_PIPELINE_ID >= 20481038
),
PROJ_INST_BASE AS (
SELECT
PIP.PROJECT_INSTANCE_PIPELINE_ID,
PIP.PROJECT_NUMBER,
PIP.PACKET_NUMBER,
PIP.PIPELINE_STRING,
PIP.SOURCE_SET_INSTANCE,
PIP.PROJECT_INSTANCE_ID,
PIB.ORIGINAL_PROMOTER,
PIB.DEV_INSTANCE,
PROJECT_TYPE_NUMBER,
PIB.SUBVERSION_PROJECT_REVISION,
PIB.SUBVERSION _PROJECT_URL,
PIB.Front_End,
PIB.Back_End
FROM
PROJECT_INSTANCE_BASE PIB
INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID
AND PIP.PROJECT_NUMBER = PIB.PROJECT_NUMBER
AND PIB.PROJECT_TYPE_NUMBER IN (5, 105, 106)
),
SF_PROJ AS (
SELECT
PJTINST.PROJECT_INSTANCE_PIPELINE_ID,
PJTINST.PROJECT_INSTANCE_ID,
PJTINST.PROJECT_NUMBER,
PJTINST.PIPELINE_STRING,
PJTINST.ORIGINAL_PROMOTER,
PJTINST.SOURCE_SET_INSTANCE,
PJTINST.PROJECT_TYPE_NUMBER,
PJTINST.PACKET_NUMBER,
SFP.PROJECT_NAME,
PJTINST.SUBVERSION_PROJECT_REVISION,
PJTINST.SUBVERSION_PROJECT_URL,
PJTINST.Front_End,
PJTINST.Back_End
FROM
DBO.SF_PROJECT SFP
INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER
),
USER_DETAIL AS (
SELECT
SFP.PROJECT_NAME,
SFP.PROJECT_NUMBER,
SFP.PROJECT_TYPE_NUMBER,
SFP.SOURCE_SET_INSTANCE,
SFP.PACKET_NUMBER,
SFP.PIPELINE_STRING,
SFP.SUBVERSION_PROJECT_REVISION,
SFP.SUBVERSION_PROJECT_URL,
SFP.PROJECT_INSTANCE_PIPELINE_ID,
SFP.PROJECT_INSTANCE_ID,
AIAA.EMAIL_ADDRESS,
SFP.Front_End,
SFP.Back_End
FROM
SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA
INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER
),
FINAL AS (
SELECT
UD.PROJECT_NAME,
FP.Feature_Number,
UD.PROJECT_NUMBER,
UD.PROJECT_TYPE_NUMBER,
UD.SOURCE_SET_INSTANCE,
UD.PACKET_NUMBER,
UD.PIPELINE_STRING,
UD.SUBVERSION_PROJECT_REVISION,
UD.SUBVERSION_PROJECT_URL,
UD.PROJECT_INSTANCE_PIPELINE_ID,
UD.PROJECT_INSTANCE_ID,
UD.EMAIL_ADDRESS,
UD.Front_End,
UD.Back_End
FROM
[RTMaster].[dbo].[Feature_Projects_History] FP
INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID
)
SELECT
*
FROM
FINAL
Query is working fine only thing is the records are not sorted.
I want to use order by on PROJECT_INSTANCE_PIPELINE_ID so that all the rows are sorted. When I use ORDER BY clause seeing following error.
Error:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Not sure how to use Order By and With Clause together.
Any thoughts!

try like below i just used PROJECT_NAME in order by
WITH SFPIPELINE AS
(SELECT PIPELINE_STRING, PACKET_NUMBER, PIPELINE_NUMBER FROM [RTMASTER].[DBO].[SF_PIPELINE]
WHERE PIPELINE_STRING IN ( 'SOLUTION_TEST', '2018.01_SVC_SANDBOX', '2018.01_SVC_ENG')
AND PACKET_NUMBER IN (98, 1090, 1092)),
PROJ_INST_PIPELINE AS
(SELECT DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_INSTANCE_ID, PIP.PACKET_NUMBER, PIP.PROJECT_NUMBER, PIP.SOURCE_SET_INSTANCE, SFP.PIPELINE_STRING FROM PROJECT_INSTANCE_PIPELINE PIP
INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER AND PIP.ACTIVE = 1
AND PIP.PROJECT_INSTANCE_PIPELINE_ID >= 20481038),
PROJ_INST_BASE AS
(SELECT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_NUMBER, PIP.PACKET_NUMBER, PIP.PIPELINE_STRING, PIP.SOURCE_SET_INSTANCE, PIP.PROJECT_INSTANCE_ID, PIB.ORIGINAL_PROMOTER, PIB.DEV_INSTANCE,PROJECT_TYPE_NUMBER, PIB.SUBVERSION_PROJECT_REVISION, PIB.SUBVERSION_PROJECT_URL,
PIB.Front_End, PIB.Back_End FROM PROJECT_INSTANCE_BASE PIB INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID AND PIP.PROJECT_NUMBER= PIB.PROJECT_NUMBER AND PIB.PROJECT_TYPE_NUMBER IN (5,105, 106)),
SF_PROJ AS
(SELECT PJTINST.PROJECT_INSTANCE_PIPELINE_ID, PJTINST.PROJECT_INSTANCE_ID, PJTINST.PROJECT_NUMBER, PJTINST.PIPELINE_STRING, PJTINST.ORIGINAL_PROMOTER, PJTINST.SOURCE_SET_INSTANCE, PJTINST.PROJECT_TYPE_NUMBER, PJTINST.PACKET_NUMBER, SFP.PROJECT_NAME,
PJTINST.SUBVERSION_PROJECT_REVISION, PJTINST.SUBVERSION_PROJECT_URL, PJTINST.Front_End, PJTINST.Back_End FROM DBO.SF_PROJECT SFP INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER),
USER_DETAIL AS
(SELECT SFP.PROJECT_NAME, SFP.PROJECT_NUMBER, SFP.PROJECT_TYPE_NUMBER, SFP.SOURCE_SET_INSTANCE, SFP.PACKET_NUMBER, SFP.PIPELINE_STRING, SFP.SUBVERSION_PROJECT_REVISION, SFP.SUBVERSION_PROJECT_URL, SFP.PROJECT_INSTANCE_PIPELINE_ID, SFP.PROJECT_INSTANCE_ID, AIAA.EMAIL_ADDRESS, SFP.Front_End, SFP.Back_End
FROM SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER),
FINAL AS
(SELECT UD.PROJECT_NAME, FP.Feature_Number, UD.PROJECT_NUMBER, UD.PROJECT_TYPE_NUMBER, UD.SOURCE_SET_INSTANCE, UD.PACKET_NUMBER, UD.PIPELINE_STRING, UD.SUBVERSION_PROJECT_REVISION, UD.SUBVERSION_PROJECT_URL,
UD.PROJECT_INSTANCE_PIPELINE_ID, UD.PROJECT_INSTANCE_ID, UD.EMAIL_ADDRESS, UD.Front_End, UD.Back_End FROM [RTMaster].[dbo].[Feature_Projects_History] FP
INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID)
SELECT * FROM FINAL order by PROJECT_NAME -- use here others column name as you need

Related

SQL Server aggregate function without group by

I want to include tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours without applying group by. How can I do that?
SELECT
bp.Serial_Number,
tcon.Serial_Number AS ConverterSerialNumber,
MAX(tcon.Time_Stamp) AS DateStamp,
tcon.Inductive_Injection_Hours,
tcon.Capacitive_Injection_Hours
FROM
dbo.Bypass AS bp
INNER JOIN
dbo.Converter AS c ON bp.Bypass_ID = c.Bypass_ID
INNER JOIN
dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
WHERE
(bp.Site_ID = 7)
GROUP BY
bp.Serial_Number, tcon.Serial_Number,
tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours
ORDER BY
ConverterSerialNumber
I have figured it out.
select [data].Serial_Number,Time_Stamp,Inductive_Injection_Hours,Capacitive_Injection_Hours,b.Serial_Number from Converter_Tel_Data as [data]
inner join dbo.Converter AS c On [data].Converter_ID = c.Converter_ID
inner join dbo.Bypass as b on c.Bypass_ID = b.Bypass_ID
WHERE
(Time_Stamp = (SELECT MAX(Time_Stamp) FROM Converter_Tel_Data WHERE Converter_ID = [data].Converter_ID)) And ([data].Site_ID=7)
ORDER BY [data].Serial_Number
You can use row_number - either in a CTE/derived table or using a trick with TOP 1.
Select Top 1 With Ties
bp.Serial_Number
, tcon.Serial_Number AS ConverterSerialNumber
, tcon.Time_Stamp AS DateStamp
, tcon.Inductive_Injection_Hours
, tcon.Capacitive_Injection_Hours
From dbo.Bypass AS bp
Inner Join dbo.Converter AS c On bp.Bypass_ID = c.Bypass_ID
Inner Join dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
Where bp.Site_ID = 7
Order By
row_number() over(Partition By bp.Serial_Number Order By tcon.Time_Stamp desc)
This should return the latest row from the tconn table for each bp.Serial_Number.

I am converting Oracle queries to Standard Bigquery, i am gettting error "IN subquery is not supported inside join predicate."

I have converted oracle query into below standard bq but in last statement(IN subquery). I am getting error:
"IN subquery is not supported inside join predicate."
Please advise how to use IN subquery in bq in the below code
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`domain-rr.DB_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`domain-rr.oracle_DB_DB.he_project_assoc`
INNER JOIN
`domain-rr.DB_RPT.PROJECT_GR_QTY`
ON
`domain-rr.oracle_DB_DB.he_project_assoc`.child_ISBN = `domain-
rr.DB_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `domain-rr.oracle_DB_DB.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
AND yy.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`domain-rr.DB_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`domain-rr.oracle_DB_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `domain-
rr.oracle_DB_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )
Can you try like this:
Select * from (
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`pearson-rr.oracle_grdw_grdw.he_project_assoc`
INNER JOIN
`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`
ON
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.child_ISBN = `pearson-
rr.GRDW_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `pearson-rr.oracle_grdw_grdw.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
) AA
where AA.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`pearson-rr.GRDW_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`pearson-rr.oracle_grdw_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `pearson-
rr.oracle_grdw_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )

SQL Query to return 2 results for multiple employees

I am very new to SQL and in fact, I am completely self taught. I currently have this query below which works to find (badly) 2 random support tickets by employee.
Right now, the query will ask the employees name and provide 2 results. Is there a way to have this provide 2 results for ALL employees?
SELECT
TOP 2 CONVERT (
DATE,
SD_REQUEST.END_DATE_UT
) AS 'Close Date',
SD_REQUEST.RFC_number AS 'Ticket',
agent.LAST_NAME AS 'Agent',
AM_DOMAIN.NAME_EN AS 'Company',
EE.LAST_NAME AS 'Recipient',
RR.LAST_NAME AS 'Requestor',
catpath.SD_CATALOG_PATH_EN
FROM
SD_REQUEST
LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID
LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID
LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID
LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID
LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID
WHERE
agent.LAST_NAME = 'insert name here'
AND CONVERT (
datetime,
SD_REQUEST.END_DATE_UT,
101
) BETWEEN (Getdate() - 8)
AND (Getdate() - 2)
ORDER BY
NEWID()
I'm assuming you're using SQL Server based on syntax in question. You can use the ROW_NUMBER() function inside a cte/subquery to generate a number for each row, using PARTITION BY you can have the numbering start over for each member of a given set/group, in this case agent.LAST_NAME, you can use that number to limit to two results per set/group:
;with cte AS (
SELECT CONVERT (DATE,SD_REQUEST.END_DATE_UT) AS 'Close Date',
SD_REQUEST.RFC_number AS 'Ticket',
agent.LAST_NAME AS 'Agent',
AM_DOMAIN.NAME_EN AS 'Company',
EE.LAST_NAME AS 'Recipient',
RR.LAST_NAME AS 'Requestor',
catpath.SD_CATALOG_PATH_EN,
ROW_NUMBER() OVER(PARTITION BY agent.LAST_NAME ORDER BY NEWID()) AS RN
FROM
SD_REQUEST
LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID
LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID
LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID
LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID
LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID
WHERE CONVERT (datetime,SD_REQUEST.END_DATE_UT,101) BETWEEN (Getdate() - 8) AND (Getdate() - 2)
)
SELECT *
FROM cte
WHERE RN <= 2

how to insert random records without violating primary constraint

Please pardon my title if misleading, but I have a table tb_party with PRIMARY KEY on party_key
I have following query -
insert TMS..tb_party
(
[party_key]
,[party_first_name]
,[tax_id]
,[party_type_cd]
,[citizenship_country_cd]
,[domicile_country_cd]
,[party_num]
,[batch_dt]
)
select distinct
[party_key]
,[party_first_name]
,[tax_id]
,[party_type_cd]
,[cit]
,[dom]
,[party_num]
,[batch_dt]
from
(select distinct
sca.[party_key]
,sca.[party_first_name]
,sca.[tax_id]
,pt.party_type_cd
,tc_cit.COUNTRY_ID as cit
,tc_dom.COUNTRY_ID as dom
,sca.[party_num]
,getdate() as batch_dt
,dense_rank() over(partition by sca.[party_key] order by sca.party_key) as rnk
from Iteration_3.dbo.staging_cust_acct sca (nolock)
join Iteration_3..STG_PARTY_UPLOAD (nolock) stg_party
on sca.party_key = stg_party.PARTY_KEY
left join Iteration_3..STG_COUNTRY_ISO tc_dom (nolock)
on sca.[domicile_country] = tc_dom.COUNTRY_NAME
left join Iteration_3..STG_COUNTRY_ISO tc_cit (nolock)
on sca.[citizenship_country] = tc_cit.COUNTRY_NAME
left join TMS..tb_party_type pt (nolock)
on sca.[party_type] = pt.party_type_desc
WHERE
SCA.party_type IS NOT NULL
) x
where rnk = 1
The insert fails because it is trying to insert duplicate party key and since the distinct is on ALL columns, it is picking up duplicate party_keys.
What I want - I want to pick up all distinct party_keys and insert 1 row in tb_party. the other rows can be ignored. Is this possible?
Here is where row_number came in handy.
select distinct
[party_key]
,[party_first_name]
,[tax_id]
,[party_type_cd]
,[cit]
,[dom]
,[party_num]
,[batch_dt]
from
(
select distinct
sca.[party_key]
,sca.[party_first_name]
,sca.[tax_id]
,pt.party_type_cd
,tc_cit.COUNTRY_ID as cit
,tc_dom.COUNTRY_ID as dom
,sca.[party_num]
,getdate() as batch_dt
--,dense_rank() over(partition by sca.[party_key] order by sca.party_key,sca.[tax_id],sca.[party_num],sca.[party_first_name]*/) as rnk
,row_number() over (partition by sca.party_key order by sca.party_key) rn
from Iteration_3.dbo.staging_cust_acct sca (nolock)
join Iteration_3..STG_PARTY_UPLOAD (nolock) stg_party
on sca.party_key = stg_party.PARTY_KEY
left join Iteration_3..STG_COUNTRY_ISO tc_dom (nolock)
on sca.[domicile_country] = tc_dom.COUNTRY_NAME
left join Iteration_3..STG_COUNTRY_ISO tc_cit (nolock)
on sca.[citizenship_country] = tc_cit.COUNTRY_NAME
left join TMS..tb_party_type pt (nolock)
on sca.[party_type] = pt.party_type_desc
WHERE --SCA.update_source = 'ECM' AND SCA.update_dt = #ECM_MAX_DATE
--and
SCA.party_type IS NOT NULL
) x
where rn = 1
Try merging into your target table on the unique columns. When not matched, insert. When matched update like this:
...
set target.[column] = coalesce(source.[column], target.[column])
...
This way you update all your target columns when you have source values, otherwise they remain unchanged.)

SQL INNER JOIN DISTINCT with max function

I have the tables tbMeasurement and tbPatientMeasurement .
tbMeasurement
MeasurementIDP
MeasurementName
tbPatientMeasurement
PatientMeasurementIDP
MeasurementIDF
MeasurementValue
Taken (Datetime)
When doing the following query:
SELECT DISTINCT dbo.tbMeasurement.MeasurementName
, dbo.tbPatientMeasurement.MeasurementValue
, dbo.tbPatientMeasurement.Taken
FROM dbo.tbMeasurement
INNER JOIN dbo.tbPatientMeasurement
ON dbo.tbMeasurement.MeasurementIDP = dbo.tbPatientMeasurement.MeasurementIDF
This returns a double entry of one of the MeasurementName.
and i also want MeasurementName,MeasurementValue by max Taken(datetime).
Try this one -
SELECT DISTINCT
m.MeasurementName
, p2.MeasurementValue
, p2.Taken
FROM dbo.tbMeasurement m
JOIN (
SELECT
p.MeasurementValue
, Taken = MAX(p.Taken)
FROM dbo.tbPatientMeasurement p
GROUP BY m.MeasurementName, p.MeasurementValue
) p2 ON m.MeasurementIDP = p2.MeasurementIDF
SELECT
m.MeasurementName
, p.MeasurementValue
, a.Taken
FROM dbo.tbMeasurement m
INNER JOIN dbo.tbPatientMeasurement p ON m.MeasurementIDP = p.MeasurementIDF
INNER JOIN
(
select MeasurementIDF,MAX(Taken) as taken
from tbPatientMeasurement
group by MeasurementIDF
) a on a.MeasurementIDF=p.MeasurementIDF and a.taken=p.Taken