Inner Join to Same Table Twice on same column - sql-server

I'm having a problem with a SQL Server query trying to join a view with another view twice
SELECT
FAC.*
FROM
ViewFacturacionDiaria_Test AS FAC
INNER JOIN
ViewInformacionRepresentantes AS REP
ON REP.RepIDTabacal = FAC.Vendedor
INNER JOIN
ViewInformacionRepresentantes AS REP2
ON REP2.RepIDCtayOrden = FAC.Vendedor
WHERE
FecCpbte BETWEEN '2015-11-28' AND '2015-11-30'
In the "FAC" view I have sales information, in the other one I have a specific group of sales person which I want to filter from the main view.
I would like to understand why the query is returning an empty resultset.

Sorry, I cannot comment. But I believe Peter is right in his comment. Since you are using 2 inner joins they both need to return results. Are you expecting both joins to find a match?
Try this and see which column is null. That is the join that is resulting in no returned rows.
SELECT
FAC.Vendedor
,REP.RepIDTabacal
,REP2.RepIDCtayOrden
FROM
ViewFacturacionDiaria_Test AS FAC
LEFT JOIN
ViewInformacionRepresentantes AS REP ON
REP.RepIDTabacal = FAC.Vendedor
LEFT JOIN
ViewInformacionRepresentantes AS REP2 ON
REP2.RepIDCtayOrden = FAC.Vendedor
WHERE
FecCpbte BETWEEN '2015-11-28' AND '2015-11-30'

Related

How can I get 3 tables INNER JOIN in MS SQL Server

From the specialist table, retrieve the first name, last name and contact number for the people that provide care to penguins from the species table.
There are 3 tables: tbl_specialist, tbl_species, tbl_care
I need help trying to INNER JOIN the tables to display First, Last, And Contact for penguins.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_species ON species_care = tbl_species.species_care)
INNER JOIN tbl_care ON care_id = tbl_care.care_id)
WHERE species_name = 'penguin'
;
It's a bit difficult without seeing the exact schema of the tables, but your syntax for the subquery is a bit off and you need to alias columns that are found in multiple tables in a JOIN statment. Try rewriting your SQL like this:
SELECT spl.specialist_fname, spl.specialist_lname, spl.specialist_contact
FROM tbl_specialist spl
INNER JOIN tbl_species s
ON spl.species_care = s.species_care
INNER JOIN tbl_care c
ON s.care_id = c.care_id
WHERE s.species_name = 'penguin'
I'm obviously inferring which tables certain columns come from in the join, but hopefully you get the idea.
I figured it out thank you.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_care ON tbl_care.care_specialist = tbl_specialist.specialist_id)
INNER JOIN tbl_species ON tbl_species.species_care= tbl_care.care_id)
WHERE species_name = 'penguin'
;

How to get column value of join query in SSRS?

I have select join query for generating report in SSRS. Query is working fine in SQL Server but as I add same query as dataset in SSRS and try to get rows count using CountRows() function it always return 0 (Zero). I'm not getting where my query is going wrong.
SQL Query
SELECT PR.NAME
FROm innovator.PROJECT PR
INNER JOIN innovator.PROJECT_RISK LPR ON LPR.SOURCE_ID = Pr.ID
INNER JOIN innovator.RISK_MANAGEMENT LR ON LR.id = LPR.RELATED_ID
Inner join innovator.PROGRAM_PROJECT P ON PR.ID = P.RELATED_ID
Inner Join innovator.PROGRAM PP ON P.SOURCE_ID = PP.ID
WHERE pp.ID = #Id
Fetching total count using CountRows() for Textbox
=CountRows(Fields!NAME.Value, "DataSetRisk")
DataSetRisk is Dataset name and Name is column name of Project Table
Use the CountRows function. For example
=CountRows("MyDataset")
Example : =CountRows("DataSetRisk")
will give you the number of rows in MyDataSet.
Try something a little simpler: Count(Fields!NAME.Value) as a column. This assumes, of course, that field name actually is populated. If the column is in separate groups, it will provide a count for each group, otherwise it will count for the entire report.

JOINS in SQL using AdWorks Example

I'm practicing using AdventureWorks and here's the question:
How many Sales Orders (Headers) used Vista credit cards in October 2002
SELECT * FROM Sales.SalesOrderHeader --a
SELECT * FROM Sales.CreditCard --b
SELECT
SUM(a.OrderDate), b.CardType
FROM
[Sales].[CreditCard] b
LEFT OUTER JOIN
[Sales].[SalesOrderHeader] a
I'm not sure how to write this query. I'm new to SQL and this is my first JOIN. Eyes are red...thanks
There are several issues:
You cannot sum dates. You have to use count here.
You must not use an outer join here. Use an inner join. The reason is that you only want SalesOrderHeaders that also have a corresponding CreditCard
You forgot the where clause
A join needs an on condition
select count(*) from
CreditCard cc inner join SalesOrderHeader so on cc.Id = so.CreditCardId
where cc.CardType = 'Visa' and so.OrderDate between '2002-10-01' and '2002-10-31'
I guessed the names of the foreign key fields cc.Id and so.CreditCardId because you didn't indicate this piece of information.

Grouping data based on expression using CountDistinct aggregate function

