Continuous Different Errors [closed] - sql

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem β€” and include valid code to reproduce it β€” in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have edited the SQL to use DISTINCT however I am still getting the same data as when I use GROUP BY. Any suggestions?
When I use GROUP BY it requires that all the fields in the select clause are included, can anyone tell me why that is?
Any help is greatly appreciated.
SELECT DISTINCT
TrnClaim.ClientID
, TrnClaim.FileNo
, TrnLegend.RecordNo
, RTRIM(dbo.TrnClient.ClientName + ' ' + ISNULL(dbo.TrnClient.Initials,'') + ' ' + (CASE WHEN dbo.TrnClient.LanguageCode = 'A' THEN ISNULL(dbo.TrnClient.Title, 'Mr') ELSE ISNULL(dbo.TrnClient.Title,'')END)) AS NameInitials
, TrnClient.IDNumber
, ISNULL(dbo.MstInsurer.InsurerName, 'Unknown') AS InsurerName
, CAST(dbo.TrnPolicy.AgentID AS VARCHAR(10)) + ' ' + ISNULL(CAST(dbo.MstAgent.AgentName AS VARCHAR(50)),'Unknown') AS AgentIDName
, CAST(dbo.TrnPolicy.TeamID AS VARCHAR(10)) + ' ' + ISNULL(dbo.VieTeamSelect.TeamName, 'Unknown') AS TeamIDName
, CAST(dbo.TrnPolicy.LinkID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstLink.LinkName, 'Unknown') AS LinkIDName
, CAST(dbo.TrnPolicy.SubagentID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstSubagent.SubagentName, 'Unknown') AS SubagentIDName
, CAST(dbo.TrnPolicy.MarketerID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstMarketerCodes.MarketerName, 'Unknown') AS MarketerIDName
, dbo.TrnRisk.RiskID
, dbo.TrnRisk.Registration
, dbo.TrnRisk.VehID
, dbo.TrnRisk.VinNo
, dbo.TrnRisk.VehMake
, dbo.TrnRisk.VehMake
, dbo.TrnRisk.VehModel
, dbo.TrnRisk.VehModel
, dbo.TrnExt.ExtStartDate
, dbo.TrnExt.ExtEndDate
, dbo.MstRateCodes.RateCodeID
, dbo.TrnExt.ExtDesc
, dbo.TrnPolicy.Status AS PolicyStatus
, dbo.TrnPolicy.PayMeth
, dbo.TrnPolicy.PolicyPeriod
, 1 AS [Count]
, dbo.TrnPolicy.TotalPrem AS LastMonthPremium
--, LastPolicy.TotalDue AS LastMonthTotalDue
, dbo.TrnPolicy.TeamID
, dbo.TrnPolicy.AgentID
, dbo.TrnPolicy.LinkID
, ISNULL(dbo.TrnPolicy.LeadInsurerID,MstInsurer.InsurerID) AS InsurerIDForFilter
, dbo.TrnLegend.LegendDescr
, dbo.TrnLegend.ActiveDate
FROM dbo.TrnClaim
INNER JOIN dbo.TrnPolicy ON
TrnClaim.ClientID = dbo.TrnPolicy.ClientID
AND
TrnClaim.FileNo = dbo.TrnPolicy.FileNo
INNER JOIN dbo.TrnClient ON
dbo.TrnPolicy.ClientID = dbo.TrnClient.ClientID
INNER JOIN dbo.TrnRisk ON
dbo.TrnPolicy.ClientID = dbo.TrnRisk.ClientID
AND
dbo.TrnPolicy.FileNo = dbo.TrnRisk.FileNo
INNER JOIN dbo.TrnExt ON
dbo.TrnRisk.ClientID = dbo.TrnExt.ClientID
AND
dbo.TrnRisk.FileNo = dbo.TrnExt.FileNo
LEFT OUTER JOIN dbo.MstRateCodes ON
dbo.MstRateCodes.RateCodeID = dbo.TrnExt.ExtCode
LEFT OUTER JOIN dbo.MstInsurer MstInsurerLead ON
dbo.TrnPolicy.LeadInsurerID = MstInsurerLead.InsurerID
LEFT OUTER JOIN dbo.TrnPolicy LastPolicy ON
dbo.TrnPolicy.ClientID = LastPolicy.ClientID
AND
dbo.TrnPolicy.FileNo = LastPolicy.FileNo
LEFT OUTER JOIN dbo.MstAgent ON
dbo.TrnPolicy.AgentID = dbo.MstAgent.AgentID
LEFT OUTER JOIN dbo.MstSubagent ON
dbo.TrnPolicy.SubagentID = dbo.MstSubagent.SubagentID
LEFT OUTER JOIN dbo.MstMarketerCodes ON
dbo.TrnPolicy.MarketerID = dbo.MstMarketerCodes.MarketerID
LEFT OUTER JOIN dbo.VieTeamSelect ON
dbo.TrnPolicy.TeamID = dbo.VieTeamSelect.TeamID
LEFT OUTER JOIN dbo.MstLink ON
dbo.TrnPolicy.LinkID = dbo.MstLink.LinkID
LEFT OUTER JOIN dbo.MstInsurer ON
dbo.MstInsurer.InsurerID= dbo.TrnClaim.InsurerID
INNER JOIN dbo.TrnLegend On
dbo.TrnLegend.ClientID = dbo.TrnClaim.ClientID
AND
dbo.TrnLegend.FileNo = dbo.TrnClaim.FileNo
WHERE
Upper(dbo.TrnLegend.LegendDescr) LIKE '%CANCELLED%'
Order By
dbo.TrnClaim.ClientID
, dbo.TrnClaim.FileNo
, dbo.TrnLegendRecordNo

