I have 3 tables
CREATE TABLE [Distributors]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
)
INSERT INTO [Distributors]([Name]) VALUES ('A')
INSERT INTO [Distributors]([Name]) VALUES ('B')
CREATE TABLE [Points]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Distributor_ID] [int] NULL,
[Point_Count] [int] NULL,
[Point_Type] [nvarchar](max) NULL,
[Point_Level] [int] NULL,
[From_Distributor] [int] NULL,
[Is_Calculated] [bit] NULL,
[Point_Date] [datetime]
)
INSERT INTO [Points] ([Distributor_ID], [Point_Count], [Point_Type],[Point_Level], [From_Distributor], [Is_Calculated], [Point_Date])
VALUES(1, 1, 'AN', '', 2, 'True', '2015-02-16')
INSERT INTO [Points] ([Distributor_ID], [Point_Count], [Point_Type],[Point_Level], [From_Distributor], [Is_Calculated], [Point_Date])
VALUES(1, 1, 'Offer', '', 2, 'True', '2015-02-16')`
CREATE TABLE [dbo].[Profit]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Distributor_ID] [int] NULL,
[Profit] [decimal](18, 2) NULL,
[Percentage] [int] NULL,
[Profit_Date] [datetime] NULL,
[From_Distributor_ID] [int] NULL,
[Is_Paid] [bit] NULL,
[Paid_By] [int] NULL
)
INSERT INTO [Profit]([Distributor_ID], [Profit], [Percentage],[Profit_Date], [From_Distributor_ID], [Is_Paid], [Paid_By])
VALUES (1, '80', 10, '2015-02-16', 2, 'False', 0)
INSERT INTO [Profit]([Distributor_ID], [Profit], [Percentage],[Profit_Date], [From_Distributor_ID], [Is_Paid], [Paid_By])
VALUES (1, '40', 5, '2015-02-16', 2, 'False', 0)
When I do the select query with join statement I face a duplication
SELECT distinct Points.[ID]
,Points.[Distributor_ID]
,[Point_Count]
,[Point_Type]
,[Point_Level]
,[From_Distributor]
,[Is_Calculated]
,[Point_Date]
--,Profit.Profit
FROM
[Points]
INNER JOIN
Profit ON Points.From_Distributor = Profit.From_Distributor_ID
AND Points.Distributor_ID = Profit.Distributor_ID
WHERE
(Points.[Distributor_ID] = 1)
AND ([Point_Date] >= '2/16/2015')
AND ([Point_Date] <= '2/28/2015')
results are tow rows
when using " Profit.Profit " in the select statement it got 4 rows
i think problem in join statement
please i need your advice
Related
I have been tasked with getting some data out of another database not designed by me, so the design cannot be altered.
Looking at the data I need to join a table dynamically based on the value held in another table.
E.G
SELECT * FROM TableA LEFT JOIN TableB oN TableA.TBID = TableB.ID LEFT JOIN TableB.TableOffset AS C ON C.TableAID = TableA.ID
So table B has a column called TableOffset, this holds the name of the table that needs to be joined on as C
(I've tried to do an SQLFIDDLE but the site isn't working with SQL Server ATM)
The issue is there are 112 attribute tables where the data could be, so doing a left join for every one of them would slow down the query I imagine.
So based on the below I would need to get a result set of:
| TableAID | TableATitle | AttrTableA21 | AttrTableA22 |
|----------|-------------|--------------|--------------|
|1 |test | Name | 2019 |
|2 |test2 | Name 2 | 2016 |
Example SQL Code
CREATE TABLE [dbo].[TableA](
[ID] [int] NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[TableBID] [int] NOT NULL
);
CREATE TABLE [dbo].[TableB](
[ID] [int] NOT NULL,
[TableName] [nvarchar](100) NOT NULL
);
CREATE TABLE [dbo].[ATTR_A](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_B](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_C](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_D](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
INSERT INTO TableA VALUES(1, 'test', 1);
INSERT INTO TableB VALUES(1, 'ATTR_C');
INSERT INTO ATTR_C VALUES (1, 1, 'Name', 2019);
INSERT INTO TableA VALUES(2, 'test2', 2);
INSERT INTO TableB VALUES (2, 'ATTR_A');
INSERT INTO ATTR_A VALUES (1, 2, 'Name 2', 2016);
```
You were told already, that this approach is the wrong one entirely. But if you have to stick with this, you might try this:
Your test scenario in a new database (carefull, if you use this database name already...)
USE master;
GO
CREATE DATABASE MyTestDb;
GO
USE MyTestDb;
GO
CREATE TABLE [dbo].[TableA](
[ID] [int] NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[TableBID] [int] NOT NULL
);
CREATE TABLE [dbo].[TableB](
[ID] [int] NOT NULL,
[TableName] [nvarchar](100) NOT NULL
);
CREATE TABLE [dbo].[ATTR_A](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_B](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_C](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
CREATE TABLE [dbo].[ATTR_D](
[ID] [int] NOT NULL,
[TableAID] [int] NOT NULL,
[A21] [nvarchar](100) NOT NULL,
[A22] [int] NOT NULL
);
INSERT INTO TableA VALUES(1, 'test', 1);
INSERT INTO TableB VALUES(1, 'ATTR_C');
INSERT INTO ATTR_C VALUES (1, 1, 'Name', 2019);
INSERT INTO TableA VALUES(2, 'test2', 2);
INSERT INTO TableB VALUES (2, 'ATTR_A');
INSERT INTO ATTR_A VALUES (1, 2, 'Name 2', 2016);
GO
--I create an inlined table valued function where all attribute tables are returned as one set using UNION ALL
--The engine is smart enough, to avoid the call, if the parameter does not fit.
CREATE FUNCTION dbo.GetTheRightSet(#SetKey VARCHAR(10))
RETURNS TABLE
AS
RETURN
SELECT ID,TableAID,A21,A22 FROM dbo.ATTR_A WHERE #SetKey='ATTR_A'
UNION ALL
SELECT ID,TableAID,A21,A22 FROM dbo.ATTR_B WHERE #SetKey='ATTR_B'
UNION ALL
SELECT ID,TableAID,A21,A22 FROM dbo.ATTR_C WHERE #SetKey='ATTR_C'
UNION ALL
SELECT ID,TableAID,A21,A22 FROM dbo.ATTR_D WHERE #SetKey='ATTR_D'
GO
--This is how to use it
SELECT TableA.*
,TableB.*
,TheSet.*
FROM TableA
LEFT JOIN TableB ON TableA.TableBID = TableB.ID
OUTER APPLY dbo.GetTheRightSet(TableB.TableName) TheSet
GO
--Clean up (carefull with real data)
USE master;
GO
DROP DATABASE MyTestDb;
I'm trying to find all customers who have placed an order but there isn't a callback after their last order date.
My current query:
SELECT dbo.[Order].CustomerId, MAX(OrderDate) AS OrderDate, NextCallbackDate, UserName
FROM dbo.[Order]
LEFT OUTER JOIN (SELECT MAX(CallbackDate) NextCallbackDate, CustomerID
FROM AccountCallbacks
GROUP By CustomerId
) callbacks ON callbacks.CustomerID = dbo.[Order].CustomerID
LEFT OUTER JOIN dbo.aspnet_Users users ON dbo.[Order].UserID = users.UserId
WHERE (PaymentTypeID IN (2, 3, 4, 6, 8))
AND OrderDate >= NextCallbackDate
GROUP BY dbo.[Order].CustomerID, dbo.[Order].OrderDate,callbacks.NextCallbackDate, UserName
ORDER BY dbo.[Order].CustomerID
Tables:
AccountCallBacks:
[CallbackID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [uniqueidentifier] NOT NULL,
[CustomerID] [int] NOT NULL,
[Created] [datetime] NOT NULL,
[CallbackDate] [date] NOT NULL,
[Enabled] [bit] NOT NULL,
[CallbackTimeID] [int] NULL,
[GaryCust] [bit] NULL,
[NotInterestedReasonID] [int] NULL
Order Table:
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NULL,
[UserID] [uniqueidentifier] NULL,
[OrderDate] [datetime] NOT NULL,
[PaymentTypeID] [int] NULL,
[PaymentStatusID] [int] NOT NULL,
[PaymentDate] [datetime] NULL,
[TransactionRef] [varchar](50) NULL
And the aspnet_Users table is the usual .net membership users table
EDIT:
Apologies! I never actual said what was wrong! My query doesn't give me what I'm expecting one of the rows of data for a particular CustomerID isn't in the result set. And no, there should always be at least one AccountCallbacks.CallbackDate for every CustomerID as I'm joining on the dbo.[Order] table and they wouldn't be in there without first ever being in the AccountCallbacks table.
Feel free to ask any other info, help is greatly appreciated.
I have 2 tables,each contains 4-500k records
CREATE TABLE [dbo].[User][UserId] [int] IDENTITY(1,1) NOT NULL,
[Password] [nvarchar](max) NULL,
[RoleId] [int] NOT NULL,
[Name] [nvarchar](max) NULL,
[Address] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL,
[Landline] [nvarchar](max) NULL,
[MobileNumberCode] [int] NULL,
[MobileNumber] [nvarchar](max) NULL,
[DateOfBirth] [datetime] NULL,
[MarriageDate] [datetime] NULL,
[CreatedDate] [datetime] NOT NULL,
[UpdatedDate] [datetime] NOT NULL,
[Status] [nvarchar](max) NOT NULL,
[BranchId] [int] NULL,
[UserTitle] [nvarchar](50) NULL,
[MiddleName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[HouseNumber] [nvarchar](50) NULL,
[BuildingNumber] [nvarchar](50) NULL,
[RoadNumber] [nvarchar](50) NULL,
[BlockNumber] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[NearBranchId] [int] NULL,
[MobileIsValid] [bit] NULL,
[EmailIsValid] [bit] NULL,
[Gender] [nvarchar](50) NULL,
[SourceId] [int] NULL)
CREATE TABLE [dbo].[PurchaseOrder]
[PurchaseOrderId] [int] NOT NULL,
[BranchId] [int] NOT NULL,
[PurchaseDate] [datetime] NOT NULL,
[Amount] [decimal](18, 3) NOT NULL,
[UserId] [int] NOT NULL,
[Status] [nvarchar](max) NULL,
[sbs_no] [int] NOT NULL)
And I have stored procedure to get data from these tables using join.
CREATE PROC Sp_SearchCustomer (#FromDate datetime = null,
#ToDate datetime = null,
#RegFromDate datetime = null,
#RegToDate datetime = null)
AS
BEGIN
select a.UserId,a.Name,b.PurchaseOrderId,b.Amount from dbo.[User] a left join PurchaseOrder b on a.UserId=b.UserId
where
((a.CreatedDate >= ''' + cast(#RegFromDate as varchar) + ''')
AND (a.CreatedDate <= ''' + cast(#RegToDate as varchar) + '''))
and ((b.PurchaseDate >= ''' + cast(#FromDate as varchar) + ''')
AND (b.PurchaseDate <= ''' + cast(#ToDate as varchar) + '''))
END
When executing this procedure with date, its getting "The wait operation timed out" exception. Please help to solve this issue.
Your date in your tables and in your Procedure are both saved as varchar. This is perfect and there is no need to convert them to varchar.
Beside, varchar is surrounded by quotes and won't be executed. This is just becoming a string:
where ((a.CreatedDate >= 'cast(#RegFromDate as varchar)')...
There are also way too many useless parenthesis since you are using AND.
Try this instead:
CREATE PROC Sp_SearchCustomer (
#FromDate datetime = null,
#ToDate datetime = null,
#RegFromDate datetime = null,
#RegToDate datetime = null
)
AS
BEGIN
SELECT a.UserId
,a.Name
,b.PurchaseOrderId
,b.Amount
FROM dbo.[User] a
LEFT JOIN PurchaseOrder b
ON a.UserId = b.UserId
WHERE
a.CreatedDate >= #RegFromDate
AND a.CreatedDate <= #RegToDate
AND b.PurchaseDate >= #FromDate
AND b.PurchaseDate <= #ToDate
END
Once the query has been improved, you can test it again.
You should also look at Statistics and Indexes and make sure that Statistics are up-to-date and Indexes are not fragmented.
For Statistics, you can use: exec sp_updatestats
For Indexes on these 2 tables, look at the Fragmentation % and choose to REBUILD or REORGANIZE them.
select
a.COUNTY_FIPS
,COUNT(e.PROPERTY_ID) as house_count
,AVG(cast(e.AVM_FINAL_VALUE as bigint)) as avg_avm
,max(cast(e.AVM_FINAL_VALUE as bigint)) as max_avm
,min(cast(e.AVM_FINAL_VALUE as bigint)) as min_avm
from
RAW_Equity e
left join
(SELECT
SA_PROPERTY_ID, MM_FIPS_STATE_CODE, MM_FIPS_MUNI_CODE,
CASE
WHEN MM_FIPS_STATE_CODE < 10
THEN '0' + CAST(MM_FIPS_STATE_CODE as VARCHAR)
ELSE CAST(MM_FIPS_STATE_CODE as VARCHAR)
END
+ CASE
WHEN MM_FIPS_MUNI_CODE < 10
THEN '00' + CAST(MM_FIPS_MUNI_CODE as VARchar)
WHEN MM_FIPS_MUNI_CODE < 100
THEN '0' + CAST(MM_FIPS_MUNI_CODE as VARchar)
ELSE CAST(MM_FIPS_MUNI_CODE as VARchar)
END AS COUNTY_FIPS
FROM
RAW_Address) a ON a.SA_PROPERTY_ID = e.PROPERTY_ID
where
AVM_CONFIDENCE_SCORE >= 70
group by
a.COUNTY_FIPS
Is there any way I can improve the performance of this query? Schema for both the tables are shown below. I am was thinking about creating non clustered index on AVM_CONFIDENCE_SCORE but I think it will only going to increase the query time. Any help will be greatly appreciated.
RAWADDRESS table:
CREATE TABLE [dbo].[RAW_Address]
(
[SA_PROPERTY_ID] [int] NOT NULL,
[SA_SCM_ID] [int] NOT NULL,
[MM_STATE_CODE] [varchar](2) NOT NULL,
[MM_MUNI_NAME] [varchar](24) NOT NULL,
[MM_FIPS_STATE_CODE] [tinyint] NOT NULL,
[MM_FIPS_MUNI_CODE] [smallint] NOT NULL,
[MM_FIPS_COUNTY_NAME] [varchar](35) NOT NULL,
[SA_SITE_HOUSE_NBR] [varchar](20) NULL,
[SA_SITE_FRACTION] [varchar](10) NULL,
[SA_SITE_DIR] [varchar](2) NULL,
[SA_SITE_STREET_NAME] [varchar](40) NULL,
[SA_SITE_SUF] [varchar](4) NULL,
[SA_SITE_POST_DIR] [varchar](2) NULL,
[SA_SITE_UNIT_PRE] [varchar](10) NULL,
[SA_SITE_UNIT_VAL] [varchar](6) NULL,
[SA_SITE_CITY] [varchar](30) NULL,
[SA_SITE_STATE] [varchar](2) NOT NULL,
[SA_SITE_ZIP] [int] NULL,
[SA_SITE_PLUS_4] [smallint] NULL,
[SA_SITE_CRRT] [varchar](4) NULL,
[SA_MAIL_HOUSE_NBR] [varchar](20) NULL,
[SA_MAIL_FRACTION] [varchar](10) NULL,
[SA_MAIL_DIR] [varchar](2) NULL,
[SA_MAIL_STREET_NAME] [varchar](50) NULL,
[SA_MAIL_SUF] [varchar](4) NULL,
[SA_MAIL_POST_DIR] [varchar](2) NULL,
[SA_MAIL_UNIT_PRE] [varchar](10) NULL,
[SA_MAIL_UNIT_VAL] [varchar](6) NULL,
[SA_MAIL_CITY] [varchar](50) NULL,
[SA_MAIL_STATE] [varchar](2) NULL,
[SA_MAIL_ZIP] [int] NULL,
[SA_MAIL_PLUS_4] [smallint] NULL,
[SA_MAIL_CRRT] [varchar](4) NULL,
[SA_SITE_MAIL_SAME] [varchar](1) NULL
) ON [PRIMARY]
RAW Equity table:
CREATE TABLE [dbo].[RAW_Equity]
(
[PROPERTY_ID] [int] NOT NULL,
[SCM_ID] [int] NOT NULL,
[MM_STATE_CODE] [varchar](2) NOT NULL,
[MM_MUNI_NAME] [varchar](24) NOT NULL,
[MM_FIPS_STATE_CODE] [int] NOT NULL,
[MM_FIPS_MUNI_CODE] [int] NOT NULL,
[MM_FIPS_COUNTY_NAME] [varchar](35) NOT NULL,
[AVM_FINAL_VALUE] [int] NULL,
[AVM_LOW_VALUE] [int] NULL,
[AVM_HIGH_VALUE] [int] NULL,
[AVM_CONFIDENCE_SCORE] [int] NULL,
[FINAL_VALUE] [float] NULL,
[FIRST_POSITION_SR_UNIQUE_ID] [int] NULL,
[FIRST_POSITION_LOAN_DATE] [int] NULL,
[FIRST_POSITION_DOC_NBR] [varchar](20) NULL,
[FIRST_POSITION_LOAN_VAL] [int] NULL,
[FIRST_POSITION_LENDER_CODE] [int] NULL,
[FIRST_POSITION_LNDR_LAST_NAME] [varchar](50) NULL,
[FIRST_POSITION_LNDR_FIRST_NAME] [varchar](50) NULL,
[FIRST_POSITION_LENDER_TYPE] [varchar](1) NULL,
[FIRST_POSITION_LOAN_TYPE] [varchar](1) NULL,
[FIRST_POSITION_INTEREST_RATE_TYPE] [varchar](1) NULL,
[FIRST_POSITION_ESTIMATED_INTEREST_RATE] [float] NULL,
[FIRST_POSITION_LNDR_CREDIT_LINE] [varchar](1) NULL,
[FIRST_POSITION_MODELED_MORTGAGE_TYPE] [varchar](1) NULL,
[SECOND_POSITION_SR_UNIQUE_ID] [int] NULL,
[SECOND_POSITION_LOAN_DATE] [int] NULL,
[SECOND_POSITION_DOC_NBR] [varchar](20) NULL,
[SECOND_POSITION_LOAN_VAL] [int] NULL,
[SECOND_POSITION_LENDER_CODE] [int] NULL,
[SECOND_POSITION_LNDR_LAST_NAME] [varchar](50) NULL,
[SECOND_POSITION_LNDR_FIRST_NAME] [varchar](50) NULL,
[SECOND_POSITION_LENDER_TYPE] [varchar](1) NULL,
[SECOND_POSITION_LOAN_TYPE] [varchar](1) NULL,
[SECOND_POSITION_INTEREST_RATE_TYPE] [varchar](1) NULL,
[SECOND_POSITION_ESTIMATED_INTEREST_RATE] [float] NULL,
[SECOND_POSITION_LNDR_CREDIT_LINE] [varchar](1) NULL,
[SECOND_POSITION_MODELED_MORTGAGE_TYPE] [varchar](1) NULL,
[THIRD_POSITION_SR_UNIQUE_ID] [int] NULL,
[THIRD_POSITION_LOAN_DATE] [int] NULL,
[THIRD_POSITION_DOC_NBR] [varchar](20) NULL,
[THIRD_POSITION_LOAN_VAL] [int] NULL,
[THIRD_POSITION_LENDER_CODE] [int] NULL,
[THIRD_POSITION_LNDR_LAST_NAME] [varchar](50) NULL,
[THIRD_POSITION_LNDR_FIRST_NAME] [varchar](50) NULL,
[THIRD_POSITION_LENDER_TYPE] [varchar](1) NULL,
[THIRD_POSITION_LOAN_TYPE] [varchar](1) NULL,
[THIRD_POSITION_INTEREST_RATE_TYPE] [varchar](1) NULL,
[THIRD_POSITION_ESTIMATED_INTEREST_RATE] [float] NULL,
[THIRD_POSITION_LNDR_CREDIT_LINE] [varchar](1) NULL,
[THIRD_POSITION_MODELED_MORTGAGE_TYPE] [varchar](1) NULL,
[TOTAL_OUTSTANDING_LOANS] [bigint] NULL,
[LTV] [int] NULL,
[AVAILABLE_EQUITY] [int] NULL,
[LENDABLE_EQUITY] [int] NULL,
[PROCESS_ID] [int] NOT NULL,
[FILLER] [varchar](4) NULL,
CONSTRAINT [PK_RAW_Equity] PRIMARY KEY CLUSTERED
(
[PROPERTY_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
You could try this way :-
(willing to know, how much this one, helpful to you)
Declare #result Table
(
RowId Int Identity(1,1) Primary Key
,COUNTY_FIPS Varchar(100)
,MM_FIPS_STATE_CODE Int
,MM_FIPS_MUNI_CODE Int
,house_count Int
,avg_avm Int
,max_avm Int
,min_avm Int
)
Insert Into #result(MM_FIPS_STATE_CODE,MM_FIPS_MUNI_CODE,house_count,avg_avm,max_avm,min_avm)
Select a.MM_FIPS_STATE_CODE
,a.MM_FIPS_MUNI_CODE
,Count(e.PROPERTY_ID) as house_count
,Avg(Cast(e.AVM_FINAL_VALUE as bigint)) as avg_avm
,Max(Cast(e.AVM_FINAL_VALUE as bigint)) as max_avm
,Min(Cast(e.AVM_FINAL_VALUE as bigint)) as min_avm
From RAW_Equity As e With (Nolock)
Left Join RAW_Address As a With (Nolock) On e.PROPERTY_ID = a.SA_PROPERTY_ID
Where e.AVM_CONFIDENCE_SCORE >= 70
Group by a.MM_FIPS_STATE_CODE
,a.MM_FIPS_MUNI_CODE
Update r
Set r.COUNTY_FIPS = REPLICATE('0',2-LEN(RTRIM(r.MM_FIPS_STATE_CODE))) + RTRIM(r.MM_FIPS_STATE_CODE) + REPLICATE('0',3-LEN(RTRIM(r.MM_FIPS_MUNI_CODE))) + RTRIM(r.MM_FIPS_MUNI_CODE)
From #result As r
Select r.COUNTY_FIPS
,r.house_count
,r.avg_avm
,r.max_avm
,r.min_avm
From #result As r
1st try without any index, and after that create clustered index as mentioned and try AGAIN the above same query
CREATE INDEX IX_RAW_Address_SA_PROPERTY_ID ON RAW_Address(SA_PROPERTY_ID)
I would put an index on:
Table: RAW_Equity
Columns: PROPERTY_ID, AVM_CONFIDENCE_SCORE
and
Table: RAW_Address
Columns: SA_PROPERTY_ID
Include: MM_FIPS_STATE_CODE,MM_FIPS_MUNI_CODE
Your query can be simplified, which will likely make it faster:
select
REPLICATE('0',2-LEN(RTRIM(a.MM_FIPS_STATE_CODE)))
+ RTRIM(a.MM_FIPS_STATE_CODE)
+ REPLICATE('0',3-LEN(RTRIM(a.MM_FIPS_MUNI_CODE)))
+ RTRIM(a.MM_FIPS_MUNI_CODE)
AS COUNTY_FIPS
,COUNT(e.PROPERTY_ID) as house_count
,AVG(cast(e.AVM_FINAL_VALUE as bigint)) as avg_avm
,max(cast(e.AVM_FINAL_VALUE as bigint)) as max_avm
,min(cast(e.AVM_FINAL_VALUE as bigint)) as min_avm
from
RAW_Equity e
left join RAW_Address a
ON a.SA_PROPERTY_ID = e.PROPERTY_ID
where
e.AVM_CONFIDENCE_SCORE >= 70
group by
a.MM_FIPS_STATE_CODE, a.MM_FIPS_MUNI_CODE
If RAW_Address doesn't already have a CLUSTERED INDEX with SA_PROPERTY_ID as the first key of the index, then this may help:
CREATE INDEX IX_RAW_Address_SA_PROPERTY_ID ON RAW_Address(SA_PROPERTY_ID)
INCLUDE (MM_FIPS_STATE_CODE, MM_FIPS_MUNI_CODE)
When you have 2 tables table like this
CREATE TABLE #BranchType
(
[External_BranchTypeID] [uniqueidentifier] DEFAULT newsequentialid() NOT NULL,
[BranchTypeID] [smallint] identity(1,1) ,
[BranchTypeDescription] [nvarchar](20) NOT NULL,
[DateCreated] [datetime] NOT NULL,
[UserCreated] [nvarchar](20) NOT NULL,
[DateModified] [datetime] NULL,
[UserModified] [nvarchar](20) NULL,
[IsDeleted] [bit] NOT NULL,
)
CREATE TABLE BranchSubType
(
[External_BranchSubTypeID] [uniqueidentifier] DEFAULT newsequentialid() NOT NULL,
[BranchSubTypeID] [smallint] identity(1,1) ,
[BranchTypeID] [uniqueidentifier] NOT NULL,
[BranchSubTypeDescription] [nvarchar](30) NOT NULL,
[FinancialSystemTypeId] [smallint] NOT NULL,
[DateCreated] [datetime] NOT NULL,
[UserCreated] [nvarchar](20) NOT NULL,
[DateModified] [datetime] NULL,
[UserModified] [nvarchar](20) NULL,
[IsDeleted] [bit] NOT NULL,
)
How can you do an insert like the one below in SQL Server? I am trying to return the guid value
DECLARE #SQLCmd VARCHAR(max)
set #SQLCmd = 'SELECT External_BranchTypeID FROM #BranchType WHERE BranchTypeID =1'
INSERT INTO BranchSubType (BranchTypeID, BranchSubTypeDescription, BranchSubTypeId, DateCreated, UserCreated,IsDeleted)
VALUES ( exec(#SQLCmd), 'Normal',1, getdate(), 'System',0) --FROM #BranchType A WHERE A.BranchTypeID = 1
In this case you don't need to use EXEC
INSERT INTO BranchSubType
(BranchTypeID,
BranchSubTypeDescription,
BranchSubTypeId,
DateCreated,
UserCreated,
IsDeleted)
SELECT External_BranchTypeID,
'Normal',
1,
getdate(),
'System',
0
FROM #BranchType WHERE BranchTypeID =1