SQL how to cross reference two unrelated tables - sql

I need to cross reference from these 2 tables and display only the matching contindex from the first table if the contindex from the other table matches. Below is an image of what i have. Also the code is pasted below.
select t.ContIndex, t.clientcode, t.debttranname as ClientName, DebtDetService,
case when DebtTranType = 3 then 'Invoice' else 'Credit Memo' end as Type, d.amount,
REPLACE(REPLACE(REPLACE(CAST(FeeNarrative As varchar(max)),
CHAR(10) + CHAR(13), ' '), CHAR(10), ' '), CHAR(13), ' ') as Narrative
from tblTranDebtorDetail d
inner join tbltrandebtor t on t.DebtTranIndex=d.DebtTranIndex
where DebtTranDate > 'jan 1 2015' and t.debttrantype in (3,6)
and DebtDetService = 'abr reimb'
select w.contindex /*, ClientCode, ClientName, Job_Name,
case when TransTypeIndex=1 then 'Time' else 'Exp' end as Type, sum(wipamount)*/
from tblTranWIP w
inner join tblJob_Header h on h.job_idx=w.ServPeriod and h.ContIndex=w.ContIndex
inner join tblengagement e on e.ContIndex=w.ContIndex
inner join tblstaff s on s.StaffIndex=w.StaffIndex
where wipoutstanding <>0 and h.Job_Template in (99,100) and TransTypeIndex in (1,2)
--group by w.contindex, ClientCode, ClientName, Job_Name, TransTypeIndex
Basically I need to show only the top table rows that match the bottom table contindex.

Sounds like the tables are related by contindex, no? Anyhow, copy and pasting your code and adding just a little bit extra should do the trick:
select t.ContIndex, t.clientcode, t.debttranname as ClientName, DebtDetService,
case when DebtTranType = 3 then 'Invoice' else 'Credit Memo' end as Type, d.amount,
REPLACE(REPLACE(REPLACE(CAST(FeeNarrative As varchar(max)),
CHAR(10) + CHAR(13), ' '), CHAR(10), ' '), CHAR(13), ' ') as Narrative
from tblTranDebtorDetail d
inner join tbltrandebtor t on t.DebtTranIndex=d.DebtTranIndex
where DebtTranDate > 'jan 1 2015' and t.debttrantype in (3,6)
and DebtDetService = 'abr reimb'
and t.ContIndex IN
(
select w.contindex /*, ClientCode, ClientName, Job_Name,
case when TransTypeIndex=1 then 'Time' else 'Exp' end as Type, sum(wipamount)*/
from tblTranWIP w
inner join tblJob_Header h on h.job_idx=w.ServPeriod and h.ContIndex=w.ContIndex
inner join tblengagement e on e.ContIndex=w.ContIndex
inner join tblstaff s on s.StaffIndex=w.StaffIndex
where wipoutstanding <>0 and h.Job_Template in (99,100) and TransTypeIndex in (1,2)
--group by w.contindex, ClientCode, ClientName, Job_Name, TransTypeIndex
)
The additional code is the WHERE t.contindex IN (<yoursecondquery>) You could accomplish the same thing with an INNER JOIN too, but this is a quick-fix given that you already wrote out both queries seperately.

You can use an IN or EXISTS here.. You just need to alter the second query slightly to add a WHERE condition if you use EXISTS.
SELECT
t.ContIndex,
t.clientcode,
t.debttranname AS ClientName,
DebtDetService,
CASE WHEN DebtTranType = 3 THEN 'Invoice'
ELSE 'Credit Memo'
END AS Type,
d.amount,
REPLACE(REPLACE(REPLACE(CAST(FeeNarrative AS VARCHAR(MAX)),CHAR(10) + CHAR(13),' '),CHAR(10),' '),CHAR(13),' ') AS Narrative
FROM
tblTranDebtorDetail d
INNER JOIN tbltrandebtor t ON t.DebtTranIndex = d.DebtTranIndex
WHERE
DebtTranDate > 'jan 1 2015'
AND t.debttrantype IN (3,6)
AND DebtDetService = 'abr reimb'
AND EXISTS ( SELECT
w.contindex
FROM
tblTranWIP w
INNER JOIN tblJob_Header h ON h.job_idx = w.ServPeriod
AND h.ContIndex = w.ContIndex
INNER JOIN tblengagement e ON e.ContIndex = w.ContIndex
INNER JOIN tblstaff s ON s.StaffIndex = w.StaffIndex
WHERE
t.ContIndex = w.contindex -- new where clause
AND wipoutstanding <> 0
AND h.Job_Template IN (99,100)
AND TransTypeIndex IN (1,2) )

Related

How to write one CASE function two THEN method at the same time END AS Two NEW column depend on THEN action

