Joining view and tables in sql server - sql-server

I have the following tables.
Customer Customer_id, Customer_name
Customer_details Customer_id,Phone_no,Address
Order_details Order_id,Customer_id,Order_type
I have created a view as following
Create view Orders_Analysis
Select c.Customer_id,cd.phone_no,od.order_id
From customer c
inner join order_details od
on c. Customer_id=od. Customer_id
Inner join Where c. Customer_id=cd. Customer_id
cd. Customer_id=c.Customer_id
Now using the above view and pre mentioned tables I have to extract only those records in the view which are of a particular order_type.
Can you guys suggest me a method.

First of all, You have some mistake in View, This is the correct View after fix mistakes
Create view Orders_Analysis
Select c.Customer_id,cd.phone_no,od.order_id
From customer c
INNER JOIN order_details od
ON c.Customer_id = od.Customer_id
INNER JOIN Customer_details CD
ON c.Customer_id = cd.Customer_id
Now You want to extract only those records in the view which are of a particular order_type.
Solution One:- Because you dont have column order_type in View then use INNER JOIN
SELECT *
FROM Orders_Analysis OA
INNER JOIN Order_details OD
ON OA.order_id = OD.order_id
WHERE OD.Order_type = your value here
Solution Two:-
Otherwise Add Order-Type column in View
Create view Orders_Analysis
Select c.Customer_id,cd.phone_no,od.order_id,od.order_type
From customer c
INNER JOIN order_details od
ON c.Customer_id = od.Customer_id
INNER JOIN Customer_details CD
ON c.Customer_id = cd.Customer_id
and use
Select * from Orders_Analysis where Order_Type = your value here

You need to add the field, od.order_type, to the Select statement results set in your view definition:
SELECT c.Customer_id,cd.phone_no,od.order_id,od.Order_type
Then, if you run a select against the view, specify a WHERE clause on the order_type field for the value you are looking for.

Update your view and select also order type
Select c.Customer_id,cd.phone_no,od.order_id, od.Order_type
You can now execute select query using the view you created
Select * from Orders_Analysis where Order_Type = "any value"

Related

Stored procedure outputting duplicate records with multiple inner joins

