SQL Query based on ROW_Number not working - sql

Basically I am trying to do a query to a page that holds just an image. I need to provide the tripID number and then the ROWID (as there could be multiple images) to receive a single image. I will be looping until each image is in its corresponding image box in html.
This code doesn't seem to work(I get Invalid column name 'ROWID'), but if I remove the AND ROWID='1' it returns all the images and its row id like this:
ROWID PHOTO
1 32jjr3h2jh23hj4h32jh42ll23j42
2 HU8308DJAOID9ASIDJI32C89EE29
-
Select ROW_NUMBER() OVER (ORDER BY Photo ASC) AS ROWID, TBL_Photo.Photo
From TBL_Photo
left join TBL_TripDetails
ON TBL_Photo.TripID=TBL_TripDetails.pkiTripID
Where pkiTripID = '121' AND ROWID = '1'

You can't reference a column alias in the WHERE clause -- you need to use a subquery or a CTE:
Subquery Example:
SELECT x.rowid,
x.photo
FROM (SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID,
p.photo
FROM TBL_PHOTO p
LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid
WHERE td.pkiTripID = '121') x
WHERE x.rowid = 1
CTE example:
WITH example AS (
SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID,
p.photo
FROM TBL_PHOTO p
LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid
WHERE td.pkiTripID = '121')
SELECT x.rowid,
x.photo
FROM example x
WHERE x.rowid = 1
Performance
There's no performance difference between the two options, but the WITH syntax isn't supported on all databases.

Related

SQL SERVER make a row data to column

I'm currently making a program to store data in database sql server.
and the data is a cost that divided into max 5 column cost details.
As for the first row it labeled with 1 and second with 2, up to 5 row with same id.
So i'm making the table like the picture below. And Now i want to select the table from row to column like in the picture.
i'm making the query like this. I get the result like i want, but the problem is that the query cost like 5/more times the execution plan by just selecting the same table.
My question is, is there a way to make the result like in the picture just by selecting once the table or is there any other way to make like the result with better performance, i hear of using pivot for transposing row to column, but in my case i don't know how to do it. Thanks for reply
this is the execution plan https://www.brentozar.com/pastetheplan/?id=SJGJdaCB7
AND this is the query i used
select * FROM TblKecelakaanBiaya;
with tbl AS (
select *, ROW_NUMBER() OVER(PARTITION by id_kasus ORDER BY id_kasus) rn FROM TblKecelakaanBiaya
)
SELECT A.id_kasus, A.ket_biaya1, A.jlh_biaya1, C.ket_biaya2, C.jlh_biaya2,
D.ket_biaya3, D.jlh_biaya3, E.ket_biaya4, E.jlh_biaya4, F.ket_biaya5, F.jlh_biaya5
FROM (SELECT id_kasus, ket_biaya ket_biaya1, jlh_biaya jlh_biaya1 FROM tbl WHERE rn = 1) A
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya2, jlh_biaya jlh_biaya2 FROM tbl WHERE rn = 2) C ON A.id_kasus = C.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya3, jlh_biaya jlh_biaya3 FROM tbl WHERE rn = 3) D ON A.id_kasus = D.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya4, jlh_biaya jlh_biaya4 FROM tbl WHERE rn = 4) E ON A.id_kasus = E.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya5, jlh_biaya jlh_biaya5 FROM tbl WHERE rn = 5) F ON A.id_kasus = F.id_kasus
The execution plan for query 1 is just 1% and the other one is 99%.
Perhaps a Pivot inconcert with a Cross Apply.
Example
Select *
From (
Select id_kasus,item,value
From (Select * ,RN = Row_Number() over (Partition By id_kasus Order By id_kasus) From TblKecekakaanBiaya ) A
Cross Apply (values (concat('jih_biaya',RN),convert(varchar(150),jih_biaya))
,(concat('ket_biaya',RN),ket_biaya)
) b(item,value)
) src
Pivot (max(value) for item in ([ket_biaya1],[jih_biaya1],[ket_biaya2],[jih_biaya2],[ket_biaya3],[jih_biaya3],[ket_biaya4],[jih_biaya4],[ket_biaya5],[jih_biaya5]) ) pvt
Returns

I need more than a row PostgreSQL

