Choice of Clustered and Non-Clustered Index in SQL Server - sql-server

I have two standalone tables Person and Bank in one database. Moreover I have a reference table Customers in another database.
Table: Person - Database #1
PersonId (PK) Name
_________________________________
1 Ram
2 Raj
3 John
4 Emma
Table: Bank - Database #1
BankId (PK) Name
_________________________________
1 ICICI
2 HDFC
3 SBI
Table: Customers - Database #2
CustomerId (PK) BankId PersonId UserName PIN
_____________________________________________________________
1 1 1 person1 7456bb
2 1 4 person4 NULL
3 2 1 person1 5691io
4 3 2 person2 7892yh
5 3 4 person4 1596pl
I need to execute the following queries efficiently, without INDEX it will do a FULL COLUMN search:
SELECT
c.CustomerId, p.Name, b.Name, c.UserName, c.PIN
FROM
DB2.Customers c
INNER JOIN
DB1.Person p ON p.PersonId = c.PersonId
INNER JOIN
DB1.Bank b ON b.BankId = c.BankId
SELECT *
FROM DB2.Customers c
WHERE c.UserName = 'person1'
SELECT *
FROM DB2.Customers c
WHERE c.UserName = 'person2' AND c.PIN = '7892yh'
So, I need a CREATE table SQL query for the table Customers. The following are the constraints
CustomerId int NOT NULL primary key
BankId int NOT NULL -- needs index and non-unique
PersonId int NOT NULL -- needs index and non-unique
UserName varchar(25) NOT NULL -- needs index and non-unique
PIN varchar(10) NULL -- needs index and non-unique
The said table don't have a FK relationship because the said table is in different database server. So, I need a efficient table structure to fetch records using JOIN. I don't know the which INDEX is efficient in this scenario either clustered nor non-clustered index.

Related

SQL Server : left outer join on two relations to 2 tables