When using Group By you specify list of attributes. A query that contains a GROUP BY clause generates one row per group based on each unique combination of values of the attributes that belong to the grouping set.
Consequently, when GROUP BY is specified in a query, all subsequent steps (HAVING, SELECT, and so on) can specify only expressions that have a scalar (singular) value per group. These expressions can include columns or expressions from the GROUP BY list like TrnClaim.ClientID β€”or aggregate functions, such as COUNT(TrnClaim.ClientID).
As I can see you have not included any aggregate function in your query above that's why when you write say Group By (TrnClaim.ClientID) or any other column then no group is created or to rephrase each row becomes a unique group and so it requires that all the fields in the select clause are included.
That's the reason why you are getting same data with Distinct and GROUP BY becuase no group has been created.

Related

Two select statements turn into one

I have set of two queries. In first query, if is separate from second, I got good results.
First query
SELECT *
FROM
(
SELECT nks.[Id]
, nks.[IdNarudzbe]
, nks.[IdArtikla] as artikal
, nks.[IdUsluge]
, nks.[Naziv]
, nks.Kolicina
, p.Naziv as kupac
, p.Id as kupacId
, p.Adresa
, p.Telefon
, nkz.[BrojDokumenta] AS nalog
, nkz.[BrojDokumentaKroz] AS nalogKroz
, nkz.[RokIsporuke]
, nkz.[IdNastaloOdDokumenta]
, d.Naziv as drzava
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0
--...
from first query nkz.[IdNastaloOdDokumenta] is important to second
SELECT BrojDokumenta
, BrojDokumentaKroz
FROM .[dbo].[NarudzbeKupacaZaglavlje]
where id = nkz.[IdNastaloOdDokumenta]
For ex. In first query I got nkz.[IdNastaloOdDokumenta] = 20. Number 20 I use in second query in where statement, and value I get from BrojDokumenta, I would like to join to first query.
I was wondering if is possible to make one query out of these two. I think I can not union operator because number of column from these two queries don't match.
The same table, and the same columns are already in the first query. Perhaps you want a self-join, like this:
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz2
ON nkz2.Id = nkz.[IdNastaloOdDokumenta]
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0

SSRS Subreport runs multiple times, I only want it running once

I have a report that has a drillthrough subreport that runs multiple times when it has more than one relationship to a many to many item that has nothing to do with the subreport.
Main report query
SELECT DISTINCT
cat.CategoryName AS 'Category Name', sub.SubCategoryName AS 'SubCategory Name', cur.Status, cur.PastConsiderationFlag, cur.Model, cur.Version, cur.Vendor, cur.AvailableDate AS 'Available Date', cur.EndOfProduction AS 'End of Production',
cur.EndOfSupport AS 'End of Support', dep.DepartmentName AS 'Department Name', emp.FirstName + ' ' + emp.LastName AS 'Tech Owner', emp2.FirstName + ' ' + emp2.LastName AS 'Tech Contact',
cur.NumOfDevices AS '# of Devices', cur.UpgradeDuration AS 'Upgrade Duration', cur.FiscalConsideration AS 'Fiscal Consideration', cur.Description, cur.SupportingComments, cur.CurrencyId, STUFF
((SELECT ', ' + pl.PlatformName AS Expr1
FROM Platform AS pl LEFT OUTER JOIN
Currency_Platform AS cp ON cur.CurrencyId = cp.CurrencyId
WHERE (pl.PlatformId = cp.PlatformId) FOR XML PATH('')), 1, 1, '') AS 'Platforms', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Dependency AS cd ON cur.CurrencyId = cd.CurrencyId
WHERE (cu2.CurrencyId = cd.DependencyId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Dependencies', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Affected AS ca ON cur.CurrencyId = ca.CurrencyId
WHERE (cu2.CurrencyId = ca.AffectedId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Affected Apps', Currency_Platform.PlatformId
FROM Currency AS cur INNER JOIN
SubCategory AS sub ON cur.SubCategoryId = sub.SubCategoryId INNER JOIN
Category AS cat ON sub.CategoryId = cat.CategoryId LEFT OUTER JOIN
Employee AS emp ON cur.OwnerId = emp.EmployeeId LEFT OUTER JOIN
Employee AS emp2 ON cur.ContactId = emp2.EmployeeId LEFT OUTER JOIN
Department AS dep ON cur.PortfolioOwnerId = dep.DepartmentId LEFT OUTER JOIN
Currency_Platform ON cur.CurrencyId = Currency_Platform.CurrencyId
Even though it's a distinct select, the subreport will run equal to the amount of Platforms it belongs to. I'll include the Query for the subreport here.
;with cte as (
-- anchor elements: where curr.Status = 1 and not a dependent
select
CurrencyId
, Model
, Version
, ParentId = null
, ParentModel = convert(varchar(128),'')
, Root = curr.Model
, [Level] = convert(int,0)
, [ParentPath] = convert(varchar(512),Model + Version)
from dbo.Currency as curr
where curr.Status = 1
/* anchor's do not depend on any other currency */
and not exists (
select 1
from dbo.Currency_Dependency i
where curr.CurrencyId = i.DependencyId
)
-- recursion begins here
union all
select
CurrencyId = c.CurrencyId
, Model = c.Model
, Version = c.Version
, ParentId = p.CurrencyId
, ParentModel = convert(varchar(128),p.Model + p.Version)
, Root = p.Root
, [Level] = p.[Level] + 1
, [ParentPath] = convert(varchar(512),p.[ParentPath] + ' > ' + c.Model + ' ' + c.Version)
from dbo.Currency as c
inner join dbo.Currency_Dependency as dep
on c.CurrencyId = dep.DependencyId
inner join cte as p
on dep.CurrencyId = p.CurrencyId
)
select CurrencyId, ParentPath, Model + ' ' + Version AS 'Model' from cte
WHERE CurrencyId = #CurrencyId
When I run the subreport individually, everything is fine. When I open the subreport through the main report passing the CurrencyId as a parameter, it does so as many times as the amount of platforms it belongs to.
Is there a way I can correct this either by improving the queries, or as I would prefer, force the subreport to only run once no matter what?
Thanks so much for having a look.
You can use SQL Server Profiler to check the following things.
How many times and with what parameters is the subreport query has ran
How many values your first query returned
I don't think your problem is more about SSRS than it is about your T-SQL Code. I'm going to guess and say that the subreport object is in the report detail section of the report. That means that the subreport is going to render once for every row in the main queries dataset. I don't have any idea what your container report actually looks like but one option you have might be to include the subreport in the header or footer section and have it run off of a MAX(), MIN(), of a value that you know will be the same for every row.

Joining reports

I am trying to join 3 reports into one, taking parts out of each report.
This is my script that works with 2 of the reports:
ALTER VIEW [dbo].[v_JB2] AS
SELECT R.*, I.ENTERED, I.PROBLEM_CODE, I.WORKORDER
FROM DALE.DBO.V_JBTRB R
JOIN REPORTS.DBO.V_TC_ANALYSIS_JEREMY I
ON R.HUBID = I.HUB
AND R.NODEID = I.NODE
AND CAST(R.CREATE_DATE AS DATE) = I.ENTERED_DATE
GO
and I want to add this field A.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS from what should be DALE.DBO.V_MTTA
Your join of DALE.DBO.V_MTTA has no ON condition...
Try this:
SELECT R.*, I.ENTERED, I.PROBLEM_CODE, I.WORKORDER,
A.CREATE_DATE-O.ACTUAL_START_DATE as ASSIGN_SECS
FROM
DALE.DBO.V_JBTRB R JOIN
REPORTS.DBO.V_TC_ANALYSIS_JEREMY I
ON R.HUBID = I.HUB AND R.NODEID = I.NODE AND
CAST(R.CREATE_DATE AS DATE) = I.ENTERED_DATE
JOIN DALE.DBO.V_MTTA A ON A.CREATE_DATE-O.ACTUAL_START_DATE = ??? (what do you want this to be joined on? I don't know how your tables are related, but you need a valid ON statement for this join to work)
so the right answer was and i don't think anyone would have been able to tell based on the code was instead of joining a third query i added to my trb query and got the same data not sure why i didn't think of it sooner.
ALTER VIEW [dbo].[v_JBTRB] AS
SELECT SINGLE_USER, RECORD_ID, DIVISION, CREATE_DATETIMEINNEW, OUTAGESTARTDATE, STATUS_DESC, CAST(HUBID AS VARCHAR(255)) AS HUBID, CAST(NODEID AS VARCHAR(255)) AS NODEID, CATEGORY, STATUS, ASSIGN_SECS
FROM OPENQUERY(REMEDY_BI,
'
SELECT
T.RECORD_ID AS Record_ID
, T.DIVISION AS Division
, T.CREATE_DATE_ET AS Create_Date
, T.TIME_IN_NEW AS TimeInNew
, O.ACTUAL_START_DATE_ET AS OutageStartDate
, T.STATUS_DESC
, T.FACILITY AS HubID
, T.NODE AS NodeID
, T.CATEGORY
, T.STATUS
, T.SINGLE_USER
, T.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS
FROM ARNEUSER.VW_BASE_TROUBLE T
JOIN ARNEUSER.VW_BASE_OUTAGE O
ON O.INSTANCE_ID = T.OUTAGE_INSTANCE_ID
AND O.SUBMITTED_BY = T.SUBMITTER
JOIN ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS A
ON A.TROUBLE_ID = T.TROUBLE_ID
AND A.CREATE_DATE = ( SELECT MIN(CREATE_DATE)
FROM ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS
WHERE TROUBLE_ID=T.TROUBLE_ID
AND STATUS_NUM=1
AND CREATE_DATE>=O.ACTUAL_START_DATE
AND SUBMITTER=T.SUBMITTER )
WHERE T.STATUS > 3
AND T.REGION = ''Carolina''
AND T.CREATE_DATE >= DATE_TO_UNIX_TZ(TRUNC(SYSDATE)-14)
AND T.CATEGORY IN (''HFC'',''CRITICAL INFRASTRUCTURE'',''VIDEO DIGITAL'',''VIDEO ANALOG'',''DIGITAL PHONE'',''HEADEND/HUB'',''METRO/REGIONAL NETWORK'',''NATIONAL BACKBONE'',''NETWORK'')
')
I added this part the rest was already there if that helps this is one of the reports i was originally joining. I was trying to join another report but it came from the same data base.
, T.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS
AND A.CREATE_DATE = ( SELECT MIN(CREATE_DATE)
FROM ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS
WHERE TROUBLE_ID=T.TROUBLE_ID
AND STATUS_NUM=1
AND CREATE_DATE>=O.ACTUAL_START_DATE
AND SUBMITTER=T.SUBMITTER )
this is the other query that was being joined for anyone curious the 8 **** replace some sensitive data
ALTER VIEW [dbo].[v_TC_ANALYSIS_JEREMY] AS
SELECT *, cast(entered_date + ' ' + entered_time as datetime) as ENTERED FROM OPENQUERY(ICOMS_H,'
SELECT
W.WONUM AS WORKORDER,
W.WOTYC AS TYPE,
CVGDT2DATE(W.WOEDT) AS ENTERED_DATE,
W.WOQCD AS QUEUE_CODE,
W.WOETM AS TIME_ENTERED,
W.WOPB1 AS PROBLEM_CODE,
TRIM(H.HOAAEQ) AS HUB,
TRIM(H.HONODE) AS NODE,
H.HOZIP5 AS ZIPCODE,
W.WOPOL AS POOL,
P.EXTXD0 AS AREA,
CVGTM2TIME(W.WOETM) AS ENTERED_TIME
FROM
********.WOMHIPF W
JOIN ******.HOSTPF H ON H.HONUM = W.WOHNUM
JOIN CF83PF P ON P.EXPLLL = W.WOPOL
WHERE
W.WOEDT >= REPLACE(CHAR(CURRENT_DATE - 14 DAYS,ISO),''-'','''')-19000000
AND ((WOTYC =''SR'' AND WOQCD IN (''O'',''M'')) OR (WOTYC =''TC''))
AND WOPOL IN (''1'',''2'',''3'',''4'',''6'',''7'',''E'',''M'',''R'')

Exclude few selected fields on group by

I had a query that was returning member transaction information. This query has an aggregate function to calculate the amount. All is working fine according to its grouping. Now what I need to do is to add two more columns from different tables. I did try to add them unfortunately they are giving me duplicated information with tons number of records.
Can anyone help me I just want to be able to include the two fields on the query and not include them in the group by clause. And also ensure that data returned is not a duplicate
See below is the query I used.
DECLARE #LastMonthExtractID Int = 11
SELECT x.*
,lstmnth.Submission ---added
,lm_subt.SubmissionTypeDescription ---added
FROM (
SELECT MemberRef --unique key
, SiteName
, ChargePeriod
, SUM(Amount) AS Amount
, TransactionMap
, PackageCode
FROM (
SELECT MemberRef
, SiteName
, ChargePeriod
, Amount
, PackageCode
, CASE WHEN map.TransactionMap = 'JoinFee' AND lstmnth.ChargeDate <> lstmnth.JoinDate THEN 'PayPlan'
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'PV%' AND lstmnth.SiteID <> 15 THEN 'VitalityMF' -- must use Package and not CURRENT PACKAGE
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'PV%' AND lstmnth.SiteID = 15 THEN 'PlatVitalityMF' -- PLATINUM
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'Z%' THEN 'ZContract'
WHEN map.TransactionMap IS NULL THEN 'Other'
ELSE map.TransactionMap END AS TransactionMap
--, lstmnth.Submission
--, lm_subt.SubmissionTypeDescription --added
FROM dbo.CCX_Billing lstmnth
LEFT JOIN dbo.TransactionMap map on lstmnth.TransactionType = map.TransactionType
AND lstmnth.TransactionDescription = map.TransactionDescription
AND ISNULL (lstmnth.AnalysisCode, '') = map.AnalysisCode
WHERE lstmnth.ExtractID = #LastMonthExtractID
) l
GROUP BY SiteName, MemberRef, ChargePeriod, PackageCode, TransactionMap
) x
INNER JOIN dbo.CCX_Billing lstmnth ON lstmnth.MemberRef = x.MemberRef
LEFT JOIN dbo.CCX_Billing_PSubmission lm_sub on lstmnth.SubmissionID = lm_sub.ID
INNER JOIN dbo.CCX_Billing_SubmissionType lm_subt on lm_sub.SubmissionTypeID = lm_subt.SubmissionID --added

SQL Sub-select as field?

I'm a bit lost here...
I have several tables I'd like to pull a unified record from: Unit, Building, Owner, and Picture.
Here's my query so far:
SELECT building.`Street_Address`
, building.`Building_Name`
, building.`Building_Type`
, CONCAT(building.`Cross_Street_1`, ' & ', building.`Cross_Street_2`) Cross_Streets
, building.`Cross_Street_1`
, building.`Cross_Street_2`
, building.`Access` Building_Access
, owner.`Company_Name`
, owner.`Contact_Or_Reference`
, owner.`Landlord_Phone`
, picture.`Path_To_Picture_On_Server`
, picture.`Picture_Category`
, unit.`Apartment_Number`
, unit.`Unit_Size_Number` Size
, unit.`Is_Doorman`
, unit.`Is_Furnished`
, unit.`Is_Elevator`
, unit.`Is_Pets`
, unit.`Is_OutdoorSpace`
, unit.`Rent_Price`
, unit.`Baths`
, unit.`Access` Unit_Access
, unit.`fourd_id`
, unit.`Updated_Date`
, unit.`Occupancy_Date`
, unit.`Term`
, unit.`Incentives`
, unit.`Info_OutdoorSpace`
, unit.`List_Date`
, zone.`Description`
FROM 4D_Units unit
JOIN 4D_Building building
ON unit.`BUILDING_RecID` = building.`fourd_id`
JOIN 4D_Zones zone
ON building.`ZONES_RecID` = zone.`fourd_id`
LEFT JOIN 4D_Owners owner
ON unit.`OWNER_RecID` = owner.`fourd_id`
LEFT JOIN 4D_Building_Picts picture
ON (building.`fourd_id` = picture.`BUILDING_RecID` AND picture.`Picture_Category` = 'Front')
WHERE unit.`id` = 49901
This works fine as-is, except that the return record will only ever have the "Front" picture in the record (if present). My issue is that there are several different types of photos that could be associated with a return record, including 'Panorama', 'Interior', and 'Floorplan'... all are different possible values for picture.Picture_Category.
Is there a way to return those values (if they are present, as above) in the returned set without doing a separate query? I want the returned set to include (if present) aliased values for all four possible options of picture.Picture_Category: 'Front', 'Panorama', 'Interior', & 'Floorplan' (with their own unique picture.Path_To_Picture_On_Server associated with it).
Does that make sense?
If I understand you correctly, you want to have 4 sets of picture columns in your result set - one of reach of 4 categories? Right now you have just one for front, right?
You can join to the same table multiple times with different aliases and different join clauses. Just join to 4D_Building_Picts 4 times, once for each picture you want.
select
--whatever
, pic_front.`Path_To_Picture_On_Server` AS Front_Path_To_Picture_On_Server
, pic_panorama.`Path_To_Picture_On_Server` AS Panorama_Path_To_Picture_On_Server
, pic_interior.`Path_To_Picture_On_Server` AS Interior_Path_To_Picture_On_Server
, pic_floorplan.`Path_To_Picture_On_Server` AS Floorplan_Path_To_Picture_On_Server
--whatever
FROM 4D_Units unit
JOIN 4D_Building building
ON unit.`BUILDING_RecID` = building.`fourd_id`
JOIN 4D_Zones zone
ON building.`ZONES_RecID` = zone.`fourd_id`
LEFT JOIN 4D_Owners owner
ON unit.`OWNER_RecID` = owner.`fourd_id`
LEFT JOIN 4D_Building_Picts pic_front
ON (building.`fourd_id` = pic_front.`BUILDING_RecID` AND pic_front.`Picture_Category` = 'Front')
LEFT JOIN 4D_Building_Picts pic_panorama
ON (building.`fourd_id` = pic_panorama.`BUILDING_RecID` AND pic_panorama.`Picture_Category` = 'Panorama')
LEFT JOIN 4D_Building_Picts pic_interior
ON (building.`fourd_id` = pic_interior.`BUILDING_RecID` AND pic_interior.`Picture_Category` = 'Interior')
LEFT JOIN 4D_Building_Picts pic_floorplan
ON (building.`fourd_id` = pic_floorplan.`BUILDING_RecID` AND pic_floorplan.`Picture_Category` = 'Floorplan')
WHERE unit.`id` = 49901
I think you want the coalesce function. It takes multiple fields, and returns the first of them that's non-null. So something like:
Select
Coalesce(A.Panorama, A.Interior, A.Floorplan, '') as ImagePath
From
Table A
You only end up with one value this way though, which may not actually be what you're after. If you want all of them I'd suggest using correlated subqueries, like so:
Select
(Select P.Path_To_Picture From 4D_Building_Picts P where P.Building_RecID = B.fourd_Id And P.Picture_Category = 'Front') as Front_Pic,
(Select P.Path_To_Picture From 4D_Building_Picts P where P.Building_RecID = B.fourd_Id And P.Picture_Category = 'Panorama') as Panamora_Pic,
(Select P.Path_To_Picture From 4D_Building_Picts P where P.Building_RecID = B.fourd_Id And P.Picture_Category = 'FloorPlan') as FloorPlan_Pic,
...
From
4D_Building B