I need a PostgreSQL subquery that can return more than a row. Here's the piece of the query that I have so far:
select (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500]
FROM "Image"
LEFT JOIN "Product_Image"
ON "Image".id = "Product_Image".image_id
WHERE "Product_Image".product_id = 517
ORDER BY "Product_Image".sort ASC) as images
Put the subquery in the FROM clause?
select vals
from (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500] as vals
FROM "Image" LEFT JOIN
"Product_Image"
ON "Image".id = "Product_Image".image_id
WHERE "Product_Image".product_id = 517
) images

SQL Correlation error using OVER & PARTITION in SELECT statement

I am getting the following error when I am trying to execute my SQL SELECT statement
Could not execute statement.
Correllation name 'contact' not found
SQLCODE=-142, ODBC 3 State"42S02"
Line 1, Column 1
My code is as follows
Select forename, surname, email, quotedate
From ( SELECT *, ROW_NUMBER() OVER (PARTITION BY tblQuote.contno ORDER BY quoteno DESC) AS rn
FROM dba.quotehdr as tblQuote left join dba.contact as tblContact on tblQuote.contno = tblContact.contno)q
where rn = 1 and quotedate <=today()-720 and emailbounced = 0 and email is not null and dba.contact.statusflag = 'A'
order by quotedate desc
This error only happended when I added in
dba.contact.statusflag = 'A'
I have tried this as
tblContact.statusflag = 'A'
and I get the same error!
Any suggestions?
(What about q.statusflag = 'A' , as it seems you are using q as an Alias.) This original answer is not correct, amended to:
#Shannon Severance is correct in his comment. You are trying to use the Where clause on the outer query - which does not contain any fields from the contact table. Let me tidy your query to help you see your subquery (q) - as:
Select
forename
,surname
,email
, quotedate
From
(
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY tblQuote.contno ORDER BY quoteno DESC) AS rn
FROM dba.quotehdr as tblQuote
left join dba.contact as tblContact on tblQuote.contno = tblContact.contno
) q
left join dba.contact as tblContact on q.contno = tblContact.contno
where rn = 1
and quotedate <=today()-720
and emailbounced = 0
and email is not null
and tblContact.statusflag = 'A' -- Now sourced from last left join
order by quotedate desc
You will need another LEFT JOIN on the dba.contact table to be able to access this field (ADDED NOW as an example).
Also, depending on your database engine - if your field is duplicated in both tables, the SELECT * in a subquery may eject those fields, or rename them, or throw an error. Run your inner subquery by itself and see what it produces, or use explicit field name instead of *
(I still really think your * in the subquery is causing the error and also the confusion. Remove it and replace with table.field names - this will help you understand what is going wrong ...Otherwise your query logic is pretty fine, and adding the extra left join that I suggest is overkill)

How to increment a column based on two tables that are joined

