Row-Number in Between Sub Query - tsql

select
row_number() over (order by BookTitle) AS Row,
BookTitleID,
BookTitle,
CallNumber,
FullName,
count(case Status when 'OnShelf' then 1 else null end) AS CopiesOnShelves
from
(
select
Book.BookTitleID,
BookTitles.BookTitle,
BookTitles.CallNumber,
Book.Status,
FullName = LastName + ', ' + FirstName + ' ' + MiddleName
From
Book
left outer join
BookTitles
on BookTitles.BookTitleID = Book.BookTitleID
left outer join
Authors
on Authors.AuthorID = BookTitles.AuthorID ) sub
Where Row between 1 and 10 -- not working
Group By Callnumber, BookTitle, BookTitleID, FullName
How I will use In between ROW in this on example to display Row 1 to Row 10.

select * from(
select
Row,
BookTitleID,
BookTitle,
CallNumber,
FullName,
CopiesOnShelves
from
(
select
Book.BookTitleID,
BookTitles.BookTitle,
BookTitles.CallNumber,
FullName = LastName + ', ' + FirstName + ' ' + MiddleName,
CopiesOnShelves = count(case Status when 'OnShelf' then 1 else null end),
Row = row_number() over (order by BookTitle)
From
Book
left outer join
BookTitles
on BookTitles.BookTitleID = Book.BookTitleID
left outer join
Authors
on Authors.AuthorID = BookTitles.AuthorID
Group By Book.BookTitleID, BookTitles.BookTitle, BookTitles.CallNumber,
LastName, FirstName, MiddleName
) sub
) sub2
WHERE Row between #start and #end

Your row_Number function needs to be in the subquery. You cannot reference a row_number column in the where clause of the query where it is declared. You can from the outer query though. Just one of those weird TSQL rules. I wan't sure if you really wanted the row in the select results or not so I threw it in there anyway.
select
Row,
BookTitleID,
BookTitle,
CallNumber,
FullName,
count(case Status when 'OnShelf' then 1 else null end) AS CopiesOnShelves
from
(
select
Book.BookTitleID,
BookTitles.BookTitle,
BookTitles.CallNumber,
Book.Status,
FullName = LastName + ', ' + FirstName + ' ' + MiddleName,
row_number() over (order by BookTitle) AS Row
From
Book
left outer join
BookTitles
on BookTitles.BookTitleID = Book.BookTitleID
left outer join
Authors
on Authors.AuthorID = BookTitles.AuthorID ) sub
Where Row between 1 and 10 -- not working
Group By Callnumber, BookTitle, BookTitleID, FullName, Row

Related

If the object we made by the group is null, I want to give [ ] instead postgresql

with
zakaz as (
select
o.*,
(select f_name from clients where id = o.client_id) as f_name,
(select l_name from clients where id = o.client_id) as l_name,
(select phone from clients where id = o.client_id) as phone,
(select name from item_types where id = o.item_type_id) as item_name,
(select name from trailer_types where id = o.trailer_type_id) as trailer_name,
(select name from cover_types where id = o.cover_type_id) as cover_name,
(select name from cities where id = o.from_city_id) as from_city,
(select name from cities where id = o.to_city_id) as to_city,
(select name from transport_types where id = o.transport_type_id) as transport_type,
(select first_name || ' ' || last_name || ' ' || middle_name as name from workers where id = o.logist_id) as logist_name
from orders as o
where o.transport_type_id = (select id from transport_types where name = $tt$${transport_type}$tt$)
${ where_key ? `and ${where_key} = $v$${where_val}$v$` : ``}
order by o.created_at
),
zakaz_j_agg as (
select
COALESCE(json_agg(zakaz.*), '[]') as array
from zakaz
group by zakaz.status
)
select
json_agg(ord.*) as result
from zakaz_j_agg as ord
Replace json_agg(ord.*) as result with coalesce(json_agg(ord.*), '[]') as result. The same pattern is used in the zakaz_j_agg CTE.
with
zakaz as (... your CTE query ...),
zakaz_j_agg as (... your CTE query ...)
select
coalesce(json_agg(ord.*), '[]') as result
from zakaz_j_agg as ord;