I am creating a stored procedure and would like to inner join between 4 different tables. The tables are names:
Category, SubCategory, Project, VisUser
SubCategory depends on Category and VisUser while Project depends on SubCategory.
When I run my stored procedure with the 3 inner joins, it returns the correct information - just duplicated 3 times.
I tried using distinct in the beginning and it does work to filter the records correctly however it may still run slow when running with a large amount of data with it outputting 3x the records.
Stored procedure:
DROP PROCEDURE IF EXISTS GetAllProjects
GO
CREATE PROCEDURE GetAllProjects
(#UserId INT)
AS
BEGIN
SELECT DISTINCT
proj.ProjectName, proj.ProjectDescription, sub.SubCategoryName
FROM
SubCategory AS sub
INNER JOIN
VisUser AS vis ON #UserId = sub.UserId
INNER JOIN
Category AS cat ON cat.CategoryId = sub.CategoryId
INNER JOIN
Project AS proj ON proj.SubCategoryId = sub.SubCategoryId
END
What part am I doing wrong here? I have a feeling it is because I am using 'sub' 3x in the inner joins. Is there a better approach for this?
INNER JOIN VisUser AS vis ON #UserId = sub.UserId
Will join on all VisUsers because you don't reference the table in the join condition.
As you don't actually use the VisUsers table just remove it as follows:
SELECT
DISTINCT proj.ProjectName, proj.ProjectDescription, sub.SubCategoryName
FROM SubCategory AS sub
INNER JOIN Category AS cat ON cat.CategoryId = sub.CategoryId
INNER JOIN Project AS proj ON proj.SubCategoryId = sub.SubCategoryId
WHERE sub.UserId = #UserId;
And if you do need the VisUsers table you can join on like this:
SELECT
DISTINCT proj.ProjectName, proj.ProjectDescription, sub.SubCategoryName
FROM SubCategory AS sub
INNER JOIN VisUser AS vis ON vis.UserId = sub.UserId
INNER JOIN Category AS cat ON cat.CategoryId = sub.CategoryId
INNER JOIN Project AS proj ON proj.SubCategoryId = sub.SubCategoryId
WHERE sub.UserId = #UserId;

How to optimize view performance in SQL Server 2012 by indexing

I have a view like that:
create view dbo.VEmployeeSalesOrders
as
select
employees.employeeID, Products.productID,
Sum(Price * Quantity) as Total,
salesDate,
COUNT_BIG() as [RecordCount]
from
dbo.Employees
inner join
dbo.sales on employees.employeeID = sales.employeeID
inner join
dbo.products on sales.productID = products.ProductID
group by
Employees.employeeID, products.ProductID, salesDate
When I select * from dbo.VEmployeeSalesOrders it takes 97% of the execution plan. It needs it to be faster.
And when I try to create an index, an exception fires with the following message:
select list doesn't include a proper use on count_Big()
Why am getting this error?
1-first you need to alter your view and make it contains COUNT_BIG() function because you used aggregate function in select statment,
AND THE REASON FOR USING THAT is that SQL Server needs to track the record where the record is ,number of records
like this
create view dbo.VEmployeeSalesOrders
as
select employees.employeeID,Products.productID,Sum(Price*Quantity)
as Total,salesDate,COUNT_BIG(*) as [RecordCount]
from dbo.Employees
inner join dbo.sales on employees.employeeID=sales.employeeID
inner join dbo.products on sales.productID-products.ProductID
group by Employees.employeeID,products.ProductID,salesDate
2- then you need to create index like that
Create Unique Clustered Index Cidx_IndexName
on dbo.VEmployeeSalesOrders(employedID,ProductID,SalesDate)
Hope It Works

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.

How do I build a query that crosses multiple tables?

Here are my tables:
CUSTOMER
Cust_ID (PK)
Name
ORDERS
Order_ID (PK)
Cust_ID (FK)
ORDER_LINE
Order_ID (pk)
Part_ID (FK)
PART
Part_ID (PK)
Part_Description
Now I want to list the customer details, the part number and the description of the parts that each customer ordered.
How do i do this?
Thanks.
You should use "JOIN" using the FK, but from what I see you don't have a foreign key between "ORDERS" and "ORDER_LINE". Are you sure you're not missing something from the table definition, ie: ORDER_LINE should maybe have the ORDER_ID as a FK ?
Hope this helps
You can try something like
SELECT c.*,
p.*
FROM CUSTOMER c INNER JOIN
ORDERS o ON c.Cust_ID = o.Cust_ID INNER JOIN
ORDER_LINE ol ON o.Order_ID = ol.Order_Number INNER JOIN
PART p ON ol.Part_Number = p.Part_Number
Have a look at
Join (SQL)
An SQL join clause combines records from two or more tables in a
database.
SQL Joins
The JOIN keyword is used in an SQL statement to query data from two or
more tables, based on a relationship between certain columns in these
tables.
And for some graphic examples
JOIN Basics
What you need is a simple straightforward JOIN like so:
SELECT
c.Cust_ID,
c.Name,
l.Part_Number,
l.Part_Description
FROM CUSTOMER c
INNER JOIN ORDERS o ON c.Cust_ID = o.Cust_ID
INNER JOIN ORDER_LINE ol ON o.OrdeR_ID = ol.Order_Number
INNER JOIN PART l ON ol.Part_Number = l.Part_Number
You want an SQL "join", such as:
SELECT c.Name, ol.Part_Number, p.Part_Description
FROM Customer AS c
JOIN Orders AS o ON c.Cust_ID = o.Cust_ID
JOIN Order_Line AS ol ON o.Order_ID = ol.Order_Number
JOIN Part AS p ON ol.Part_Number = p.Part_Number
Be aware that without a WHERE clause, this query will return all all parts in all orders for all customers, which will really hammer the network and perform poorly on anything but a tiny database:
WHERE (c.Cust_ID = MyCustomerID)
MySQL join syntax
SQL Server join syntax

Can I select all the tables with more than one update trigger

Can I select all the tables with more than one update trigger? The following code selects all the tables with more than one trigger, but I need only the tables with more than one update trigger.
This query also returns tables with one insert trigger and one update one, which is not what I want.
SELECT * FROM sys.triggers
WHERE parent_id IN(SELECT parent_id
FROM sys.triggers
GROUP BY parent_id
HAVING COUNT(*)>1)
You should be able to tell this from sys.trigger_events, e.g:
SELECT *
FROM sys.trigger_events AS te
INNER JOIN sys.triggers AS t
ON t.[object_id] = te.[object_id]
WHERE te.[type] IN (1,2,3);
So to get tables with more than one update trigger:
SELECT OBJECT_NAME(parent_id)
FROM sys.triggers AS t
INNER JOIN sys.trigger_events AS te
ON t.[object_id] = te.[object_id]
WHERE te.type_desc = 'UPDATE'
GROUP BY OBJECT_NAME(parent_id)
HAVING COUNT(*) > 1;
Not very reliable, but it should work if you need something quick and dirty.
SELECT * FROM sys.triggers
WHERE parent_id IN
(SELECT parent_id
FROM sys.triggers tt
JOIN sys.syscomments sc on sc.id=tt.object_id
WHERE sc.text LIKE '%AFTER UPDATE%'
GROUP BY parent_id
HAVING COUNT(*)>1)

Resources