How can I select bottom row from second table using inner join in SQL Server 2000? - sql-server-2000

How can I select bottom row from second table using inner join from two tables?
Here [customer records] contains customer details and photoinfo contains photodetails.
SELECT
CR.customernumber, CR.customername,
CR.Addressline1, CR.city, CR.state,
CR.pincode, CR.landline, CR.mobile,
CR.dob, CR.gender,
PR.FileName, CR.remarks, CR.fulladdress, CR.regno,
CR.qualification, CR.bg, CR.fname,
CR.field1, CR.field2, CR.field3, CR.field4, CR.field5,
CR.sign
from
[customer records] CR
inner join
photoinfo PR on PR.customernumber = CR.customernumber
where
CR.customernumber >= 5050 and CR.customernumber <= 5100
order by
CR.customernumber
Here filename is text field from photoinfo. i need to select every last row of filename from photoinfo
Thanks in advance
Customer records
cnumber cname Mobile Gender
2000 K.Deepalakshmi F
2001 J.Geetha 9789426497 F
photoinfo
cid cnumber Filename
5152 2000 B6216.jpg
5153 2001 B6203.jpg
5154 2001 B6209.jpg
5155 2001 B6205.jpg
here i want join the above two tables based on cnumber(customernumber). and i want join last or the first filename from photoinfo based on cid like.
expected output
cnumber cname filename Mobile Gender
2000 K.Deepalakshmi B6216.jpg F
2001 J.Geetha B6205.jpg 9789426497 F

Create & insert Customer table
create table #customer(cnumber decimal(18,0),cname varchar(100),Mobile varchar(100),Gender varchar(1))
insert into #customer values
(2000,'K.Deepalakshmi','','F'),
(2001,'J.Geetha','9789426497','F')
Create & Insert Photo info table
create table #photoinfo(cid decimal(18,0),cnumber decimal(18,0),filename varchar(100))
insert into #photoinfo values
(5152,2000,'B6216.jpg'),
(5153,2001,'B6203.jpg'),
(5154,2001,'B6209.jpg'),
(5155,2001,'B6205.jpg')
Result
select c.cnumber,c.cname,p.filename,c.Mobile,c.Gender
from #customer c
join #photoinfo p on p.cnumber=c.cnumber
join (select c.cnumber,max(p.cid) cid
from #customer c
join #photoinfo p on p.cnumber=c.cnumber
group by c.cnumber) r on r.cnumber=p.cnumber and p.cid=r.cid

Related

SQL can not refer table in from clause within where

I have a simple SQL query used in oracle 11g
select something
from sc
where sc.column satisfies something
but I can not refer SC in the where composite, any one can help explain this, thanks in advance.
---second edit: I tested the sql command in oracle 19c it works but in 11g it does not work.
table contents
create table sc(
sno varchar2(10),
cno varchar2(10),
score number(4,2),
constraint pk_sc primary key (sno,cno)
);
example data
insert into sc values ('s001','c001',78.9);
insert into sc values ('s002','c001',80.9);
insert into sc values ('s003','c001',81.9);
insert into sc values ('s004','c001',60.9);
insert into sc values ('s001','c002',82.9);
insert into sc values ('s002','c002',72.9);
insert into sc values ('s003','c002',81.9);
insert into sc values ('s001','c003','59');
sql command
SELECT SNO
FROM SC A
WHERE 0 = (SELECT COUNT(*)
FROM
(SELECT B.CNO
FROM SC B
WHERE B.SNO = 's001'
MINUS
SELECT C.CNO
FROM SC C
WHERE A.SNO = C.SNO) --this is the error location, oracle reports invalid identifier A.
);
I would try a exists clause instead of where 0 =
SELECT SNO
FROM SC A
WHERE not exists (SELECT B.CNO
FROM SC B
WHERE B.SNO = 's001'
MINUS
SELECT C.CNO
FROM SC C
WHERE A.SNO = C.SNO) --this is the error location, oracle reports undefined A.
I'm assuming you want to return where there is not a match?
If you're trying to get the CNO that are not only in SNO 's001'.
Then maybe this.
SELECT DISTINCT SNO, cno
FROM SC sc
WHERE SNO = 's001'
AND EXISTS (
SELECT 1
FROM SC sc2
WHERE sc2.CNO = sc.CNO
AND sc2.SNO != sc.SNO
)

Use Data of 1 table into another one dynamically