SELECT Emp.IntegrationFieldOne AS LocationCode, Emp.EmployeeId,
Emp.FirstName + ' '+ Emp.LastName as 'EmployeeName',
CASE WHEN ( (ORSet.Rate) =1.5 ) THEN
Sum(OT.Minutes)
END AS '1.5HRSMinutes',
CASE WHEN( ORSet.Rate =2 ) THEN
Sum(OT.Minutes)
END AS '2HRSMinutes'
FROM [CemexDB_CP_Test].[TimeAttendance].[OvertimeTransaction] OT
INNER JOIN [HumanResource].[Employee] Emp ON OT.EmployeeId = Emp.EmployeeId
INNER JOIN [CemexDB_CP_Test].[TimeAttendance].[OvertimeRateSettingDetail]
ORSet ON ORSet.OvertimeRateSettingId= OT.OvertimeType
GROUP BY Emp.EmployeeId,Emp.FirstName,Emp.LastName,Emp.IntegrationFieldOne,ORSet.Rate[!
This is Output picture click it]1
This is the out put but i want same row depend same id. but here each id has 2
row how to handle it
I think you want conditional aggregation:
SELECT Emp.IntegrationFieldOne AS LocationCode, Emp.EmployeeId,
Emp.FirstName + ' '+ Emp.LastName as EmployeeName,
SUM(CASE WHEN ORSet.Rate = 1.5 THEN OT.Minutes END) AS [1.5HRSMinutes],
SUM(CASE WHEN ORSet.Rate = 2 THEN OT.Minutes END) AS [2HRSMinutes]
FROM [CemexDB_CP_Test].[TimeAttendance].[OvertimeTransaction] OT INNER JOIN
[HumanResource].[Employee] Emp
ON OT.EmployeeId = Emp.EmployeeId INNER JOIN
[CemexDB_CP_Test].[TimeAttendance].[OvertimeRateSettingDetail]
ORSet
ON ORSet.OvertimeRateSettingId= OT.OvertimeType
GROUP BY Emp.EmployeeId, Emp.FirstName, Emp.LastName, Emp.IntegrationFieldOne;

Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int

I have a query that is getting some that is comparing a uniqueidentifier in the table and its a strange one.
SELECT * FROM vw_ryzex_CustomerAssets where BillToId='51ee47d2-eb97-4b12-8865-dab9a7f15a46'
So when i run this query i get the following error
Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int.
But when i select only the top 1000 i get the result and no error occurrs I tried Casting and converting checking nulls everything i could i tried following queries but did not work
SELECT * FROM vw_ryzex_CustomerAssets_V2 where CAST(BillToId as nvarchar(200))=Cast('51ee47d2-eb97-4b12-8865-dab9a7f15a46' as nvarchar(200))
SELECT * FROM vw_ryzex_CustomerAssets where (Case BillToId
when '00000000-0000-0000-0000-000000000000' Then NEWID()
ELSE BillToId
END) = '51ee47d2-eb97-4b12-8865-dab9a7f15a46'
Can anyone help me on this please..?
This is the view definition
ALTER VIEW [dbo].[vw_ryzex_CustomerAssets_V2] AS SELECT a.Id,
'~/Reports/BillToAssetDetails.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS URL,
'~/Reports/BillToAssets.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS EditUrl,
LEFT(a.PartDescription, 50) AS PartDescription,-- EKL:03042009
a.Quantity,
a.SerialNumber,
/* CASE ISNULL(s.Name,'') WHEN '' THEN a.Location ELSE s.Name + '(' + s.ErpId + ')
'+ a.Location END AS Location, */
a.Location,
s.NAME + '(' + s.ErpId + ')' AS SiteName,
--a.OrderId,
o.OrderGroupId AS OrderId,
a.OrderErpId,
a.OrderExt,
a.OrderLine,
a.DateCreated,
a.DateModified,
Isnull(ru.DisplayName, '') AS ModifiedBy,
a.BillToId,
a.PartNo,
b.NAME AS BillToName,
b.Description AS BillToDescription,
b.ErpId AS BillToErpId,
b.DateCreated AS BillToDateCreated,
b.DateModified AS BillToDateModified,
b.ModifiedBy AS BillToModifiedBy,
a.ProductId,
--p.ProductPartNo,
--p.ProductModel,
--p.ProductDescription as ProductDescription,
--p.ProductDateCreated,
--p.ProductDateModified,
--p.ProductModifiedBy,
Isnull(ol.UnitPrice, '0') AS UnitPrice,
ol.SalesTax,
Isnull(ol.TotalPrice, '0') AS TotalPrice,
ol.OrderErpId AS OrderLineId,
Isnull(ol.QuantityOrdered, '0') AS QuantityOrdered,
Isnull(ol.QuantityShipped, '0') AS QuantityShipped,
-- o.Created AS OrderDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.Created) AS OrderDate,
-- o.ShippedDate AS ShipDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.ShippedDate) AS ShipDate,
o.SalesPersonName AS SalesPersonDisplayName,
o.BillingCurrency AS Currency,
dbo.vw_PurchaseOrderPayments.PurchaseOrderPaymentNumber AS CustPo,
a.AssetNumber,
a.CustomerReference,
a.ModelNumber,
a.CustomField1Value AS xCust1,
a.CustomField2Value AS xCust2,
s.Id AS ShipToId,
s.AddressLine1 AS Address1,
s.AddressLine2 AS Address2,
s.AddressLine3 AS Address3,
s.City,
s.Country,
s.[State],
s.ZipCode AS Zip
FROM dbo.vw_PurchaseOrderPayments
RIGHT OUTER JOIN dbo.vw_PurchaseOrders AS o
ON dbo.vw_PurchaseOrderPayments.OrderFormId = o.OrderFormId -- EKL:03042009 chg from OrderGroupId to OrderFormId
RIGHT OUTER JOIN dbo.ryzex_CustomerAsset AS a
INNER JOIN dbo.ryzex_BillTo AS b WITH (NOLOCK)
ON a.BillToId = b.Id
AND Isnull(a.Inactive, 0) = 0
LEFT OUTER JOIN dbo.ryzex_ShipTo AS s WITH (NOLOCK)
ON a.ShipToId = s.Id
AND b.Id = s.BillToId
LEFT OUTER JOIN dbo.ryzex_Product AS p WITH (NOLOCK)
ON a.PartNo = p.ProductPartNo
LEFT OUTER JOIN dbo.vw_OrderLines AS ol
ON a.OrderErpId = ol.OrderErpId
AND a.OrderLine = ol.LineNumber
ON o.OrderErpNumber = a.OrderErpId
AND o.OrderExtensionNumber = a.OrderExt
LEFT OUTER JOIN dbo.ryzex_Users AS ru WITH (NOLOCK)
ON a.ModifiedBy = ru.Id
The BillToId that is coming from ryzex_CustomerAsset tbl is a not null uniqueidentifier