I have 2 tables with primary keys and third or many table which references these 2 primary tables and have some extra values on one or both primary keys.
I need to create some SQL which will always deliver result with as much information as possible by joining these 3 tables. Best result - all 3 tables joined. Medium result - at least some primary keys (or both) are selected. Worst result all columns are null.
Main idea is to have combination of two primary tables and many extra tables which could be empty but should allow results from tables with values.
I tried to start with 3 tables but got stuck on second join.
It works for me only when I join first table. Joining second one produces error.
What should I use instead of ? as SQL statement?
http://sqlfiddle.com/#!18/7438b/3
CREATE TABLE [AGENCIES]
(
[AGENCY_NAME] [CHAR](9),
id INT IDENTITY(1,1) NOT NULL PRIMARY KEY
);
CREATE TABLE [PERSONS]
(
[NAME] [CHAR](9),
id INT IDENTITY(1,1) NOT NULL PRIMARY KEY
);
CREATE TABLE [AGENCY_PERSON]
(
agency_id INT FOREIGN KEY REFERENCES agencies(id),
person_id INT FOREIGN KEY REFERENCES persons(id),
[TITLE] [CHAR](9) NULL,
id INT IDENTITY(1,1) NOT NULL PRIMARY KEY
);
INSERT INTO agencies (AGENCY_NAME)
VALUES ('AgencyOne'), ('AgencyTwo'), ('Agency3');
INSERT INTO persons (name)
VALUES ('PersonOne'), ('PersonTwo'), ('Person3');
INSERT INTO AGENCY_PERSON (agency_id, person_id, title)
VALUES (1, 1, 'TitleOne'), (1, 2, 'TitleTwo');
SELECT * FROM AGENCY_PERSON;
-- works fine for one primary table
SELECT [AGENCY_NAME], [TITLE]
FROM agencies
LEFT OUTER JOIN [AGENCY_PERSON] ON [AGENCY_PERSON].agency_id = agencies.id
WHERE [AGENCY_NAME] = 'AgencyOne';
-- error for two primary tables: Msg 4104 - The multi-part identifier "agencies.id" could not be bound.
SELECT [AGENCY_NAME], [TITLE], persons.name
FROM agencies, persons
LEFT OUTER JOIN [AGENCY_PERSON] ON [AGENCY_PERSON].agency_id = agencies.id
AND [AGENCY_PERSON].person_id = persons.id
WHERE [AGENCY_NAME] = 'AgencyOne';
-- select ? 'AgencyOne' - all records exist
-- AgencyOne, TitleOne, PersonOne
-- select ? 'TitleTwo' - both records on primary tables exist, but no in join table
-- AgencyOne, TitleTwo, NULL
-- select ? 'Agency3' - one of primary tables exist
-- Agency3, NULL, NULL
-- select ? 'Title3' - one of primary tables exist
-- NULL, Title3, NULL
-- select ? 'AgencyX' - nothing exists
-- NULL, NULL, NULL
forpas gave good answer but it is in reverse. Extra tables are left joined by primary which requires extra tables exist and have values. What I need is opposite - extra tables should join primaries. For example it could be more extra tables like PERSON_PHONE, PERSON_ADDRES or AGENCY_PERSON_LOCATION. As soon as agency or person exist (but no values in these extra tables) result should be row with existing agency and person and nulls in all other columns from the joined tables.
Your code would work if you did not use that old style (cross) join:
from agencies, persons
So write it like this:
select a.[AGENCY_NAME], ap.[TITLE], p.name
from agencies as a cross join persons as p
left outer join [AGENCY_PERSON] as ap
on ap.agency_id = a.id and ap.person_id = p.id
where a.[AGENCY_NAME] = 'AgencyOne';
I used aliases for all the tables involved and I qualified all the columns with the aliases of the tables they belong.
Results:
> AGENCY_NAME | TITLE | name
> :---------- | :-------- | :--------
> AgencyOne | TitleOne | PersonOne
> AgencyOne | TitleTwo | PersonTwo
> AgencyOne | null | Person3
I'm not sure if this is what you want as output but I believe you see now how you can join all 3 tables.
In case you want only the matching rows of the tables, then you should do inner joins:
select a.[AGENCY_NAME], ap.[TITLE], p.name
from [AGENCY_PERSON] as ap
inner join agencies as a on ap.agency_id = a.id
inner join persons as p on ap.person_id = p.id
where a.[AGENCY_NAME] = 'AgencyOne';
Results:
> AGENCY_NAME | TITLE | name
> :---------- | :-------- | :--------
> AgencyOne | TitleOne | PersonOne
> AgencyOne | TitleTwo | PersonTwo
See the demo.

Lookup delimited values in a table in sql-server

In a table A i have a column (varchar*30) city-id with the value e.g. 1,2,3 or 2,4.
The description of the value is stored in another table B, e.g.
1 Amsterdam
2 The Hague
3 Maastricht
4 Rotterdam
How must i join table A with table B to get the descriptions in one or maybe more rows?
Assuming this is what you meant:
Table A:
id
-------
1
2
3
Table B:
id | Place
-----------
1 | Amsterdam
2 | The Hague
3 | Maastricht
4 | Rotterdam
Keep id column in both tables as auto increment, and PK.
Then just do a simple inner join.
select * from A inner join B on (A.id = B.id);
Ideal way to deal with such scenarios is to have a normalized table as Collin. In case that can't be done here is the way to go about -
You would need to use a table-valued function to split the comma-seperated value. If you are having SQL-Server 2016, there is a built-in SPLIT_STRING function, if not you would need to create one as shown in this link.
create table dbo.sCity(
CityId varchar(30)
);
create table dbo.sCityDescription(
CityId int
,CityDescription varchar(30)
);
insert into dbo.sCity values
('1,2,3')
,('2,4');
insert into dbo.sCityDescription values
(1,'Amsterdam')
,(2,'The Hague')
,(3,'Maastricht')
,(4,'Rotterdam');
select ctds.CityDescription
,sst.Value as 'CityId'
from dbo.sCity ct
cross apply dbo.SplitString(CityId,',') sst
join dbo.sCityDescription ctds
on sst.Value = ctds.CityId;