Getting pyspark.sql.utils.ParseException: missing ')' at 'in' in pyspark sql

Hi I am running below query on pyspark sql but getting error. Please help me where I am missing ')'.
Query -
`with cte1 as (select `Project Number`, indication,rank() over (partition by `Project Number`,REGEXP_REPLACE(indication,'[^a-zA-Z0-9]+', '') order by `Project Number`,indication) as rnk from (select distinct `Project Number`, indication from vw_onco_pharma onco_pharma union select distinct `Project Number`, indication from vw_onco_cell_gene cell_gene union select distinct `Project Number`, indication from vw_non_onco_cell_gene onco_cell_gene union select distinct `Project Number`, indication from vw_non_onco_pharma non_onco_pharma union select distinct `Project Number`, indication from vw_plasma_protein plasma_protein)),y as (select max(cast(project_id as integer)) as max_prj_id from vw_project_id) select nvl(max_prj_id,0)+ROW_NUMBER () OVER (ORDER BY `Project Number`,indication) as project_id,`Project Number`,indication,date_format(current_timestamp(),'yyyy-MM-dd hh:mm:ss') as HTA_INSERT_DT from (select cte1.`Project Number`, cte1.indication,max_prj_id from cte1 left join vw_project_id prj on cte1.`Project Number` = prj.`Project Number` and REGEXP_REPLACE(cte1.indicatio,'[^a-zA-Z0-9]+', '') = REGEXP_REPLACE(prj.indication,'[^a-zA-Z0-9]+', '') left join y on 1 = 1 where rnk = 1 and prj.project_id is null and cte1.`project number` in (select `project number` from cte1 group by `project number` having count(*) > 1) union select cte1.`Project Number`, null as indication,max_prj_id from cte1 left join vw_project_id prj on cte1.`Project Number` = prj.`Project Number` left join y on 1 = 1 where rnk = 1 and prj.project_id is null and cte1.`project number` in (select `project number` from cte1 groupby `project number` having count(*) = 1))`
Error-
pyspark.sql.utils.ParseException:
missing ')' at 'in'(line 1, pos 1575)
The last groupby should be group by.
Also try formatting your query, so it can be readable:
with cte1 as (
select
` Project Number `,
indication,
rank() over (
partition by ` Project Number `,
REGEXP_REPLACE(indication, '[^a-zA-Z0-9]+', '')
order by
` Project Number `,
indication
) as rnk
from
(
select
distinct ` Project Number `,
indication
from
vw_onco_pharma onco_pharma
union
select
distinct ` Project Number `,
indication
from
vw_onco_cell_gene cell_gene
union
select
distinct ` Project Number `,
indication
from
vw_non_onco_cell_gene onco_cell_gene
union
select
distinct ` Project Number `,
indication
from
vw_non_onco_pharma non_onco_pharma
union
select
distinct ` Project Number `,
indication
from
vw_plasma_protein plasma_protein
)
),
y as (
select
max(cast(project_id as integer)) as max_prj_id
from
vw_project_id
)
select
nvl(max_prj_id, 0) + ROW_NUMBER () OVER (
ORDER BY
` Project Number `,
indication
) as project_id,
` Project Number `,
indication,
date_format(current_timestamp(), 'yyyy-MM-dd hh:mm:ss') as HTA_INSERT_DT
from
(
select
cte1.` Project Number `,
cte1.indication,
max_prj_id
from
cte1
left join vw_project_id prj on cte1.` Project Number ` = prj.` Project Number `
and REGEXP_REPLACE(cte1.indicatio, '[^a-zA-Z0-9]+', '') = REGEXP_REPLACE(prj.indication, '[^a-zA-Z0-9]+', '')
left join y on 1 = 1
where
rnk = 1
and prj.project_id is null
and cte1.` project number ` in (
select
` project number `
from
cte1
group by
` project number `
having
count(*) > 1
)
union
select
cte1.` Project Number `,
null as indication,
max_prj_id
from
cte1
left join vw_project_id prj on cte1.` Project Number ` = prj.` Project Number `
left join y on 1 = 1
where
rnk = 1
and prj.project_id is null
and cte1.` project number ` in (
select
` project number `
from
cte1 group by ` project number `
having
count(*) = 1
)
)