WHERE Clause with conditions in it

I want to create a where clause that will take into account the termination date and say if they hire date is between these values and the term date isn't on or before the hiredate - IE the employee never started - how would I go about that? So far I have this:
SELECT A.AdpID AS EmployeeID,
ISNULL(A.Lname, '') AS [Last Name],
ISNULL(A.Fname, '') AS [First Name],
ISNULL(A.PrimaryEmail, '') AS [Email],
ISNULL(M.Fname + ' ' + M.Lname, '') AS Manager,
ISNULL(CONVERT(VARCHAR(100), A.HireDate, 101), '') AS HireDate,
ISNULL(CONVERT(VARCHAR(100), A.TerminationDate, 101), '') AS TermDate,
ISNULL(DIV.DivisionName, '') AS Division,
ISNULL(FUN.FunctionName, '') AS [Function],
ISNULL(DEP.DepartmentName, '') AS Department,
ISNULL(WGP.WorkgroupName, '') AS Workgroup,
ISNULL(LOB.CcaLOBName, '') AS LOB,
ISNULL(MAES.EmpStatusDesc, '') AS [Employee Type]
FROM dbo.Associates AS A
LEFT OUTER JOIN dbo.Associates AS M -- Look up for associate information
ON A.SuperPrincipal = M.AssocId
LEFT OUTER JOIN dbo.MasterCCALob AS LOB -- Look up line of business
ON A.LobID = LOB.CcaLOBID
LEFT OUTER JOIN dbo.MasterAssocEmpStatus AS MAES -- Look up for employee type
ON A.EmpStatusID = MAES.EmpStatusID
LEFT OUTER JOIN dbo.AssociatesDepartment AS DEP WITH(NOLOCK) -- Look up for Department
ON A.AssociatesDepartmentID = DEP.AssociatesDepartmentID
LEFT OUTER JOIN dbo.AssociatesDivision AS DIV WITH(NOLOCK) -- Look up for Division
ON A.AssociatesDivisionID = DIV.AssociatesDivisionID
LEFT OUTER JOIN dbo.AssociatesWorkGroup AS WGP WITH(NOLOCK) -- Look up for WorkGroup
ON A.AssociatesWorkgroupID = WGP.AssociatesWorkgroupID
LEFT OUTER JOIN dbo.AssociatesFunction AS FUN WITH(NOLOCK) -- Look up for Function
ON A.AssociatesFunctionID = FUN.AssociatesFunctionID
WHERE ( LEN(A.TerminationDate) = 0
AND ISNULL(A.HireDate, '1900-01-01') BETWEEN '2015-10-01' AND GETDATE() )
OR ( LEN(A.TerminationDate) > 0
AND ISNULL(A.TerminationDate, '1900-01-01') > ISNULL(A.HireDate, '1900-01-01')
AND ISNULL(A.HireDate, '1900-01-01') BETWEEN '2015-10-01' AND GETDATE() )
ORDER BY A.HireDate DESC
There where clause is as bad as can be because I get the craziest results back from this