I am newbie to Stack overflow and also SQL server reporting services. So please excuse me for the format of the question.
So here is the situation:
I am developing a SSRS report which needs to be grouped by an Count of Distinct product names as shown below.
I created a text box called ProdCount with an expression
COUNTDISTNCT(Fields!Product.value,"DataSet1")
which gives me the count 63 within the scope of DataSet1.
Now i need to group the data by taking product names where the above formula is >1 .
=IIF(ProdCount>1,Fields!Product.value,Nothing)
My Problem:
I tried to call the ProdCount from the calculated field since i
cant use the aggregate functions in Calculated Fields and use
the second expression by using
= ReportItems!ProdCount.value
which gives me an error FieldValue Denying ReportItems
I tried to combine the above two expressions by creating a calculated field by
IIF(CountDistinct(Fields!Product.Value,"DataSet1")>1,Fields!Product.Value,Nothing)
which gives me an error Calculated fields cannot have expressions
I tried to use Report Variables in the same way as above(1) which was not working either.
I also tried to use CROSS JOIN in the query
Select Count(Distinct(Product Name)
from Query1
Cross join
My Main Query which give me the data
which is taking more time to execute.
So Can anyone help me with solution where i can group the data by combining the above two expressions.
Please excuse me for the format. I was confused with framing question. I accept all your edits , so that i can learn in future.
Here is my code:
SELECT * FROM
--Query1 which counts the number of distinct products)
(SELECT DISTINCT COUNT(gproduct.ProductName) AS ProdCount
FROM Table1
LEFT JOIN Table4
ON Table1.column=Table1.column
LEFT JOIN Table2
ON Table3.Column = TTable1.Column
LEFT JOIN
(
SELECT Distinct Table6.Name AS ProductName,Table9.ColumnId
FROM Table6
INNER JOIN Table7
ON Table6.Column=Table7.Column
INNER JOIN Table8
ON Table7.Column=Table8.Column
INNER JOIN Table9
ON Table9.Column=Table8.Column
)gproduct
ON Table1.ColumnId=gproduct.ColumnId
GROUP BY gproduct.ColumnId,
)qProduct
CROSS JOIN
--My main Query which get data from different table including Product name
(SELECT
Upper(CASE WHEN (CASE WHEN Table4.Column =1 THEN 'Yes' ELSE 'NO' END)='YES'
THEN gab.ProductName
ELSE
Table2.productName
END) AS Product,
FROM Table1 AS ec
LEFT JOIN Table2 AS ep
ON --
LEFT JOIN Table3 AS ebrd
ON --
Left JOIN Table4 AS etpc
ON --
LEFT JOIN Table5 AS gst
ON --
LEFT JOIN
(
SELECT Distinct Table6.Name AS ProductName,Table9.ColumnId
FROM Table6
INNER JOIN Table7
ON Table6.Column=Table7.Column
INNER JOIN Table8
ON Table7.Column=Table8.Column
INNER JOIN Table9
ON Table9.Column=Table8.Column
) gab
ON Table1.ColumnId=gab.ColumnId
)QMain
Personally I would try to solve the problem in query itself instead of SSRS report. According the data you provided it would be something like:
SELECT
ProductName,
count(distinct Product)
from
YourTable
group by
ProductName
having count(distinct product) > 1
Later on creating SSRS report should be quite easy.

Multiple Joins in TSQL

I am trying to JOIN multiple tables to the same value in a table. So I have the table ActivityPartyBase and it has a column PartyId. I want to join COntactId in ContactBase table to PartyId and AccountId in AccountBase table to PartyId. This is the code I am using and it doesn't return anything. If I only join one it works. Any ideas?
SELECT DISTINCT Appointment.ScheduledStart, ActivityPartyBase.ActivityId
, Appointment.ActivityId AS Expr1, ActivityPartyBase.ScheduledStart AS Expr2
, Appointment.Subject, ActivityPartyBase.PartyId, ContactBase.ContactId
, ContactBase.FullName
FROM Appointment
INNER JOIN ActivityPartyBase
ON Appointment.ActivityId = ActivityPartyBase.ActivityId
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId
ORDER BY Appointment.ScheduledStart DESC
Your inner joins are filtering out results because there is no corresponding record on the joined table. I've always found the easiest way to debug is to "Select *" and use all LEFT JOINs. This will show you everything in your tables that relates to your main table; you should be able to look at your data and figure out what table is missing a record easily at that point.
To confirm that this is just a naming convention mismatch,
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
Are PartyID and AccountId the PK/FK?
Given this...
FROM Appointment
INNER JOIN ActivityPartyBase ON Appointment.ActivityId = ActivityPartyBase.ActivityId
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId
... you state this works (?) ...
FROM Appointment
INNER JOIN ActivityPartyBase ON Appointment.ActivityId = ActivityPartyBase.ActivityId
/* INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId */
/* LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId */
Since the LEFT OUTER JOIN won't explicitly cause no results, that won't be your problem. Since the INNER JOIN will cause what you're seeing, we can only deduce that the join condition is incorrect.
In other words, ActivityPartyBase.PartyId is not equal to AccountBase.AccountID.
Are you sure there is data in all three tables in the inner join?
I'm guessing one of your INNER JOINs isn't picking up any data. Start with all 3 joins, then take out one of the joins at a time see which one breaks it. Then look at your join conditions and see which column isn't returning a record.
SOunds to me as if the tables are mutually exclusive. If it is ione table it is not inthe other (poor design). Try left joins to both tables.

Resources