how to replace duplicated subquery?

I got a query
SELECT name AS name,
count(group_name) AS all_test_cases,
(SELECT count(*) FROM test_cases AS tc2 WHERE tc2.group_name = tg.name AND status = 'OK' ) AS passed_test_cases,
tg.test_value * (SELECT count(*) FROM test_cases AS tc2 WHERE tc2.group_name = name AND status = 'OK') AS total_value
FROM test_groups AS tg
LEFT JOIN test_cases AS tc
ON tg.name = tc.group_name
GROUP BY name, test_value
ORDER BY total_value DESC, name ASC
How I can replace duplicated subquery:
tg.test_value * (SELECT count(*) FROM test_cases AS tc2 WHERE tc2.group_name = name AND status = 'OK') AS total_value
with something more efficient in postgres without stored procedure?
Does this work for you?
with cte_test_cases as (
SELECT group_name,
count(*) filter (where status = 'OK') as passed_test_cases,
count(*) as all_test_cases
FROM test_cases
GROUP BY group_name
)
SELECT tg.name,
tc.all_test_cases,
tc.passed_test_cases,
tg.test_value * tc.passed_test_cases AS total_value
FROM test_groups AS tg
LEFT JOIN cte_test_cases AS tc
ON tg.name = tc.group_name
ORDER BY total_value DESC, name ASC

Postgres substring error