I am trying to increment a column on a sql server table based on the join between the initial table and the joined table. The idea is to update tblForm10Objectives, set the ObjectiveNumber column to an increment number starting with 1 based on the number of rows returned from the join of tblForm10GoalsObjectives and tblForm10Objectives where ID_Form10Goal equals a number. Example query so far:
Update tblForm10Objectives
Set ObjectiveNumber = rn
From (
Select ROW_NUMBER() over (PARTITION by OG.ID_Form10Goal) as rn
, *
From (
Select *
From tblForm10GoalsObjectives OG
Join tblForm10Objectives O On OG.ID_Form10Objective = O.ID_Form10Objective
Where OG.ID_Form10Goal = 4
Order by O.ID_Form10Objective
) as tblForm10Objectives;
If the select portion of the query is performed the columns are displayed so you can see the ObjectiveNumber is currently 0 where ID_Form10Goal = 4
Once the update runs I need for the ObjectiveNumber to show 1 , 2; since there are two rows for ID_Form10Goal = 4.
I had to introduce a new table to the logic of this update statement, the table name is tblForm10Goals. The objectives need to be pulled by ID_Agency instead of ID_Form10Goal I am getting an error message stating a "a multipart identifier 'dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective' could not be bound. I am using the following SQL Update statement:
UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM tblForm10Goals As g
Left Join tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
Right Join
(
SELECT
ROW_NUMBER() OVER (PARTITION BY g.ID_Agency
ORDER BY OB.ID_Form10Objective) AS rn,
OB.ID_Form10Objective
FROM tblForm10Goals g
LEFT JOIN dbo.tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
RIGHT JOIN dbo.tblForm10Objectives OB ON gobs.ID_Form10Objective = OB.ID_Form10Objective
Where g.ID_Agency = 2
) rns ON dbo.tblForm10Objectives.ID_Form10Object = rns.ID_Form10Objective
Your example seems to be missing a closing parenthesis somewhere, and without the table structures to look at, I can't be certain of my answer. It seems you have two tables:
tblForm10Objectives
-------------------
ID_Form10Objective
ObjectiveNumber
...
and
tblForm10GoalsObjectives
------------------------
ID_Form10Goal
ID_Form10Objective
...
If this is the case, the following query should give you the results you desire:
UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM dbo.tblForm10Objectives INNER JOIN
(
SELECT
ROW_NUMBER() OVER (PARTITION BY OG.ID_Form10Goal
ORDER BY O.ID_Form10Objective) AS rn,
O.ID_Form10Objective
FROM dbo.tblForm10Objectives O INNER JOIN
dbo.tblForm10GoalsObjectives OG ON OG.ID_Form10Objective = O.ID_Form10Objective
Where OG.ID_Form10Goal = 4
) rns ON dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective
If you run the inner SELECT statement, you will see the desired ObjectiveNumber values and the corresponding ID_Form10Objective that will get updated with those values.
If you post your table structures, I or someone else may be able to be of more help.

Limit join to one row

I have the following query:
SELECT sum((select count(*) as itemCount) * "SalesOrderItems"."price") as amount, 'rma' as
"creditType", "Clients"."company" as "client", "Clients".id as "ClientId", "Rmas".*
FROM "Rmas" JOIN "EsnsRmas" on("EsnsRmas"."RmaId" = "Rmas"."id")
JOIN "Esns" on ("Esns".id = "EsnsRmas"."EsnId")
JOIN "EsnsSalesOrderItems" on("EsnsSalesOrderItems"."EsnId" = "Esns"."id" )
JOIN "SalesOrderItems" on("SalesOrderItems"."id" = "EsnsSalesOrderItems"."SalesOrderItemId")
JOIN "Clients" on("Clients"."id" = "Rmas"."ClientId" )
WHERE "Rmas"."credited"=false AND "Rmas"."verifyStatus" IS NOT null
GROUP BY "Clients".id, "Rmas".id;
The problem is that the table "EsnsSalesOrderItems" can have the same EsnId in different entries. I want to restrict the query to only pull the last entry in "EsnsSalesOrderItems" that has the same "EsnId".
By "last" entry I mean the following:
The one that appears last in the table "EsnsSalesOrderItems". So for example if "EsnsSalesOrderItems" has two entries with "EsnId" = 6 and "createdAt" = '2012-06-19' and '2012-07-19' respectively it should only give me the entry from '2012-07-19'.
SELECT (count(*) * sum(s."price")) AS amount
, 'rma' AS "creditType"
, c."company" AS "client"
, c.id AS "ClientId"
, r.*
FROM "Rmas" r
JOIN "EsnsRmas" er ON er."RmaId" = r."id"
JOIN "Esns" e ON e.id = er."EsnId"
JOIN (
SELECT DISTINCT ON ("EsnId") *
FROM "EsnsSalesOrderItems"
ORDER BY "EsnId", "createdAt" DESC
) es ON es."EsnId" = e."id"
JOIN "SalesOrderItems" s ON s."id" = es."SalesOrderItemId"
JOIN "Clients" c ON c."id" = r."ClientId"
WHERE r."credited" = FALSE
AND r."verifyStatus" IS NOT NULL
GROUP BY c.id, r.id;
Your query in the question has an illegal aggregate over another aggregate:
sum((select count(*) as itemCount) * "SalesOrderItems"."price") as amount
Simplified and converted to legal syntax:
(count(*) * sum(s."price")) AS amount
But do you really want to multiply with the count per group?
I retrieve the the single row per group in "EsnsSalesOrderItems" with DISTINCT ON. Detailed explanation:
Select first row in each GROUP BY group?
I also added table aliases and formatting to make the query easier to parse for human eyes. If you could avoid camel case you could get rid of all the double quotes clouding the view.
Something like:
join (
select "EsnId",
row_number() over (partition by "EsnId" order by "createdAt" desc) as rn
from "EsnsSalesOrderItems"
) t ON t."EsnId" = "Esns"."id" and rn = 1
this will select the latest "EsnId" from "EsnsSalesOrderItems" based on the column creation_date. As you didn't post the structure of your tables, I had to "invent" a column name. You can use any column that allows you to define an order on the rows that suits you.
But remember the concept of the "last row" is only valid if you specifiy an order or the rows. A table as such is not ordered, nor is the result of a query unless you specify an order by
Necromancing because the answers are outdated.
Take advantage of the LATERAL keyword introduced in PG 9.3
left | right | inner JOIN LATERAL
I'll explain with an example:
Assuming you have a table "Contacts".
Now contacts have organisational units.
They can have one OU at a point in time, but N OUs at N points in time.
Now, if you have to query contacts and OU in a time period (not a reporting date, but a date range), you could N-fold increase the record count if you just did a left join.
So, to display the OU, you need to just join the first OU for each contact (where what shall be first is an arbitrary criterion - when taking the last value, for example, that is just another way of saying the first value when sorted by descending date order).
In SQL-server, you would use cross-apply (or rather OUTER APPLY since we need a left join), which will invoke a table-valued function on each row it has to join.
SELECT * FROM T_Contacts
--LEFT JOIN T_MAP_Contacts_Ref_OrganisationalUnit ON MAP_CTCOU_CT_UID = T_Contacts.CT_UID AND MAP_CTCOU_SoftDeleteStatus = 1
--WHERE T_MAP_Contacts_Ref_OrganisationalUnit.MAP_CTCOU_UID IS NULL -- 989
-- CROSS APPLY -- = INNER JOIN
OUTER APPLY -- = LEFT JOIN
(
SELECT TOP 1
--MAP_CTCOU_UID
MAP_CTCOU_CT_UID
,MAP_CTCOU_COU_UID
,MAP_CTCOU_DateFrom
,MAP_CTCOU_DateTo
FROM T_MAP_Contacts_Ref_OrganisationalUnit
WHERE MAP_CTCOU_SoftDeleteStatus = 1
AND MAP_CTCOU_CT_UID = T_Contacts.CT_UID
/*
AND
(
(#in_DateFrom <= T_MAP_Contacts_Ref_OrganisationalUnit.MAP_KTKOE_DateTo)
AND
(#in_DateTo >= T_MAP_Contacts_Ref_OrganisationalUnit.MAP_KTKOE_DateFrom)
)
*/
ORDER BY MAP_CTCOU_DateFrom
) AS FirstOE
In PostgreSQL, starting from version 9.3, you can do that, too - just use the LATERAL keyword to achieve the same:
SELECT * FROM T_Contacts
--LEFT JOIN T_MAP_Contacts_Ref_OrganisationalUnit ON MAP_CTCOU_CT_UID = T_Contacts.CT_UID AND MAP_CTCOU_SoftDeleteStatus = 1
--WHERE T_MAP_Contacts_Ref_OrganisationalUnit.MAP_CTCOU_UID IS NULL -- 989
LEFT JOIN LATERAL
(
SELECT
--MAP_CTCOU_UID
MAP_CTCOU_CT_UID
,MAP_CTCOU_COU_UID
,MAP_CTCOU_DateFrom
,MAP_CTCOU_DateTo
FROM T_MAP_Contacts_Ref_OrganisationalUnit
WHERE MAP_CTCOU_SoftDeleteStatus = 1
AND MAP_CTCOU_CT_UID = T_Contacts.CT_UID
/*
AND
(
(__in_DateFrom <= T_MAP_Contacts_Ref_OrganisationalUnit.MAP_KTKOE_DateTo)
AND
(__in_DateTo >= T_MAP_Contacts_Ref_OrganisationalUnit.MAP_KTKOE_DateFrom)
)
*/
ORDER BY MAP_CTCOU_DateFrom
LIMIT 1
) AS FirstOE
Try using a subquery in your ON clause. An abstract example:
SELECT
*
FROM table1
JOIN table2 ON table2.id = (
SELECT id FROM table2 WHERE table2.table1_id = table1.id LIMIT 1
)
WHERE
...