I have one table category_code having data like
SELECT Item, Code, Prefix from category_codes
Item Code Prefix
Bangles BL BL
Chains CH CH
Ear rings ER ER
Sets Set ST
Rings RING RG
Yellow GOld YG YG........
I have another table item_categories having data like
select code,name from item_categories
code name
AQ.TM.PN AQ.TM.PN
BL.YG.CH.ME.PN BL.YG.CH.ME.PN
BS.CZ.ST.YG.PN BS.CZ.ST.YG.PN
CR.YG CR.YG.......
i want to update item_categories.name column corresponding to category_code.item column like
code name
BL.YG.CH.ME.PN Bangles.Yellow Gold.Chains.. . . .
Please suggest good solution for that. Thanks in advance.
First, split the code into several rows, join with the category code and then, concat the result to update the table.
Here an example, based on the data you gave
create table #category_code (item varchar(max), code varchar(max), prefix varchar(max));
create table #item_categories (code varchar(max), name varchar(max));
insert into #category_code (item, code, prefix) values ('Bangles','BL','BL'),('Chains','CH','CH'),('Ear rings','ER','ER'), ('Sets','Set','ST'),('Rings','RING','RG'), ('Yellow gold','YG','YG');
insert into #item_categories (code, name) values ('AQ.TM,PN','AQ.TM.PN'),('BL.YG.CH.ME.PN','BL.YG.CH.ME.PN'),('BS.CZ.ST.YG.PN','BS.CZ.ST.YG.PN')
;with splitted as ( -- split the codes into individual code
select row_number() over (partition by ic.code order by ic.code) as id, ic.code, x.value, cc.item
from #item_categories ic
outer apply string_split(ic.code, '.') x -- SQL Server 2016+, otherwise, use another method to split the data
left join #category_code cc on cc.code = x.value -- some values are missing in you example, but can use an inner join
)
, joined as ( -- then joined them to concat the name
select id, convert(varchar(max),code) as code, convert(varchar(max),coalesce(item + ',','')) as Item
from splitted
where id = 1
union all
select s.id, convert(varchar(max), s.code), convert(varchar(max), j.item + coalesce(s.item + ',',''))
from splitted s
inner join joined j on j.id = s.id - 1 and j.code = s.code
)
update #item_categories
set name = substring (j.item ,1,case when len(j.item) > 1 then len(j.item)-1 else 0 end)
output deleted.name, inserted.name
from #item_categories i
inner join joined j on j.code = i.code
inner join (select code, max(id)maxid from joined group by code) mj on mj.code = j.code and mj.maxid = j.id

SQL - Updating rows in one table with values from another table - Multiple match