I am receiving an error when creating a view converted from code at website http://pratchev.blogspot.com/2007/02/passing-variable-to-in-list.html. ERROR: function pg_catalog.substring(text,bigint,integer) does not exist; #7. Appreciate your help.
Code:
WITH recursive Hierarchy(ChildId, SubRepInitials, ParentId, Parents, steps)
AS
(
SELECT salesforceid, salesforceinitials, parentid, CAST('' AS TEXT), 0 as steps
FROM tblbulksalesforce AS FirstGeneration
WHERE parentid IS NULL AND salesforceinitials IS NOT NULL
UNION ALL
SELECT NextGeneration.salesforceid, NextGeneration.salesforceinitials, Parent.ChildId,
CAST(CASE WHEN Parent.Parents = ''
THEN(CAST(NextGeneration.parentid AS TEXT) || ',')
ELSE(Parent.Parents || CAST(NextGeneration.parentid AS TEXT) || ',')
END AS TEXT), Parent.steps +1 as steps
FROM tblbulksalesforce AS NextGeneration
INNER JOIN Hierarchy AS Parent ON NextGeneration.parentid = Parent.ChildId
WHERE NextGeneration.salesforceinitials IS NOT NULL
)
SELECT ISNULL(h.ParentId,h.ChildId) AS ParentId, h.ChildId
, h.SubRepInitials, h.Parents, steps
,Generation0.salesforceinitials AS RepInitials
,parent.salesforceinitials AS RepInitialsParent
FROM Hierarchy AS h
LEFT JOIN tblbulksalesforce AS parent ON parent.RecordID = h.ParentId
LEFT JOIN tblbulksalesforce AS Generation0 ON Generation0.RecordID IN (
(SELECT SUBSTRING(string, 2, strpos(',', string, 2) - 2)
FROM (SELECT SUBSTRING(list, n, character_length(list))
FROM (SELECT ',' || h.Parents || ',') AS L(list),
(SELECT ROW_NUMBER() OVER (ORDER BY parentid)
FROM Hierarchy) AS Nums(n)
WHERE n <= character_length(list)) AS D(string)
WHERE character_length(string) > 1 AND SUBSTRING(string, 1, 1) = ',')
) OR Generation0.RecordID = h.ChildId;
Please see Postgres docs for how to use strpos() and substr(). Note that substring() is a completely different function with a different format for its arguments.
Try this:
WITH recursive Hierarchy(ChildId, SubRepInitials, ParentId, Parents, steps)
AS
(
SELECT salesforceid, salesforceinitials, parentid, CAST('' AS TEXT), 0 as steps
FROM tblbulksalesforce AS FirstGeneration
WHERE parentid IS NULL AND salesforceinitials IS NOT NULL
UNION ALL
SELECT NextGeneration.salesforceid, NextGeneration.salesforceinitials, Parent.ChildId,
CAST(CASE WHEN Parent.Parents = ''
THEN(CAST(NextGeneration.parentid AS TEXT) || ',')
ELSE(Parent.Parents || CAST(NextGeneration.parentid AS TEXT) || ',')
END AS TEXT), Parent.steps +1 as steps
FROM tblbulksalesforce AS NextGeneration
INNER JOIN Hierarchy AS Parent ON NextGeneration.parentid = Parent.ChildId
WHERE NextGeneration.salesforceinitials IS NOT NULL
)
SELECT ISNULL(h.ParentId,h.ChildId) AS ParentId, h.ChildId
, h.SubRepInitials, h.Parents, steps
,Generation0.salesforceinitials AS RepInitials
,parent.salesforceinitials AS RepInitialsParent
FROM Hierarchy AS h
LEFT JOIN tblbulksalesforce AS parent ON parent.RecordID = h.ParentId
LEFT JOIN tblbulksalesforce AS Generation0 ON Generation0.RecordID IN (
(SELECT SUBSTR(string, 2, strpos(',', string) - 2) -- you had a 2 sitting in strpos(',', string, 2) before. I'm not sure what you were trying to do with that.
FROM (SELECT SUBSTR(list, n, character_length(list))
FROM (SELECT ',' || h.Parents || ',') AS L(list),
(SELECT ROW_NUMBER() OVER (ORDER BY parentid)
FROM Hierarchy) AS Nums(n)
WHERE n <= character_length(list)) AS D(string)
WHERE character_length(string) > 1 AND SUBSTR(string, 1, 1) = ',')
) OR Generation0.RecordID = h.ChildId;

How to pull out the employees who have 'first name,lastname and date of birth' as same from Employee table

I need to pull out the records whose First name,lastname and date of birth are of same.
Please find the below example.
Employeeid firstname lastname DOB
00010 ravi sagi 22/01/1990
00035 ravi sagi 22/01/1990
00060 vasanth guptha 20/01/1987
00115 vasanth guptha 20/01/1987
Can you please help in writing the query.
Try this:
select *
from
(
select *,
count(*) over(partition by firstname, lastname, DOB) as CC
from YourTable
) as T
where T.CC > 1
You can JOIN the table to itself comparing the firstname, lastname and DOB to make sure they are the same value and then that the employeeid is not the same:
select *
from yourtable t1
inner join yourtable t2
on t1.firstname = t2.firstname
and t1.lastname = t2.lastname
and t1.dob = t2.dob
and t1.empid != t2.empid
the above query could display duplicate records, so you could use the following (see SQL Fiddle with Demo):
select DISTINCT t1.empid,
t1.firstname,
t1.lastname,
t1.DOB
from yourtable t1
inner join yourtable t2
on t1.firstname = t2.firstname
and t1.lastname = t2.lastname
and t1.dob = t2.dob
and t1.empid != t2.empid
Or you can use EXISTS (See SQL Fiddle with Demo):
select t1.empid,
t1.firstname,
t1.lastname,
t1.DOB
from yourtable t1
where exists (SELECT *
FROM yourtable t2
WHERE t1.firstname = t2.firstname
and t1.lastname = t2.lastname
and t1.dob = t2.dob
and t1.empid != t2.empid)