how to limit row number to one unique row in SQL query?

I need to limit the row number to one unique row in SQL query. Here's sample data to recognize what I'm talking about:
john doe 3000 fog horn drive , ky 40444
john doe 3001 merry lane , ky 40484
I want to return the first one in the list here's my query :
Select
DISTINCT p.personID, e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade, i.gender, p.studentNumber, e.citizenship, e.adult, i.birthdate,
e.disability1, e.disability2, ad.city, e.displacedHomemaker, e.homeSchooled,
e.localStudentNumber, e.migrant, e.modifiedDate, e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid, i.lastname, i.firstname, i.middlename, i.ssn,
ad.phone, ad.state, ad.zip, ad.addressLine1
FROM
Person p
LEFT join
Enrollment e ON e.personID = p.personID And isnull(e.noshow, 0) = 0
LEFT join
EnrollmentKY ky ON ky.enrollmentID = e.enrollmentID
LEFT join
[Identity] i ON i.identityID = p.currentIdentityID And i.personID = p.personID
INNER join
Calendar c ON c.calendarID = e.calendarID
INNER join
SchoolYear sy ON sy.endYear = c.endYear AND sy.active = 1
JOIN
staffMember Staff ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join
v_MailingAddress ad ON ad.personID = i.personID And ad.relatedBy = 'household'
And ad.endDate IS NULL And isnull(ad.secondary, 0) = 0
order by
i.lastname, i.firstname, i.middlename
edit: need to only pick first row in SQL code because I have a problem with people that have multiple addresses it puts two rows for them and i only need first row of data for the person that has multiple addresses.
If the personId is distinct for each of the records and they just have a different address, then you can add a field for the row_number() and then only select the records where the row_number = 1:
select *
from
(
Select p.personID,
e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade,
i.gender,
p.studentNumber,
e.citizenship,
e.adult,
i.birthdate,
e.disability1,
e.disability2,
ad.city,
e.displacedHomemaker,
e.homeSchooled,
e.localStudentNumber,
e.migrant,
e.modifiedDate,
e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid,
i.lastname,
i.firstname,
i.middlename,
i.ssn,
ad.phone,
ad.state,
ad.zip,
ad.addressLine1,
row_number() over(partition by p.personid order by p.personid) rn -- add this field
FROM Person p
LEFT join Enrollment e
ON e.personID = p.personID
And isnull(e.noshow,0)=0
LEFT join EnrollmentKY ky
ON ky.enrollmentID = e.enrollmentID
LEFT join [Identity] i
ON i.identityID = p.currentIdentityID
And i.personID = p.personID
INNER join Calendar c
ON c.calendarID = e.calendarID
INNER join SchoolYear sy
ON sy.endYear = c.endYear
AND sy.active = 1
JOIN staffMember Staff
ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join v_MailingAddress ad
ON ad.personID = i.personID
And ad.relatedBy = 'household'
And ad.endDate IS NULL
And isnull(ad.secondary,0)=0
) x
where x.rn = 1
order by x.lastname, x.firstname, x.middlename
Try using the LIMIT to limit the no. of outputs.
Eg:
SELECT COLUMN_NAME
FROM TABLE
ORDER BY CONDITION
LIMIT NO_OF_ROWS;
Have you tried using a "GROUP BY" clause instead of the DISTINCT keyword?
Also, what about a Sub-Query? If I were writing this type of thing I'd use a sproc and create a temporary table.
Edit: Deleted original answer as question was changed and original answer is not the way to go with changed question.
Suggest GROUP BY clause per Neil Hoskins.

Single Line separated records in SQL SERVER Query result

I had a query that returned multiple rows from a table. Then I converted that query to this one:
;with mycte as
(select s.FirstName + ' ' + s.LastName as Name from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join GeneralStatus gs on gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active')
select #staff = (select distinct staff = REPLACE(REPLACE(REPLACE((select Name AS [data()] FROM mycte a
order by a.Name for xml path),'</row><row>',', '),'</row>',''),'<row>','') from mycte b)
It returns those rows in a single comma-separated row.
Now I don't want comma-separated values, instead I want single-line-separated values.
Can anyone tell me if it is possible or not?
Thanks in advance.
declare #staff varchar(max)
;with mycte as
(
select distinct s.FirstName + ' ' + s.LastName as Name
from ClientStaff cs
left outer join Staff s on
s.Id = cs.StaffId
left outer join GeneralStatus gs on
gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active'
)
select #staff = isnull(#staff + char(13), '') + Name
from mycte b
print #staff