I am trying to append values in my Customer table with data from my Sales table.
The customer can have multiple records in the sales table:
Hereby a joined view:
SalesID CustomerID SalesComment CustomerComment
------------------------------------------------------------
1 14 Com1 Customer Comment 1
2 15 Com2 Customer Comment 2
3 14 Com3 Customer Comment 1
4 14 Customer Comment 1
I want to make an update like this:
UPDATE Customer
SET Customer.ShopBookKommentar = CAST([ShopBookKommentar] AS NVARCHAR(MAX)) +
CAST(CHAR(13) + CHAR(10) + S.Comments AS NVARCHAR(MAX))
FROM Customer C
INNER JOIN Sales S ON S.CustomerID = c.ID
But it's not updating any of the Customer rows where one of the Sales rows comment field is empty ('')
It looks like you are using SQL Server. You need to use the table alias for the update:
UPDATE c
SET ShopBookKommentar = c.ShopBookKommentar + CHAR(13) + CHAR(10) + S.Comments
FROM Costumer C INNER JOIN
Sales S
ON S.CostumerID = c.ID;
You only need the cast() if for some reason the intermediate result isn't big enough. But that shouldn't be a problem.
EDIT:
I am guessing that you actually want to apply multiple comments from different rows of Sales. That is a bit trickier:
UPDATE c
SET ShopBookKommentar = c.ShopBookKommentar + c.somm
FROM (SELECT c.*,
(SELECT CHAR(13) + CHAR(10) + S.Comments
FROM Sales s
WHERE S.CostumerID = c.ID AND
S.Comments IS NOT NULL
FOR XML PATH, TYPE
).value(N'.[1]', N'varchar(max)') as scomm
FROM c
) Costumer C INNER JOIN
(Sales S
ON ;

Need assistance with SQL query

I have 3 tables that I'm trying to create a query from:
Table 1 (iuieEmployee) ->position number
Table 2 (jbEmployeeH1BInfo) -> position number, LCA number, start date
Table 3 (jbEmployeeLCA) -> LCA number
Table 4 (jbInternationsl) -> Main demographic table
I have a query that works fine where there's only 1 record in each table, but tables 2 and 3 can have multiple records. I want it to find the record with he most recent start date and verify that there is a matching LCA number in the 3rd table and a matching position number int he first table and show me any records where this isn't the case. How can I accomplish this? I currently have:
SELECT DISTINCT jbInternational.idnumber, jbInternational.lastname, jbInternational.firstname, jbInternational.midname,
jbInternational.campus, jbInternational.universityid, jbInternational.sevisid, jbInternational.citizenship,
jbInternational.immigrationstatus, jbEmployeeH1BInfo.lcaNumber AS lcaNumber1, jbEmployeeLCA.lcaNumber AS lcaNumber2
FROM (select jbEmployeeH1BInfo.idnumber, MAX(jbEmployeeH1BInfo.approvalStartDate) AS MaxDateStamp FROM [internationalservices].[dbo].jbEmployeeH1BInfo GROUP BY idnumber ) my
INNER JOIN [internationalservices].[dbo].jbEmployeeH1BInfo WITH (nolock) ON my.idnumber=jbEmployeeH1BInfo.idnumber AND my.MaxDateStamp=jbEmployeeH1BInfo.approvalStartDate
INNER JOIN [internationalservices].[dbo].jbInternational WITH (nolock) ON jbInternational.idnumber=jbEmployeeH1BInfo.idnumber
inner join [internationalservices].[dbo].jbEmployeeLCA ON jbInternational.idnumber = jbEmployeeLCA.idnumber
WHERE jbInternational.idnumber not in(
SELECT DISTINCT jbInternational.idnumber
FROM (select distinct jbEmployeeH1BInfo.idnumber, MAX(jbEmployeeH1BInfo.approvalStartDate) AS MaxDateStamp
FROM [internationalservices].[dbo].jbEmployeeH1BInfo GROUP BY idnumber ) my
INNER JOIN [internationalservices].[dbo].jbEmployeeH1BInfo WITH (nolock) ON my.idnumber=jbEmployeeH1BInfo.idnumber AND my.MaxDateStamp=jbEmployeeH1BInfo.approvalStartDate
INNER JOIN [internationalservices].[dbo].jbInternational WITH (nolock) ON jbInternational.idnumber=jbEmployeeH1BInfo.idnumber
inner join [internationalservices].[dbo].jbEmployeeLCA ON jbInternational.idnumber = jbEmployeeLCA.idnumber
AND jbEmployeeH1BInfo.lcaNumber = jbEmployeeLCA.lcaNumber)
Table Schema:
create table iuieEmployee(idnumber int, POS_NBR varchar(8));
insert into iuieEmployee values(123456, '470V13');
insert into iuieEmployee values(123457, '98X000');
insert into iuieEmployee values(123458, '98X000');
insert into iuieEmployee values(123455, '98X000');
create table jbEmployeeH1BInfo (idnumber int, approvalStartDate smalldatetime, lcaNumber varchar(20), positionNumber varchar(200));
insert into jbEmployeeH1BInfo values (123456, 07/01/2012, '1-200-3000', '98X000');
insert into jbEmployeeH1BInfo values (123456, 07/30/2013, '1-200-4000', '470V13');
insert into jbEmployeeH1BInfo values (123457, 07/01/2012, '1-200-5000', '98X000');
insert into jbEmployeeH1BInfo values (123458, 07/01/2012, '1-200-6000', '98X000');
insert into jbEmployeeH1BInfo values (123455, 07/30/2014, '1-200-7000', '98X000');
insert into jbEmployeeH1BInfo values (123455, 07/01/2012, '1-200-8000', '470V13');
create table jbEmployeeLCA (idnumber int, lcaNumber varchar(20));
insert into jbEmployeeLCA values (123456, 1-200-3000);
insert into jbEmployeeLCA values (123456, 1-200-4111);
insert into jbEmployeeLCA values (123457, 1-200-5000);
insert into jbEmployeeLCA values (123458, 1-200-6000);
insert into jbEmployeeLCA values (123455, 1-200-7000);
insert into jbEmployeeLCA values (123455, 1-200-8000);
create table jbInternational(idnumber int);
insert into jbInternational values(123456);
insert into jbInternational values(123457);
insert into jbInternational values(123458);
insert into jbInternational values(123455);
Should only return 1 line:
123456, 07/30/2013, '1-200-4000'
but is instead returning two lines:
123456, 07/30/2013, '1-200-4000 (not matching 1-200-4111)
123456, 07/30/2013, '1-200-4000 (not matching 1-200-3000)
It shouldn't return the second row because the position number with the -3000 lca number doesn't have the most current date.
Your explanation is hard to understand. I guess if you could explain it well, then you could probably write the query yourself. Here's what I think you meant:
Employee contains the main records.
You want to find all idnumbers such that
idnumber is in International
the H1BInfo record with the most recent approvalStartDate does not have an LCA number matching the LCA record
The first thing to do is to simplify that H1BInfo table. We are only looking for the rows with the most recent approvalStartDate. We can do that by partitioning by idnumber and ordering by approvalStartDate:
with rankedH1BInfo as (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY jbEmployeeH1BInfo.idnumber
ORDER BY jbEmployeeH1BInfo.approvalStartDate desc) as r
FROM [internationalservices].[dbo].jbEmployeeH1BInfo
)
Let's only get the first row of each partition:
, MostRecentH1BInfo as (
SELECT * FROM rankedH1BInfo
WHERE r = 1
)
Now we can do the join to find all the good ones:
, goodIDs as (
SELECT i.idnumber
FROM [internationalservices].[dbo].jbInternational i WITH (NOLOCK)
JOIN [internationalservices].[dbo].jbEmployeeLCA l WITH (NOLOCK) on l.idnumber = i.idnumber
JOIN MostRecentH1BInfo h WITH (NOLOCK) on h.idnumber = i.idnumber
JOIN iuieEmployee e WITH (NOLOCK) on e.positionNumber = h.positionNumber
WHERE h.lcaNumber = l.lcaNumber
)
To put it all together and get the ones where this is false:
with rankedH1BInfo as (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY jbEmployeeH1BInfo.idnumber
ORDER BY jbEmployeeH1BInfo.approvalStartDate desc) as r
FROM [internationalservices].[dbo].jbEmployeeH1BInfo
), MostRecentH1BInfo as (
SELECT * FROM rankedH1BInfo
WHERE r = 1
), goodIDs as (
SELECT i.idnumber
FROM [internationalservices].[dbo].jbInternational i WITH (NOLOCK)
JOIN [internationalservices].[dbo].jbEmployeeLCA l WITH (NOLOCK) on l.idnumber = i.idnumber
JOIN MostRecentH1BInfo h WITH (NOLOCK) on h.idnumber = i.idnumber
JOIN iuieEmployee e WITH (NOLOCK) on e.positionNumber = h.positionNumber
WHERE h.lcaNumber = l.lcaNumber
)
SELECT DISTINCT jbInternational.idnumber, jbInternational.lastname, jbInternational.firstname, jbInternational.midname,
jbInternational.campus, jbInternational.universityid, jbInternational.sevisid, jbInternational.citizenship,
jbInternational.immigrationstatus, jbEmployeeH1BInfo.lcaNumber AS lcaNumber1, jbEmployeeLCA.lcaNumber AS lcaNumber2
FROM (select jbEmployeeH1BInfo.idnumber, MAX(jbEmployeeH1BInfo.approvalStartDate) AS MaxDateStamp FROM [internationalservices].[dbo].jbEmployeeH1BInfo GROUP BY idnumber ) my
INNER JOIN [internationalservices].[dbo].jbEmployeeH1BInfo WITH (nolock) ON my.idnumber=jbEmployeeH1BInfo.idnumber AND my.MaxDateStamp=jbEmployeeH1BInfo.approvalStartDate
INNER JOIN [internationalservices].[dbo].jbInternational WITH (nolock) ON jbInternational.idnumber=jbEmployeeH1BInfo.idnumber
inner join [internationalservices].[dbo].jbEmployeeLCA ON jbInternational.idnumber = jbEmployeeLCA.idnumber
WHERE jbInternational.idnumber not in (select idnumber from goodIDs)

sql using select and adding to a table

SELECT `pro`.`St`, `s`.`Quantity`
FROM `s`
LEFT JOIN `web`.`pro` ON `s`.`Pro_id` = `pro`.`ProdID`
the above query results in a table like
st quantity
132 1
11 1
st is from one table and quantity is from another
using this select statement I want to add the resulting quantity to the st row in the other table.
Basically updating the second table by adding the quantity i get from this select statement.
UPDATE `web`.`pro`
SET `pro`.`st` = `pro`.`st` + `s`.`Quantity`
FROM `web`.`pro`
JOIN `shopping cart` `s`
ON `s`.`Pro_id` = `pro`.`ProdID`;
Something like that ?