Counting all records from inner-join - sql

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.

Related

Joining two queries to one table and substracting values

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

Oracle SQL How to Count Column Value Occurences and Group BY during joins

I'm working on another SQL query, trying to group a collection of records while doing a count and joining tables. See below for goal, current query, and attached scripts for building and populating tables.
Show all customers who have checked more books than DVDs. Display
customer name, total book checkouts and total DVD checkouts. Sort
results by customer first name and last name.
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, COUNT(T.TRANSACTION_ID)
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT ON P.CATALOG_ITEM_ID = CT.CATALOG_ITEM_ID
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
Run first: https://drive.google.com/open?id=1PYAZV4KIfZtxP4eQn35zsczySsxDM7ls
Run second: https://drive.google.com/open?id=1pAzWmJqvD3o3n6YJqVUM6TtxDafKGd3f
EDIT
With some help from Mr. Barbaros I've come up with the below query, which is closer. However, this query isn't returning any results for DVDs, which leads me to believe it's a join issue.
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, COUNT(CT1.TYPE) AS BOOK_COUNT, COUNT(CT2.TYPE) AS DVD_COUNT
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT1 ON P.CATALOG_ITEM_ID = CT1.CATALOG_ITEM_ID AND CT1.TYPE = 'BOOK'
LEFT OUTER JOIN catalog_item CT2 ON P.CATALOG_ITEM_ID = CT2.CATALOG_ITEM_ID AND CT2.TYPE = 'DVD'
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME, CT1.TYPE, CT2.TYPE
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
Use "conditional aggregates" (use a case expression inside the aggregate function)
SELECT
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
, COUNT( CASE WHEN CT.TYPE = 'BOOK' THEN T.TRANSACTION_ID END ) books
, COUNT( CASE WHEN CT.TYPE = 'DVD' THEN T.TRANSACTION_ID END ) dvds
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
INNER JOIN catalog_item CT ON P.CATALOG_ITEM_ID = CT.CATALOG_ITEM_ID
GROUP BY
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
HAVING
COUNT( CASE WHEN CT.TYPE = 'BOOK' THEN T.TRANSACTION_ID END )
> COUNT( CASE WHEN CT.TYPE = 'DVD' THEN T.TRANSACTION_ID END )
ORDER BY
C.CUSTOMER_FIRSTNAME
, C.CUSTOMER_LASTNAME
;
You can use catalog_item table twice( think of as seperate tables for books and dvds ), and compare by HAVING clause as :
SELECT C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME,
COUNT(CT1.CATALOG_ITEM_ID) as "Book Checkout",
COUNT(CT2.CATALOG_ITEM_ID) as "DVD Checkout"
FROM customer C
INNER JOIN library_card LC ON C.CUSTOMER_ID = LC.CUSTOMER_ID
INNER JOIN transaction T ON LC.LIBRARY_CARD_ID = T.LIBRARY_CARD_ID
INNER JOIN physical_item P ON T.PHYSICAL_ITEM_ID = P.PHYSICAL_ITEM_ID
LEFT JOIN catalog_item CT1 ON P.CATALOG_ITEM_ID = CT1.CATALOG_ITEM_ID AND CT1.TYPE = 'BOOK'
LEFT JOIN catalog_item CT2 ON P.CATALOG_ITEM_ID = CT2.CATALOG_ITEM_ID AND CT1.TYPE = 'DVD'
GROUP BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME
HAVING COUNT(CT1.CATALOG_ITEM_ID) > COUNT(CT2.CATALOG_ITEM_ID)
ORDER BY C.CUSTOMER_FIRSTNAME, C.CUSTOMER_LASTNAME;
CUSTOMER_FIRSTNAME CUSTOMER_LASTNAME Book Checkout DVD Checkout
------------------ ----------------- ------------- -------------
Deena Pilgrim 3 1
Emile Cross 5 2
Please try to remove ,CT1.TYPE, CT2.TYPE on your group by clause.

Combine multiple queries into one query