ORA-00911: invalid character on oracle, but works with H2

I have the following SQL command, it works with H2 database, but when i try to run it on Oracle XE, it gets the " ORA-00911: invalid character " error.
create table EMPLOYEE (
EMPLOYEE_KEY NUMBER(10) not null,
SALARY NUMBER(10,2),
LAST_NAME VARCHAR2(132),
FIRST_NAME VARCHAR2(132),
SUPERVISOR_KEY NUMBER(10),
constraint EMPLOYEE_PK primary key (EMPLOYEE_KEY)
);
create unique index EMPLOYEE_PK on EMPLOYEE(EMPLOYEE_KEY);
With this example, when you created the primary key constraint, you also created an index with the same name as the index you are trying to create, EMPLOYEE_PK.
Tom Kytes states on his ask tom site:
A primary key or unique constraint is not guaranteed to create a new
index, nor is the index they create guaranteed to be a unique index.
Therefore, if you desire a unique index to be created for query
performance issues, you should explicitly create one.
Oddly, enough when I run your DDL, I receive the ORA-00955 error and not the ORA-00911 (invalid character error).
Often times the ORA-00911 error occurs when one is copying from one editor to another and you copy some non-printable characters.
Below, I ran the first DDL statement provided and then I checked the indices created. If you look closely, you will see that EMPLOYEE_PK index was created as a consequence of the primary key constraint which you created.
SCOTT#dev> create table EMPLOYEE (
2 EMPLOYEE_KEY NUMBER(10) not null,
3 SALARY NUMBER(10,2),
4 LAST_NAME VARCHAR2(132),
5 FIRST_NAME VARCHAR2(132),
6 SUPERVISOR_KEY NUMBER(10),
7 constraint EMPLOYEE_PK primary key (EMPLOYEE_KEY)
8 );
Table created.
SCOTT#dev> SELECT ind.index_name,
2 ind.index_type,
3 ind.table_owner,
4 ind.table_name
5 FROM all_indexes ind
6 JOIN all_ind_columns icol
7 ON ind.owner = icol.index_owner
8 AND ind.table_name = icol.table_name
9 AND ind.index_name = icol.index_name
10 WHERE 1 = 1
11 AND ind.table_name = 'EMPLOYEE'
12 /
INDEX_NAME INDEX_TYPE TABLE_OWNER TABLE_NAME
============================== =========================== ============================== ==============================
EMPLOYEE_PK NORMAL SCOTT EMPLOYEE
If you desire to create a unique index on EMPLOYEE_KEY separately, a number of approaches could be taken. Here is one:
--create the table
SCOTT#dev> create table EMPLOYEE (
2 EMPLOYEE_KEY NUMBER(10) not null,
3 SALARY NUMBER(10,2),
4 LAST_NAME VARCHAR2(132),
5 FIRST_NAME VARCHAR2(132),
6 SUPERVISOR_KEY NUMBER(10)
7 );
Table created.
--create the unique index
SCOTT#dev> CREATE UNIQUE INDEX EMPLOYEE_PK ON EMPLOYEE (EMPLOYEE_KEY);
Index created.
--add the primary key
SCOTT#dev> alter table EMPLOYEE add
2 constraint EMPLOYEE_PK primary key (EMPLOYEE_KEY)
3 /
Table altered.
SCOTT#dev> SELECT ind.index_name,
2 ind.index_type,
3 ind.table_owner,
4 ind.table_name
5 FROM all_indexes ind
6 JOIN all_ind_columns icol
7 ON ind.owner = icol.index_owner
8 AND ind.table_name = icol.table_name
9 AND ind.index_name = icol.index_name
10 WHERE 1 = 1
11 AND ind.table_name = 'EMPLOYEE'
12 /
INDEX_NAME INDEX_TYPE TABLE_OWNER TABLE_NAME
============================== =========================== ============================== ==============================
EMPLOYEE_PK NORMAL SCOTT EMPLOYEE
SCOTT#dev>
SCOTT#dev> SELECT cons.constraint_name
2 FROM all_constraints cons
3 JOIN all_cons_columns conc
4 ON conc.table_name = 'EMPLOYEE'
5 AND cons.owner = conc.owner
6 AND cons.table_name = conc.table_name
7 WHERE 1 = 1
8 AND cons.constraint_name = conc.constraint_name
9 /
CONSTRAINT_NAME
=============================
EMPLOYEE_PK
I won' insist on the redundancy between a primary key and an unique index, but, to answer only to your question as it is titled:
when i try to run it on Oracle XE, it gets the " ORA-00911: invalid character " error.
It chops on ; as, as far as I know, you can only issue one SQL command at a time through the "SQL Workshop > SQL Command" page of Oracle application Express (you can send a PL/SQL bloc too)
However you can select your commands one by one and hit run. When there is a selection, only the sectioned part is executed. For example, in the following screen capture, only the first DDL statement will be executed by clicking on the "run" button:

