I need the last column AvgRecordCount to be the average of every two columns; see the first image for an example...
Any suggestions?
SELECT l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END AS LabelType,
COUNT(i.LabelTypeID) as RecordCount
FROM [RxTransaction] rxt
INNER JOIN Dimension.Item i
ON rxt.DispensedItemID = i.ItemID AND
rxt.LocationID = i.LocationID
INNER JOIN Dimension.Location l
ON rxt.LocationID = l.LocationId
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND
rxt.DateFilled BETWEEN '12/1/2014' AND '12/31/2014'
GROUP BY i.LabelTypeID, l.AltName
I'd like to see results like the items in this table, notice the new column percentage average across the two rows, generic/brand sets.
Image shows the SQL and current results, I want a new column that has each 2 rows percentage over each other.
I solved this by writing select statements for each of the calculated fields I needed... see below.
SELECT L.AltName, L.LocationId, COUNT(A.LabelTypeID) As TotalRecords,
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE i.LabelTypeID = 1 AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014') As GenericTotal,
100
*
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE i.LabelTypeID = 1 AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014')
/
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014') As PercentAvg
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] B
INNER JOIN Dimension.Item A on B.DispensedItemID = A.ItemID AND B.LocationID = A.LocationID
INNER JOIN Dimension.Location L on B.LocationID = L.LocationId
WHERE B.DateFilled between '12/1/2014' and '12/31/2014'
Group by L.AltName, L.LocationId
order by PercentAvg
You need to group by with the exact CASE statement you have used in your select statement , something like....
SELECT l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END AS LabelType,
COUNT(i.LabelTypeID) as RecordCount
FROM [RxTransaction] rxt
INNER JOIN Dimension.Item i
ON rxt.DispensedItemID = i.ItemID AND
rxt.LocationID = i.LocationID
INNER JOIN Dimension.Location l
ON rxt.LocationID = l.LocationId
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND
rxt.DateFilled BETWEEN '12/1/2014' AND '12/31/2014'
GROUP BY l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END
Related
i have checked some similar issues in the forum but i can't seems to get it to work properly.
i'm on phpmyadmin
i need to get a result like that :
Reference | ProductNameEnglish | ProductNameFrench
What's blocking me is to do 2 requests on the same column (pl.name) :/
Here is my query for now :
SELECT
p.reference AS Reference,
(SELECT pl.name
FROM ps_product p
LEFT JOIN ps_product_lang pl ON (p.id_product = pl.id_product)
WHERE p.active = 1
AND pl.id_lang = 2) AS ENname,
(SELECT pl.name
FROM ps_product p
LEFT JOIN ps_product_lang pl ON (p.id_product = pl.id_product)
WHERE p.active = 1
AND pl.id_lang = 1) AS FRname
FROM ps_product p
You don't need the join in the subqueries:
SELECT p.reference AS Reference,
(SELECT pl.name
FROM ps_product_lang pl
WHERE p.id_product = pl.id_product AND
p.active = 1 AND
pl.id_lang = 2
) AS ENname,
(SELECT pl.name
FROM ps_product_lang pl
WHERE p.id_product = pl.id_product AND
p.active = 1 AND
pl.id_lang = 1
) AS FRname
FROM ps_product p;
This assumes that only one row matches the subqueries. You may need to limit the results to a single row if that is not the case.
SELECT
p.reference AS Reference,
pl.name as ENname,
pf.name as FRname
FROM ps_product p
LEFT JOIN ps_product_lang pl ON (p.id_product = pl.id_product and pl.id_lang = 1)
LEFT JOIN ps_product_lang pf ON (p.id_product = pf.id_product and pf.id_lang = 2)
WHERE p.active = 1
I might have switched English and French, but that should be easy to fix....
i need to put those two output values (Add_sum and Minus_sum) to one table and subtract them (Add_sum - Minus_sum) and show this value.
I tried many other options, subqueries etc but could not get it to work.
Query 1:
SELECT I.ItemCode, COUNT(H.TransactionTypeID) AS ADD_Sum
FROM inMoveHd AS H INNER JOIN
inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
inItem AS I ON I.ItemID = L.ItemID INNER JOIN
inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE (T.TransactionSign = 1)
GROUP BY I.ItemCode
Query 2:
SELECT I.ItemCode, COUNT(H.TransactionTypeID) AS Minus_Sum
FROM inMoveHd AS H INNER JOIN
inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
inItem AS I ON I.ItemID = L.ItemID INNER JOIN
inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE (T.TransactionSign = -1)
GROUP BY I.ItemCode
Use case expressions to do conditional aggregation:
SELECT I.ItemCode,
COUNT(case when T.TransactionSign = 1 then H.TransactionTypeID end) AS ADD_Sum,
COUNT(case when T.TransactionSign = -1 then H.TransactionTypeID end) AS Minus_Sum
FROM inMoveHd AS H INNER JOIN
inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
inItem AS I ON I.ItemID = L.ItemID INNER JOIN
inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE (T.TransactionSign = -1 or T.TransactionSign = 1)
GROUP BY I.ItemCode
I think that you are looking for conditional aggregation:
SELECT
I.ItemCode,
SUM(CASE WHEN T.TransactionSign = 1 THEN 1 ELSE 0 END) AS Add_Sum,
SUM(CASE WHEN T.TransactionSign = -1 THEN 1 ELSE 0 END) AS Minus_Sum,
SUM(T.TransactionSign) difference
FROM
inMoveHd AS H INNER JOIN
inMoveLn AS L ON L.InvMoveID = H.InvMoveID INNER JOIN
inItem AS I ON I.ItemID = L.ItemID INNER JOIN
inTransactionType AS T ON H.TransactionTypeID = T.TransactionTypeID
WHERE T.TransactionSign IN (-1, 1)
GROUP BY I.ItemCode
I have an Update query that will help me to update a certain field and right now it is throwing an error on the last two lines of code where the d.column is mentioned. Does anyone know how I can still use the d.column fields at the end or know a work around that will produce the same results? Help is greatly appreciated. The error is where I am using d.LastUpdateSchedule and d.Due_Dte in the last two lines of code.
update ods.Customer
set NumberTPD = a.NumberCode
from ods.Customer r
left join
(
Select d.CustomerNumber
, d.due_Dte
, l.NumberCode
from (select r.CustomerNumber
, r.due_Dte
, r.NumberTPD
, max(l.UpdateSchedule) as LastUpdateSchedule
from ods.Customer r
left join ods.CustomerHistory l
on r.CustomerNumber = l.CustomerNumber
and r.due_Dte >= l.UpdateSchedule
and l.Examine = 1
and r.ExamineFrequency in ('MONTHLY','MNTHLYLDAY')
and isnull(r.ScheduleEndDate,'1970-01-01') < r.due_Dte
group by r.CustomerNumber, r.Due_Dte, r.NumberTPD) d
left join ods.CustomerHistory l
on d.CustomerNumber = l.CustomerNumber
and d.LastUpdateSchedule = l.UpdatedSchedule
) a
on r.CustomerNumber = a.CustomerNumber
and r.Due_Dte = a.Due_Dte
where d.Due_Dte > '2018-08-03'
and d.LastUpdateSchedule is not null
this is because your table d is inside your table a move your where clause to table d
update ods.Customer
set NumberTPD = a.NumberCode
from ods.Customer r
left join
(Select d.CustomerNumber
, d.due_Dte
, l.NumberCode
from
(select r.CustomerNumber
, r.due_Dte
, r.NumberTPD
, max(l.UpdateSchedule) as LastUpdateSchedule
from ods.Customer r
left join ods.CustomerHistory l on r.CustomerNumber = l.CustomerNumber
and r.due_Dte >= l.UpdateSchedule
and l.Examine = 1
and r.ExamineFrequency in ('MONTHLY','MNTHLYLDAY')
and isnull(r.ScheduleEndDate,'1970-01-01') < r.due_Dte
group by r.CustomerNumber, r.Due_Dte, r.NumberTPD) d
left join ods.CustomerHistory l on d.CustomerNumber = l.CustomerNumber
and d.LastUpdateSchedule = l.UpdatedSchedule
where d.Due_Dte > '2018-08-03'
and d.LastUpdateSchedule is not null
) a on r.CustomerNumber = a.CustomerNumber
and r.Due_Dte = a.Due_Dte
-- only what you need
UPDATE cust
SET cust.NumberTPD = histRow.NumberCode
FROM ods.Customer cust
JOIN
(SELECT c.CustomerNumber,
max(h.UpdateSchedule) AS LastUpdateSchedule
FROM ods.Customer c
JOIN ods.CustomerHistory h ON c.CustomerNumber = h.CustomerNumber
AND c.due_Dte >= h.UpdateSchedule
WHERE c.Due_Dte > '2018-08-03'
AND c.ExamineFrequency IN ('MONTHLY',
'MNTHLYLDAY')
AND isnull(c.ScheduleEndDate, '1970-01-01') < c.due_Dte --sure about this?
AND h.Examine = 1
GROUP BY c.CustomerNumber) maxes
JOIN ods.CustomerHistory histRow ON maxes.CustomerNumber = histRow.CustomerNumber
AND maxes.LastUpdateSchedule = histRow.UpdatedSchedule
I have 4 tables that has aantal ( count ) and each tables shows normal numbers or numbers with - before (example: -20) now I need to count all that records. but I don't know how I can fix that.
Sorry I am a noob in sql.
this is my code
The problem that i facing to is tha all records from the different tables that has column aantal not counting in total.
example:
CSSDKMagento_10_Plankvoorraad returns 10
CSSDKMagento_20_GeenAllocatieWelFiat returns -3 and -2
CSSDKMagento_30_AllocatieVoorraad returns 5
CSSDKMagento_50_AllocatieBestellingBinnen returns -1 and -1
That means that i get on return from Voorraad is 8.
I tried count(*) but that is not the solution. with best way I can do it?
SELECT
i.ItemCode,
g.warehouse,
SUM(g.aantal) AS Voorraad,
MAX(CASE
WHEN g.transtype = 'N' THEN g.sysmodified
ELSE NULL
END) AS LastDate
FROM dbo.CSSDKMagento_10_Plankvoorraad AS g
INNER JOIN dbo.Items AS i
ON (g.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_20_GeenAllocatieWelFiat AS a
ON (a.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_30_AllocatieVoorraad AS v
ON (v.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_50_AllocatieBestellingBinnen AS b
ON (b.artcode = i.ItemCode)
WHERE
i.itemcode = 'TEST'
GROUP BY i.itemcode,
g.warehouse;
Try this
SELECT
i.ItemCode,
g.warehouse,
SUM(g.aantal)+SUM(a.aantal)+SUM(v.aantal)+SUM(b.aantal) AS Voorraad,
MAX(CASE
WHEN g.transtype = 'N' THEN g.sysmodified
ELSE NULL
END) AS LastDate
FROM dbo.CSSDKMagento_10_Plankvoorraad AS g
INNER JOIN dbo.Items AS i
ON (g.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_20_GeenAllocatieWelFiat AS a
ON (a.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_30_AllocatieVoorraad AS v
ON (v.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_50_AllocatieBestellingBinnen AS b
ON (b.artcode = i.ItemCode)
WHERE
i.itemcode = 'TEST'
GROUP BY i.itemcode,
g.warehouse;
Edited:
SELECT SUM(Voorraad) FROM (
SELECT
i.ItemCode,
g.warehouse,
g.aantal AS Voorraad,
MAX(CASE
WHEN g.transtype = 'N' THEN g.sysmodified
ELSE NULL
END) AS LastDate
FROM dbo.CSSDKMagento_10_Plankvoorraad AS g
INNER JOIN dbo.Items AS i
ON (g.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_20_GeenAllocatieWelFiat AS a
ON (a.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_30_AllocatieVoorraad AS v
ON (v.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_50_AllocatieBestellingBinnen AS b
ON (b.artcode = i.ItemCode)
WHERE
i.itemcode = 'TEST' enter code here
GROUP BY i.itemcode,
g.warehouse
)src
Looks like following would work:
WITH itemCodesScope AS
(
SELECT 'TEST' as target_ItemCode
),
aggregated_CSSDKMagento_10_Plankvoorraad AS
(
SELECT g.artcode,
g.warehouse,
COUNT(g.aantal) as count_aantal,
SUM(g.aantal) as sum_aantal,
MAX(CASE
WHEN g.transtype = 'N' THEN g.sysmodified
ELSE NULL
END) AS LastDate
FROM dbo.CSSDKMagento_10_Plankvoorraad AS g
JOIN itemCodesScope ON itemCodesScope.target_itemCode = g.artcode
GROUP BY
g.artcode,
g.warehouse
),
aggregated_CSSDKMagento_20_GeenAllocatieWelFiat AS
(
SELECT a.artcode ,
COUNT(a.aantal) as count_aantal,
SUM(a.aantal) as sum_aantal
FROM dbo.CSSDKMagento_20_GeenAllocatieWelFiat AS a
JOIN itemCodesScope ON itemCodesScope.target_itemCode = a.artcode
GROUP BY
a.artcode
),
aggregated_CSSDKMagento_30_AllocatieVoorraad AS
(
SELECT v.artcode ,
COUNT(v.aantal) as count_aantal,
SUM(v.aantal) as sum_aantal
FROM dbo.CSSDKMagento_30_AllocatieVoorraad AS v
JOIN itemCodesScope ON itemCodesScope.target_itemCode = v.artcode
GROUP BY
v.artcode
),
aggregated_CSSDKMagento_50_AllocatieBestellingBinnen AS
(
SELECT b.artcode ,
COUNT(b.aantal) as count_aantal,
SUM(b.aantal) as sum_aantal
FROM dbo.CSSDKMagento_50_AllocatieBestellingBinnen AS b
JOIN itemCodesScope ON itemCodesScope.target_itemCode = b.artcode
GROUP BY
b.artcode
)
SELECT
g.artcode as ItemCode,
g.warehouse,
g.sum_aantal AS Voorraad,
g.LastDate AS LastDate,
g.sum_aantal + ISNULL(a.sum_aantal, 0) + ISNULL(v.sum_aantal, 0) + ISNULL(b.sum_aantal, 0) as sum_aantal,
g.count_aantal + ISNULL(a.count_aantal, 0) + ISNULL(v.count_aantal, 0) + ISNULL(b.count_aantal, 0) as count_aantal
FROM aggregated_CSSDKMagento_10_Plankvoorraad AS g
INNER JOIN dbo.Items AS i
ON (g.artcode = i.ItemCode)
INNER JOIN itemCodesScope
ON itemCodesScope.target_itemCode = i.ItemCode
LEFT JOIN aggregated_CSSDKMagento_20_GeenAllocatieWelFiat AS a
ON (a.artcode = i.ItemCode)
LEFT JOIN aggregated_CSSDKMagento_30_AllocatieVoorraad AS v
ON (v.artcode = i.ItemCode)
LEFT JOIN aggregated_CSSDKMagento_50_AllocatieBestellingBinnen AS b
ON (b.artcode = i.ItemCode)
Explanation
SQL-joins produce Cartesian Products, which most probably led to unexpected results in the initial query. Here there are 4 'amount'-tables which are connected via Joins with conditions 'ON (b.artcode = i.ItemCode)', so if there any table contains several records per condition output will contain several records per ItemCode.
Let's say there are 9 records in a-table with a.artcode per single i.ItemCode, so there is a one-to-many relation. And let's say there is 1 record in b-table per single i.ItemCode. Output of Join will have 9 a.aantal records, but 9 repeated b.aantal records as well. Given that there is an aggregation (group by) it will effect that SUM(b.aantal) in this Joins-query will produce 9-time more than sum(b.aantal) in standalone query on b-table only.
Cartesian Product could be seen more easily, if run the initial query without aggregation:
SELECT *
FROM dbo.CSSDKMagento_10_Plankvoorraad AS g
INNER JOIN dbo.Items AS i
ON (g.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_20_GeenAllocatieWelFiat AS a
ON (a.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_30_AllocatieVoorraad AS v
ON (v.artcode = i.ItemCode)
INNER JOIN dbo.CSSDKMagento_50_AllocatieBestellingBinnen AS b
ON (b.artcode = i.ItemCode)
WHERE
i.itemcode = 'TEST'
The fixture was: doing group by aggregation before making joins. Most convenient way for this imho is CTE. With CTE I created 4 temporary tables with aggregates per ItemCode, so temporary tables are one-to-one per ItemCode. Then Joins on one-to-one produce just single output row per ItemCode.
I am performing a query and its showing an error Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
the query is
SELECT
tbl_Product.ID,
tbl_Product.ArticleID,
tbl_Product.Title,
tbl_Product.Description,
tbl_Product.Price,
tbl_ProductType.Name,
tbl_Status.StatusName,
tbl_VisibilityStatus.VisibilityStatus,
MAX(
CASE
WHEN tbl_RelatedProduct.TypeOfRelation = 1 THEN 'Bundle'
WHEN tbl_Product.ID IN
(
select tbl_RelatedProduct.Product2ID
from tbl_RelatedProduct
where tbl_RelatedProduct.Product1ID=9 and tbl_RelatedProduct.TypeOfRelation=1) THEN 'Bundle'
END
) 'Bundle',
MAX(
CASE
WHEN tbl_RelatedProduct.TypeOfRelation = 2 THEN 'Follower' END) 'Follower',
MAX(
CASE
WHEN tbl_RelatedProduct.TypeOfRelation = 3 THEN 'Related' END) 'Related'
FROM
tbl_Product inner JOIN
tbl_ProductType ON tbl_Product.ProductTypeId = tbl_ProductType.ID Inner JOIN
tbl_Status ON tbl_Product.StatusID = tbl_Status.ID Inner JOIN
tbl_VisibilityStatus ON tbl_Product.VisibilityID = tbl_VisibilityStatus.ID
left JOIN tbl_RelatedProduct ON tbl_Product.ID = tbl_RelatedProduct.Product1ID
group by
tbl_Product.ID,
tbl_Product.ArticleID,
tbl_Product.Title,
tbl_Product.Description,
tbl_Product.Price,
tbl_ProductType.Name,
tbl_Status.StatusName,
tbl_VisibilityStatus.VisibilityStatus
order by tbl_Product.Title
ANyone know how to help on this...plsss
The below line is causing an issue:
WHEN tbl_Product.ID IN
(
select tbl_RelatedProduct.Product2ID
from tbl_RelatedProduct
where tbl_RelatedProduct.Product1ID=9 and tbl_RelatedProduct.TypeOfRelation=1) THEN 'Bundle'
END
) 'Bundle',
You are using MAX with CASE and one of the statements within CASE uses a subquery, which is causing the error. You might want to consider using joins instead of subqueries to implement this.
SELECT tbl_Product.ID,tbl_Product.ArticleID,tbl_Product.Title,tbl_Product.Description,tbl_Product.Price,tbl_ProductType.Name,tbl_Status.StatusName, tbl_VisibilityStatus.VisibilityStatus,
Case when ((select count(1) from tbl_RelatedProduct where tbl_RelatedProduct.TypeOfRelation = 1 and tbl_RelatedProduct.Product1ID = tbl_Product.Id) > 0) then 1
when ((select count(1) from tbl_RelatedProduct where tbl_RelatedProduct.TypeOfRelation = 1 and tbl_RelatedProduct.Product2ID = tbl_Product.Id) > 0) then 1
else 0 end as Bundle,
(select count(1) from tbl_RelatedProduct where tbl_RelatedProduct.TypeOfRelation = 2 and tbl_RelatedProduct.Product1ID = tbl_Product.Id) as Follower,
(select count(1) from tbl_RelatedProduct where tbl_RelatedProduct.TypeOfRelation = 3 and tbl_RelatedProduct.Product1ID = tbl_Product.Id) as Related
FROM tbl_Product
inner JOIN
tbl_ProductType ON tbl_Product.ProductTypeId = tbl_ProductType.ID Inner JOIN
tbl_Status ON tbl_Product.StatusID = tbl_Status.ID
Inner JOIN
tbl_VisibilityStatus ON tbl_Product.VisibilityID = tbl_VisibilityStatus.ID
Its resolved with this query :)
I think I see what you are trying to do, and it is a bit strange. I would output this all as a single column, and lose the MAX aggregate as follows:
SELECT
p.ID,
p.ArticleID,
p.Title,
p.Description,
p.Price,
pt.Name,
s.StatusName,
v.VisibilityStatus,
CASE
WHEN rp.TypeOfRelation = 1 OR (rp2.Product1ID = 9 AND rp2.TypeOfRelation = 1)
THEN 'Bundle'
WHEN rp.TypeOfRelation = 2
THEN 'Follower'
WHEN rp.TypeOfRelation = 3
THEN 'Related'
ELSE Null
END AS Relation
FROM
tbl_Product p
INNER JOIN tbl_ProductType pt
ON p.ProductTypeId = pt.ID
INNER JOIN tbl_Status s
ON p.StatusID = s.ID
INNER JOIN tbl_VisibilityStatus v
ON p.VisibilityID = v.ID
LEFT JOIN tbl_RelatedProduct rp
ON p.ID = rp.Product1ID
LEFT JOIN tbl_RelatedProduct rp2
ON p.ID = rp2.Product2ID
ORDER BY p.Title
If you would still like to have them in separate columns, just break up the CASE statement as follows:
SELECT
p.ID,
p.ArticleID,
p.Title,
p.Description,
p.Price,
pt.Name,
s.StatusName,
v.VisibilityStatus,
CASE
WHEN rp.TypeOfRelation = 1 OR (rp2.Product1ID = 9 AND rp2.TypeOfRelation = 1)
THEN 'Bundle'
ELSE Null
END AS Bundle,
CASE
WHEN rp.TypeOfRelation = 2
THEN 'Follower'
ELSE Null
END AS Follower,
CASE
WHEN rp.TypeOfRelation = 3
THEN 'Related'
ELSE Null
END AS Related
FROM
tbl_Product p
INNER JOIN tbl_ProductType pt
ON p.ProductTypeId = pt.ID
INNER JOIN tbl_Status s
ON p.StatusID = s.ID
INNER JOIN tbl_VisibilityStatus v
ON p.VisibilityID = v.ID
LEFT JOIN tbl_RelatedProduct rp
ON p.ID = rp.Product1ID
LEFT JOIN tbl_RelatedProduct rp2
ON p.ID = rp2.Product2ID
ORDER BY p.Title