I am trying to group by clientid and m.id. How can I convert these 2 queries into 1 query?
Query 1
select cs.clientid, count(distinct(m.id)) as cp
into #temp
from call_table cs
join mem_table m
on cs.CLIENTID = m.clientid
join activity_table a
on a.memid = m.id
where a.activity = 'abc'
group by cs.clientid, m.id
Query 2
select clientid, sum(cp) from #temp
group by ClientId
Update
More specifically, I am looking to write this query without using a temp table.
You could group only by clientid
And since no fields from activity_table are selected, an EXISTS can be used instead.
select cs.clientid, count(distinct m.id) as cp
from call_table cs
join mem_table m on m.clientid = cs.clientid
where exists
(
select 1
from activity_table a
where a.memid = m.id
and a.activity = 'abc'
)
group by cs.clientid
Why wouldn't you just write this as:
with temp as (
select cs.clientid, count(distinct m.id) as cp
from call_table cs join
mem_table m
on cs.CLIENTID = m.clientid join
activity_table a
on a.memid = m.id
where a.activity = 'abc'
group by cs.clientid, m.id
)
select clientid, sum(cp)
from temp
group by ClientId;
I can't figure out what the logic should really be, but this seems like the simplest way to combine the queries.
I would speculate that you simply want this query:
select cs.clientid, count(distinct m.id) as cp
from call_table cs join
mem_table m
on cs.CLIENTID = m.clientid join
activity_table a
on a.memid = m.id
where a.activity = 'abc'
group by cs.clientid;
That is, remove m.id from the group by. And this can in turn be simplified to:
select m.clientid, count(distinct m.id) as cp
from mem_table m join
activity_table a
on a.memid = m.id
where a.activity = 'abc'
group by cs.clientid;
Assuming that m.id is unique and non-NULL, this can be further simplified to:
select m.clientid, count(*) as cp
from mem_table m join
activity_table a
on a.memid = m.id
where a.activity = 'abc'
group by cs.clientid;

Sum from the different tables Sql server

I have couple of tables which stores amount and I want to group by and get sum - reason for the mutiple tables are nhibernate descriminators.
I am using Union all and works but query is very big.
I am using following query
SELECT CustomerAccountNumber,
vc.CustomerName,
SUM(PermAmount) AS PermAmount,
SUM(FreetextAmount) AS FreetextAmount,
(SUM(PermAmount) + SUM(FreetextAmount)) AS TotalAmountByCustomer
FROM
(
SELECT pp.CustomerAccountNumber,
pl.Amount AS PermAmount,
0 AS FreetextAmount
FROM dbo.PermanentPlacementTransactionLine pl
INNER JOIN dbo.TransactionLine tl ON pl.TransactionLineId = tl.Id
INNER JOIN dbo.PermanentPlacement pp ON pl.PermanentPlacementId = pp.Id
WHERE tl.CurrentStatus = 1
GROUP BY pp.CustomerAccountNumber,
pl.Amount,
tl.Id
UNION ALL
SELECT ft.CustomerAccountNumber,
0 AS PermAmount,
ft.Amount AS FreetextAmount
FROM dbo.FreeTextTransactionLine fttl
INNER JOIN dbo.TransactionLine tl ON fttl.TransactionLineId = tl.Id
INNER JOIN dbo.[FreeText] ft ON fttl.FreeTextId = ft.Id
WHERE tl.CurrentStatus = 1
GROUP BY ft.CustomerAccountNumber,
ft.Amount,
tl.Id
) WIPSummary
INNER JOIN dbo.vw_Customer vc ON WIPSummary.CustomerAccountNumber = vc.CustomerAccount
GROUP BY CustomerAccountNumber,
vc.CustomerName;
is there any elegant way of displaying amount in separate columns ?
I can use partition by if it was same table and want to display row by row.
Try these query, is easy to understand and probably faster than yours.
I assume that the values are unique in your view
WITH cte_a
AS (SELECT pp.customeraccountnumber
,Sum(pl.amount) AS PermAmount
,0 AS FreetextAmount
FROM dbo.permanentplacementtransactionline pl
INNER JOIN dbo.transactionline tl
ON pl.transactionlineid = tl.id
INNER JOIN dbo.permanentplacement pp
ON pl.permanentplacementid = pp.id
WHERE tl.currentstatus = 1
GROUP BY pp.customeraccountnumber),
cte_b
AS (SELECT ft.customeraccountnumber
,0 AS PermAmount
,Sum(ft.amount) AS FreetextAmount
FROM dbo.freetexttransactionline fttl
INNER JOIN dbo.transactionline tl
ON fttl.transactionlineid = tl.id
INNER JOIN dbo.[freetext] ft
ON fttl.freetextid = ft.id
WHERE tl.currentstatus = 1
GROUP BY ft.customeraccountnumber)
SELECT vc.customeraccountnumber
,vc.customername
,Isnull(A.permamount, 0) AS PermAmount
,Isnull(B.freetextamount, 0) AS FreetextAmount
,Isnull(A.permamount, 0)
+ Isnull(B.freetextamount, 0) AS TotalAmountByCustomer
FROM dbo.vw_customer vc
LEFT JOIN cte_a a
ON vc.customeraccount = A.customeraccountnumber
LEFT JOIN cte_b b
ON vc.customeraccount = A.customeraccountnumber
if no table structures and sample data, that is the best I can do to help you.

Cannot perform an aggregate function on an expression containing an aggregate or a subquery sql server 2012

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