Filtering data from two or more tables in SQL server 2008

I have a few tables:
"DCDetails" table which contains the Master data for a few diagnostics centers.
"CompanyDetails" table which contains the Master data for Companies
"Investigation" table which contains the Investigations(meaning set of medical tests to be conducted)
These are my master tables.
I also have a few mapping tables:
1. "CompanyDCMap" table which contains the MAPPING of Company to Diagnostic centers
2. "InvestigationDCMap" table which contains the MAPPING of Investigation to Diagnostic centers(Or DC for short)
I have to filter a set of DC based on two criteria which are:
the DC belongs in the "CompanyDCMap" and
Out of the DC filtered in (1), it also belongs in the "InvestigationDCMap" table.
How do I write the query for this so that I get the DC which are in both CompanyDCMap and InvestigationDCMap given I have the primary keys of "CompanyDetails" and "Investigation" tables.
I have almost given up, I am unable to think of a query which filters two sets at the same time.
Kindly help me.
UPDATE
Schema:
CompanyDetails table:
CompanyID(PRIMARY KEY), CompanyName(NVARCHAR(100))
1 Company1
2 Company2
3 Company3
Investigation Table:
InvestigationID(Primary key) , InvestigationName(NVARCHAR(100))
1 HIV+ Blood Test
2 TMT
3 Urine Test
DCDetails Table:
DCID(PRIMARY KEY), DCName(NVARCHAR(100))
1 DC1
2 DC2
3 DC3
CompanyDCMap table
CompanyDCMapID(Primary key), CompanyID(Foreign key), DCId(Foreign Key)
1 1 1
2 1 2
3 2 2
4 2 3
5 3 1
6 3 3
InvestigationDCMap table
InvestigationDCMapID(Primary Key), InvestigationID(Foreign Key), DCId(Foreign Key)
1 1 1
2 1 3
3 2 2
4 2 3
Expected Output of a query given CompanyID = 1 and InvestigationID = 2, SELECT DCId and DCName =
DCId(Int) DCName(NVARCHAR(100))
2 DC2
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
To get "distinct" values, you can use:
SELECT DISTINCT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
Or...
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID
GROUP BY d.DCID, d.DCName;
Better yet, since no relationships with the other tables are needed:
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
WHERE EXISTS (SELECT 1 FROM dbo.CompanyDCMap WHERE DCId = d.DCID)
AND EXISTS (SELECT 1 FROM dbo.InvestigationDCMap WHERE DCId = d.DCID);
This will be a much more efficient query, but if you need other columns from the other tables, you'll need to revert to the join version.

Options for indexing a view with cte

I have a view for which I want to create an Indexed view. After a lot of energy I was able to put the sql query in place for the view and It looks like this -
ALTER VIEW [dbo].[FriendBalances] WITH SCHEMABINDING as
WITH
trans (Amount,PaidBy,PaidFor, Id) AS
(SELECT Amount,userid AS PaidBy, PaidForUsers_FbUserId AS PaidFor, Id FROM dbo.Transactions
FULL JOIN dbo.TransactionUser ON dbo.Transactions.Id = dbo.TransactionUser.TransactionsPaidFor_Id),
bal (PaidBy,PaidFor,Balance) AS
(SELECT PaidBy,PaidFor, SUM( Amount/ transactionCounts.[_count]) AS Balance FROM trans
JOIN (SELECT Id,COUNT(*)AS _count FROM trans GROUP BY Id) AS transactionCounts ON trans.Id = transactionCounts.Id AND trans.PaidBy <> trans.PaidFor
GROUP BY trans.PaidBy,trans.PaidFor )
SELECT ISNULL(bal.PaidBy,bal2.PaidFor)AS PaidBy,ISNULL(bal.PaidFor,bal2.PaidBy)AS PaidFor,
ISNULL( bal.Balance,0)-ISNULL(bal2.Balance,0) AS Balance
FROM bal
left JOIN bal AS bal2 ON bal.PaidBy = bal2.PaidFor AND bal.PaidFor = bal2.Paidby
WHERE ISNULL( bal.Balance,0)>ISNULL(bal2.Balance,0)
Sample Data for FriendBalances View -
PaidBy PaidFor Balance
------ ------- -------
9990 9991 1000
9990 9992 2000
9990 9993 1000
9991 9993 1000
9991 9994 1000
It is mainly a join of 2 tables.
Transactions -
CREATE TABLE [dbo].[Transactions](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Amount] [float] NOT NULL,
[UserId] [bigint] NOT NULL,
[Remarks] [nvarchar](255) NULL,
[GroupFbGroupId] [bigint] NULL,
CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED
Sample data in Transactions Table -
Id Date Amount UserId Remarks GroupFbGroupId
-- ----------------------- ------ ------ -------------- --------------
1 2001-01-01 00:00:00.000 3000 9990 this is a test NULL
2 2001-01-01 00:00:00.000 3000 9990 this is a test NULL
3 2001-01-01 00:00:00.000 3000 9991 this is a test NULL
TransactionUsers -
CREATE TABLE [dbo].[TransactionUser](
[TransactionsPaidFor_Id] [bigint] NOT NULL,
[PaidForUsers_FbUserId] [bigint] NOT NULL
) ON [PRIMARY]
Sample Data in TransactionUser Table -
TransactionsPaidFor_Id PaidForUsers_FbUserId
---------------------- ---------------------
1 9991
1 9992
1 9993
2 9990
2 9991
2 9992
3 9990
3 9993
3 9994
Now I am not able to create a view because my query contains cte(s). What are the options that I have now?
If cte can be removed, what should be the other option which would help in creating indexed views.
Here is the error message -
Msg 10137, Level 16, State 1, Line 1 Cannot create index on view "ShareBill.Test.Database.dbo.FriendBalances" because it references common table expression "trans". Views referencing common table expressions cannot be indexed. Consider not indexing the view, or removing the common table expression from the view definition.
The concept:
Transaction mainly consists of:
an Amount that was paid
UserId of the User who paid that amount
and some more information which is not important for now.
TransactionUser table is a mapping between a Transaction and a User Table. Essentially a transaction can be shared between multiple persons. So we store that in this table.
So we have transactions where 1 person is paying for it and other are sharing the amount. So if A pays 100$ for B then B would owe 100$ to A. Similarly if B pays 90$ for A then B would owe only $10 to A. Now if A pays 300$ for A,b,c that means B would owe 110$ and C would owe 10$ to A.
So in this particular view we are aggregating the effective amount that has been paid (if any) between 2 users and thus know how much a person owes another person.
Okay, this gives you an indexed view (that needs an additional view on top of to sort out the who-owes-who detail), but it may not satisfy your requirements still.
/* Transactions table, as before, but with handy unique constraint for FK Target */
CREATE TABLE [dbo].[Transactions](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Amount] [float] NOT NULL,
[UserId] [bigint] NOT NULL,
[Remarks] [nvarchar](255) NULL,
[GroupFbGroupId] [bigint] NULL,
CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED (Id),
constraint UQ_Transactions_XRef UNIQUE (Id,Amount,UserId)
)
Nothing surprising so far, I hope
/* Much expanded TransactionUser table, we'll hide it away and most of the maintenance is automatic */
CREATE TABLE [dbo]._TransactionUser(
[TransactionsPaidFor_Id] int NOT NULL,
[PaidForUsers_FbUserId] [bigint] NOT NULL,
Amount float not null,
PaidByUserId bigint not null,
UserCount int not null,
LowUserID as CASE WHEN [PaidForUsers_FbUserId] < PaidByUserId THEN [PaidForUsers_FbUserId] ELSE PaidByUserId END,
HighUserID as CASE WHEN [PaidForUsers_FbUserId] < PaidByUserId THEN PaidByUserId ELSE [PaidForUsers_FbUserId] END,
PerUserDelta as (Amount/UserCount) * CASE WHEN [PaidForUsers_FbUserId] < PaidByUserId THEN -1 ELSE 1 END,
constraint PK__TransactionUser PRIMARY KEY ([TransactionsPaidFor_Id],[PaidForUsers_FbUserId]),
constraint FK__TransactionUser_Transactions FOREIGN KEY ([TransactionsPaidFor_Id]) references dbo.Transactions,
constraint FK__TransactionUser_Transaction_XRef FOREIGN KEY ([TransactionsPaidFor_Id],Amount,PaidByUserID)
references dbo.Transactions (Id,Amount,UserId) ON UPDATE CASCADE
)
This table now maintains enough information to allow the view to be constructed. The rest of the work we do is to construct/maintain the data in the table. Note that, with the foreign key constraint, we've already ensured that if, say, an amount is changed in the transactions table, everything gets recalculated.
/* View that mimics the original TransactionUser table -
in fact it has the same name so existing code doesn't need to change */
CREATE VIEW dbo.TransactionUser
with schemabinding
as
select
[TransactionsPaidFor_Id],
[PaidForUsers_FbUserId]
from
dbo._TransactionUser
GO
/* Effectively the PK on the original table */
CREATE UNIQUE CLUSTERED INDEX PK_TransactionUser on dbo.TransactionUser ([TransactionsPaidFor_Id],[PaidForUsers_FbUserId])
Anything that's already written to work against TransactionUser will now work against this view, and be none the wiser. Except, they can't insert/update/delete the rows without some help:
/* Now we write the trigger that maintains the underlying table */
CREATE TRIGGER dbo.T_TransactionUser_IUD
ON dbo.TransactionUser
INSTEAD OF INSERT, UPDATE, DELETE
AS
SET NOCOUNT ON;
/* Every delete affects *every* row for the same transaction
We need to drop the counts on every remaining row, as well as removing the actual rows we're interested in */
WITH DropCounts as (
select TransactionsPaidFor_Id,COUNT(*) as Cnt from deleted group by TransactionsPaidFor_Id
), KeptRows as (
select tu.TransactionsPaidFor_Id,tu.PaidForUsers_FbUserId,UserCount - dc.Cnt as NewCount
from dbo._TransactionUser tu left join deleted d
on tu.TransactionsPaidFor_Id = d.TransactionsPaidFor_Id and
tu.PaidForUsers_FbUserId = d.PaidForUsers_FbUserId
inner join DropCounts dc
on
tu.TransactionsPaidFor_Id = dc.TransactionsPaidFor_Id
where
d.PaidForUsers_FbUserId is null
), ChangeSet as (
select TransactionsPaidFor_Id,PaidForUsers_FbUserId,NewCount,1 as Keep
from KeptRows
union all
select TransactionsPaidFor_Id,PaidForUsers_FbUserId,null,0
from deleted
)
merge into dbo._TransactionUser tu
using ChangeSet cs on tu.TransactionsPaidFor_Id = cs.TransactionsPaidFor_Id and tu.PaidForUsers_FbUserId = cs.PaidForUsers_FbUserId
when matched and cs.Keep = 1 then update set UserCount = cs.NewCount
when matched then delete;
/* Every insert affects *every* row for the same transaction
This is why the indexed view couldn't be generated */
WITH TU as (
select TransactionsPaidFor_Id,PaidForUsers_FbUserId,Amount,PaidByUserId from dbo._TransactionUser
where TransactionsPaidFor_Id in (select TransactionsPaidFor_Id from inserted)
union all
select TransactionsPaidFor_Id,PaidForUsers_FbUserId,Amount,UserId
from inserted i inner join dbo.Transactions t on i.TransactionsPaidFor_Id = t.Id
), CountedTU as (
select TransactionsPaidFor_Id,PaidForUsers_FbUserId,Amount,PaidByUserId,
COUNT(*) OVER (PARTITION BY TransactionsPaidFor_Id) as Cnt
from TU
)
merge into dbo._TransactionUser tu
using CountedTU new on tu.TransactionsPaidFor_Id = new.TransactionsPaidFor_Id and tu.PaidForUsers_FbUserId = new.PaidForUsers_FbUserId
when matched then update set Amount = new.Amount,PaidByUserId = new.PaidByUserId,UserCount = new.Cnt
when not matched then insert
([TransactionsPaidFor_Id],[PaidForUsers_FbUserId],Amount,PaidByUserId,UserCount)
values (new.TransactionsPaidFor_Id,new.PaidForUsers_FbUserId,new.Amount,new.PaidByUserId,new.Cnt);
Now that the underlying table is being maintained, we can finally write the indexed view you wanted in the first place... almost. The issue is that the totals we create may be positive or negative, because we've normalized the transactions so that we can easily sum them:
CREATE VIEW [dbo]._FriendBalances
WITH SCHEMABINDING
as
SELECT
LowUserID,
HighUserID,
SUM(PerUserDelta) as Balance,
COUNT_BIG(*) as Cnt
FROM dbo._TransactionUser
WHERE LowUserID != HighUserID
GROUP BY
LowUserID,
HighUserID
GO
create unique clustered index IX__FriendBalances on dbo._FriendBalances (LowUserID, HighUserID)
So we finally create a view, built on the indexed view above, that if the balance is negative, we flip the person owed, and the person owing around. But it will use the index on the above view, which is most of the work we were seeking to save by having the indexed view:
create view dbo.FriendBalances
as
select
CASE WHEN Balance >= 0 THEN LowUserID ELSE HighUserID END as PaidBy,
CASE WHEN Balance >= 0 THEN HighUserID ELSE LowUserID END as PaidFor,
ABS(Balance) as Balance
from
dbo._FriendBalances WITH (NOEXPAND)
Now, finally, we insert your sample data:
set identity_insert dbo.Transactions on --Ensure we get IDs we know
GO
insert into dbo.Transactions (Id,[Date] , Amount , UserId , Remarks ,GroupFbGroupId)
select 1 ,'2001-01-01T00:00:00.000', 3000, 9990 ,'this is a test', NULL union all
select 2 ,'2001-01-01T00:00:00.000', 3000, 9990 ,'this is a test', NULL union all
select 3 ,'2001-01-01T00:00:00.000', 3000, 9991 ,'this is a test', NULL
GO
set identity_insert dbo.Transactions off
GO
insert into dbo.TransactionUser (TransactionsPaidFor_Id, PaidForUsers_FbUserId)
select 1, 9991 union all
select 1, 9992 union all
select 1, 9993 union all
select 2, 9990 union all
select 2, 9991 union all
select 2, 9992 union all
select 3, 9990 union all
select 3, 9993 union all
select 3, 9994
And query the final view:
select * from dbo.FriendBalances
PaidBy PaidFor Balance
9990 9991 1000
9990 9992 2000
9990 9993 1000
9991 9993 1000
9991 9994 1000
Now, there is additional work we could do, if we were concerned that someone may find a way to dodge the triggers and perform direct changes to the base tables. The first would be yet another indexed view, that will ensure that every row for the same transaction has the same UserCount value. Finally, with a few additional columns, check constraints, FK constraints and more work in the triggers, I think we can ensure that the UserCount is correct - but it may add more overhead than you want.
I can add scripts for these aspects if you want me to - it depends on how restrictive you want/need the database to be.

Resources