Identity-like column but based on Group By criteria - sql

In my SQL Server 2012 database, I'm creating a "Tasks" table that will have a compound primary key composed of three fields:
Issue_ID [int] NOT NULL,
Issue_Sub_ID [int] NOT NULL,
Task_ID [int] NOT NULL
Issue_ID and Issue_Sub_ID are foreign keys to other tables. In the table I'm creating, there can be many tasks associated with each Issue_ID / Issue_Sub_ID combination.
What I would like to do is establish a default value for the Task_ID column, similar to if I used IDENTITY(1,1), but that will auto-increment based on the Issue_ID / Issue_Sub_ID group. For example, the Task_ID results would look as follows, given the provided Issue_ID / Issue_Sub_ID values:
Issue_ID Issue_Sub_ID Task_ID
======== ============ =======
12345 1 1
12345 1 2
12345 1 3
12345 2 1
12345 2 2
67890 2 1
67890 2 2
67890 2 3
I'm familiar with the ROW_NUMBER() OVER(PARTITION BY Issue_ID, Issue_Sub_ID ORDER BY Issue_ID, Issue_Sub_ID) possible solution but, as I'd like this column to be a part of the compound primary key of the table, I don't think that will work.
Thanks all in advance.

I agree with Sean - add an identity column, and then just use a computed column for the task id.
Even though I've answered a question very much like this one here,
I'm not sure about marking this one as a duplicate. The reason for this is that you want to use the task_id as a part of the primary key.
However, I'm not sure that's possible, since in order to include a computed column in the primary key it must be persisted, and for some reason (I think it's because of the use of a UDF) SQL Server will not allow me to mark it as persisted.
Anyway, here is my proposed solution for this:
First, create a function that will calculate the task id:
CREATE FUNCTION dbo.GenerateTaskId
(
#Row_Id int,
#Issue_Id int,
#Issue_Sub_Id int
)
RETURNS Int
AS
BEGIN
RETURN
(
SELECT COUNT(*)
FROM dbo.Tasks
WHERE Issue_Id = #Issue_Id
AND Issue_Sub_ID = #Issue_Sub_ID
AND Row_Id <= #Row_Id
)
END
GO
Then, create the table with the task id as a computed column:
CREATE TABLE dbo.Tasks
(
Row_Id [int] IDENTITY(1,1),
Issue_ID [int] NOT NULL,
Issue_Sub_ID [int] NOT NULL,
Task_Id AS dbo.GenerateTaskId(Row_Id, Issue_Id, Issue_Sub_Id),
CONSTRAINT PK_Tasks PRIMARY KEY (Row_Id)
)
GO
Now, test it:
INSERT INTO Tasks VALUES
(12345, 1),
(12345, 1),
(12345, 1),
(12345, 2),
(12345, 2),
(67890, 2),
(67890, 2),
(67890, 2)
SELECT *
FROM Tasks
Results:
Row_Id Issue_ID Issue_Sub_ID Task_Id
1 12345 1 1
2 12345 1 2
3 12345 1 3
4 12345 2 1
5 12345 2 2
6 67890 2 1
7 67890 2 2
8 67890 2 3
You can see a live demo on rextester.

Related

Is it possible to create two tables with disjoint identifiers?

By "disjoint" I mean mutually exclusive sets of ID values. No overlap between both tables.
For example, the sequence generator for the id column on both tables should work in conjunction to make sure they are always disjoint. I am not sure if this is possible. So, I thought I would just ask here.
Table A
id
name
0
abc
1
cad
2
pad
3
ial
Table B
id
name
40
pal
50
sal
A different hack-around:
CREATE TABLE odd(
id INTEGER GENERATED ALWAYS AS IDENTITY (START 1 INCREMENT 2)
, val integer
);
CREATE TABLE even(
id INTEGER GENERATED ALWAYS AS IDENTITY (START 2 INCREMENT 2)
, val integer
);
INSERT INTO odd (val)
SELECT GENERATE_SERIES(1,10);
INSERT INTO even (val)
SELECT GENERATE_SERIES(1,20);
SELECT * FROM odd;
SELECT * FROM even;
Result:
CREATE TABLE
CREATE TABLE
INSERT 0 10
INSERT 0 20
id | val
----+-----
1 | 1
3 | 2
5 | 3
7 | 4
9 | 5
11 | 6
13 | 7
15 | 8
17 | 9
19 | 10
(10 rows)
id | val
----+-----
2 | 1
4 | 2
6 | 3
8 | 4
10 | 5
12 | 6
14 | 7
16 | 8
18 | 9
20 | 10
22 | 11
24 | 12
26 | 13
28 | 14
30 | 15
32 | 16
34 | 17
36 | 18
38 | 19
40 | 20
(20 rows)
A very simple way is to share the same SEQUENCE:
CREATE TABLE a (
id serial PRIMARY KEY
, name text
);
CREATE TABLE b (
id int PRIMARY KEY
, name text
);
SELECT pg_get_serial_sequence('a', 'id'); -- 'public.a_id_seq'
ALTER TABLE b ALTER COLUMN id SET DEFAULT nextval('public.a_id_seq'); -- !
db<>fiddle here
This way, table a "owns" the sequence, while table b draws from the same source. You can also create an independent SEQUENCE if you prefer.
Note: this only guarantees mutually exclusive new IDs (even under concurrent write load) while you don't override default values and also don't update them later.
Related:
Creating a PostgreSQL sequence to a field (which is not the ID of the record)
Safely rename tables using serial primary key columns
Auto increment table column
PostgreSQL next value of the sequences?
Welcome to the painful world of inter-table constraints or assertions - this is something that ISO SQL and pretty much every RDBMS out there does not handle ergonomically...
(While ISO SQL does describe both deferred-constraints and database-wide assertions, as far as I know only PostgreSQL implements deferred-constraints, and no production-quality RDBMS supports database-wide assertions).
One approach is to have a third-table which is the only table with SERIAL (aka IDENTITY aka AUTO_INCREMENT) with a discriminator column which combined forms the table's primary-key, then the other two tables have an FK constraint to that PK - but they'll also need the same discriminator column (enforced with a CHECK constraint), but you will never need to reference that column in most queries.
As your post doesn't tell us what the real table-names are, I'll use my own.
Something like this:
CREATE TABLE postIds (
postId int NOT NULL SERIAL,
postType char(1) NOT NULL, /* This is the discriminator column. It can only contain ONLY either 'S' or 'G' which indicates which table contains the rest of the data */
CONSTRAINT PK_postIds PRIMARY KEY ( postId, postType ),
CONSTRAINT CK_type CHECK ( postType IN ( 'S', 'G' ) )
);
CREATE TABLE shitposts (
postId int NOT NULL,
postType char(1) DEFAULT('S'),
foobar nvarchar(255) NULL,
etc int NOT NULL,
CONSTRAINT PK_shitpostIds PRIMARY KEY ( postId, postType ),
CONSTRAINT CK_type CHECK ( postType = 'S' ),
CONSTRAINT FK_shitpost_ids FOREIGN KEY ( postId, postType ) REFERENCES postIds ( postId, postType )
);
CREATE TABLE goldposts (
postId int NOT NULL,
postType char(1) DEFAULT('G'),
foobar nvarchar(255) NULL,
etc int NOT NULL,
CONSTRAINT PK_goldpostIds PRIMARY KEY ( postId, postType ),
CONSTRAINT CK_type CHECK ( postType = 'G' ),
CONSTRAINT FK_goldpost_ids FOREIGN KEY ( postId, postType ) REFERENCES postIds ( postId, postType )
)
With this design, it is impossible for any row in shitposts to share a postId value with a post in goldposts and vice-versa.
However it is possible for a row to exist in postIds without having any row in both goldposts and shitposts. Fortunately, as you are using PostgreSQL you could add a new FK constraint from postIds to both goldposts and shitposts but use it with deferred-constraints.

Increment a column value of an entity in an SQL table

I've set up the following table:
CREATE TABLE transactions (txn_id SERIAL, stock VARCHAR NOT NULL, qty INT NOT NULL, user_id INT NOT NULL);
On inserting few rows, the table looks like this:
txn_id | stock | qty | user_id
--------+--------+-----+---------
1 | APPL | 2 | 1
2 | GOOGLE | 3 | 4
3 | TSLA | 1 | 2
Now, while adding a new insert into the table,
for example - INSERT INTO transactions (stock, qty, user_id) VALUES ('APPL', 3, 1)
if 'stock' and 'user_id' match (as in the above example), i only want the quantity to be updated in the database. Such as in this case, the row 1 entity should have its 'qty' column value incremented by +3.
Is there a solution to this without using any ORM like SQLalchemy etc. ?
You want on conflict. First set up a unique constraint on the stock/user_id columns:
alter table transactions add constraint unq_transactions_stock_user_id unique (stock, user_id);
Then use this with an on conflict statement:
insert into transactions (stock, qty, user_id)
values ('APPL', 3, 1)
on conflict on constraint unq_transactions_stock_user_id do update
set qty = coalesce(transactions.qty, 0) + excluded.qty;

Snowflake: create a default field value that auto increments for each primary key, resets per primary key

I would like to create a table to house the following type of data
+--------+-----+----------+
| pk | ctr | name |
+--------+-----+----------+
| fish | 1 | herring |
| mammal | 1 | dog |
| mammal | 2 | cat |
| mammal | 3 | whale |
| bird | 1 | penguin |
| bird | 2 | ostrich |
+--------+----_+----------+
PK is the primary key string (100) not null
ctr is a field I want to auto increment by 1 for each pk row
I have tried the following
create or replace table schema.animals (
pk string(100) not null primary key,
ctr integer not null default ( select NVL(max(ctr),0) + 1 from schema.animals )
name string (1000) not null);
This produced the following error
SQL compilation error: error line 6 at position 52 aggregate functions
are not allowed as part of the specification of a default value
clause.
So i would have used the auto increment /identity property like so
AUTOINCREMENT | IDENTITY [ ( start_num , step_num ) | START num INCREMENT num ]
but it doesnt seem to be able to support the resetting per unique pk
looking for any suggestions on how to solve this, thanks for any help in advance
You cannot do this with an IDENTITY method. The suggested solution is to use INSTEAD OF trigger that will calculate ctr value on every row of INSERTED table. For example
CREATE TABLE dbo.animals (
pk nvarchar(100) NOT NULL,
ctr integer NOT NULL,
name nvarchar(1000) NOT NULL,
CONSTRAINT PK_animals PRIMARY KEY (pk, ctr)
)
GO
CREATE TRIGGER dbo.animals_before_insert ON dbo.animals INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO animals (pk, ctr, name)
SELECT
i.pk,
(ROW_NUMBER() OVER (PARTITION BY i.pk ORDER BY i.name) + ISNULL(a.max_ctr, 0)) AS ctr,
i.name
FROM inserted i
LEFT JOIN (SELECT pk, MAX(ctr) AS max_ctr FROM dbo.animals GROUP BY pk) a
ON i.pk = a.pk;
END
GO
INSERT INTO dbo.animals (pk, name) VALUES
('fish' , 'herring'),
('mammal' , 'dog'),
('mammal' , 'cat'),
('mammal' , 'whale'),
('bird' , 'pengui'),
('bird' , 'ostrich');
SELECT * FROM dbo.animals;
Result
pk ctr name
------- ----- ---------
bird 1 ostrich
bird 2 pengui
fish 1 herring
mammal 1 cat
mammal 2 dog
mammal 3 whale
Another method is to use scalar user-defined function as DEFAULT value but it is slow: the trigger fires once on all rows whereas the function is called on every row.
I have no idea why you would have a column called pk that is not the primary key. You cannot (easily) do what you want. I would recommend doing this as:
create or replace table schema.animals (
animal_id int identity primary key,
name string(100) not null primary key,
);
create view schema.v_animals as
select a.*, row_number() over (partition by name order by animal_id) as ctr
from schema.animals a;
That is, calculate ctr when you need to use it, rather than storing it in the table.

How to better duplicate a set of data in SQL Server

I have several related tables that I want to be able to duplicate some of the rows while updating the references.
I want to duplicate a row in Table1, and all of it's related rows from Table2 and Table3, and I'm trying to figure out an efficient way of doing it short of iterating through rows.
So for example, I have a table of baskets:
+----------+---------------+
| BasketId | BasketName |
+----------+---------------+
| 1 | Home Basket |
| 2 | Office Basket |
+----------+---------------+
Each basket has fruit:
+---------+----------+-----------+
| FruitId | BasketId | FruitName |
+---------+----------+-----------+
| 1 | 1 | Apple |
| 2 | 1 | Orange |
| 3 | 2 | Mango |
| 4 | 2 | Pear |
+---------+----------+-----------+
And each fruit has some properties:
+------------+---------+--------------+
| PropertyId | FruitId | PropertyText |
+------------+---------+--------------+
| 1 | 2 | Is juicy |
| 2 | 2 | Hard to peel |
| 3 | 1 | Is red |
+------------+---------+--------------+
For this example, my properties are specific to the individual fruit row, these "apple" properties aren't properties of all apples in all baskets, just for that specific apple in that specific basket.
What I want to do is duplicate a basket. So given basket 1, I want to create a new basket, duplicate the fruit rows it contains, and duplicate the properties pointing to those fruits. In the end I'm hoping to have data like so:
+----------+---------------+
| BasketId | BasketName |
+----------+---------------+
| 1 | Home Basket |
| 2 | Office Basket |
| 3 | Friends Basket|
+----------+---------------+
+---------+----------+-----------+
| FruitId | BasketId | FruitName |
+---------+----------+-----------+
| 1 | 1 | Apple |
| 2 | 1 | Orange |
| 3 | 2 | Mango |
| 4 | 2 | Pear |
| 5 | 3 | Apple |
| 6 | 3 | Orange |
+---------+----------+-----------+
+------------+---------+--------------+
| PropertyId | FruitId | PropertyText |
+------------+---------+--------------+
| 1 | 2 | Is juicy |
| 2 | 2 | Hard to peel |
| 3 | 1 | Is red |
| 4 | 6 | Is juicy |
| 5 | 6 | Hard to peel |
| 6 | 5 | Is red |
+------------+---------+--------------+
Duplicating the basket and it's fruit were pretty straightforward, but duplicating the properties of the fruit seems to me to lead to iterating over rows and I'm hoping there's a better solution in TSQL.
Any ideas?
Why dont you join on the FruitName to get a table with old and new FruitId's? Considering information would be added at the same time.... it may not be the best option but you wont be using any cycles.
INSERT INTO BASKET(BASKETNAME)
VALUES ('COPY BASKET')
DECLARE #iBasketId int
SET #iBasketId = ##SCOPE_IDENTITY;
insert into Fruit (BasketId, FruitName)
select #iBasketId, FruitName
from Fruit
where BasketId = #originalBasket
declare #tabFruit table (originalFruitId int, newFruitId int)
insert into #tabFruit (originalFruitId, newFruitId)
select o.FruitId, n.FruitId
from (SELECT FruitId, FruitName from Fruit where BasketId = #originalBasket) as o
join (SELECT FruitId, FruitName from Fruit where BasketId = #newBasket) as n
on o.FruitName = n.FruitName
insert into Property (FruitId, PropertyText)
select NewFruitId, PropertyText
from Fruit f join #tabFruit t on t.originalFruitId = f.FruitId
(ab)use MERGE with OUTPUT clause.
MERGE can INSERT, UPDATE and DELETE rows. In our case we need only to INSERT. 1=0 is always false, so the NOT MATCHED BY TARGET part is always executed. In general, there could be other branches, see docs. WHEN MATCHED is usually used to UPDATE; WHEN NOT MATCHED BY SOURCE is usually used to DELETE, but we don't need them here.
This convoluted form of MERGE is equivalent to simple INSERT, but unlike simple INSERT its OUTPUT clause allows to refer to the columns that we need.
I will write down the definitions of table explicitly. Each primary key in the tables is IDENTITY. I've configured foreign keys as well.
Baskets
CREATE TABLE [dbo].[Baskets](
[BasketId] [int] IDENTITY(1,1) NOT NULL,
[BasketName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Baskets] PRIMARY KEY CLUSTERED
(
[BasketId] ASC
)
Fruits
CREATE TABLE [dbo].[Fruits](
[FruitId] [int] IDENTITY(1,1) NOT NULL,
[BasketId] [int] NOT NULL,
[FruitName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Fruits] PRIMARY KEY CLUSTERED
(
[FruitId] ASC
)
ALTER TABLE [dbo].[Fruits] WITH CHECK
ADD CONSTRAINT [FK_Fruits_Baskets] FOREIGN KEY([BasketId])
REFERENCES [dbo].[Baskets] ([BasketId])
ALTER TABLE [dbo].[Fruits] CHECK CONSTRAINT [FK_Fruits_Baskets]
Properties
CREATE TABLE [dbo].[Properties](
[PropertyId] [int] IDENTITY(1,1) NOT NULL,
[FruitId] [int] NOT NULL,
[PropertyText] [varchar](50) NOT NULL,
CONSTRAINT [PK_Properties] PRIMARY KEY CLUSTERED
(
[PropertyId] ASC
)
ALTER TABLE [dbo].[Properties] WITH CHECK
ADD CONSTRAINT [FK_Properties_Fruits] FOREIGN KEY([FruitId])
REFERENCES [dbo].[Fruits] ([FruitId])
ALTER TABLE [dbo].[Properties] CHECK CONSTRAINT [FK_Properties_Fruits]
Copy Basket
At first copy one row in Baskets table and use SCOPE_IDENTITY to get the generated ID.
BEGIN TRANSACTION;
-- Parameter of the procedure. What basket to copy.
DECLARE #VarOldBasketID int = 1;
-- Copy Basket, one row
DECLARE #VarNewBasketID int;
INSERT INTO [dbo].[Baskets] (BasketName)
VALUES ('Friends Basket');
SET #VarNewBasketID = SCOPE_IDENTITY();
Copy Fruits
Then copy Fruits using MERGE and remember a mapping between old and new IDs in a table variable.
-- Copy Fruits, multiple rows
DECLARE #FruitIDs TABLE (OldFruitID int, NewFruitID int);
MERGE INTO [dbo].[Fruits]
USING
(
SELECT
[FruitId]
,[BasketId]
,[FruitName]
FROM [dbo].[Fruits]
WHERE [BasketId] = #VarOldBasketID
) AS Src
ON 1 = 0
WHEN NOT MATCHED BY TARGET THEN
INSERT
([BasketId]
,[FruitName])
VALUES
(#VarNewBasketID
,Src.[FruitName])
OUTPUT Src.[FruitId] AS OldFruitID, inserted.[FruitId] AS NewFruitID
INTO #FruitIDs(OldFruitID, NewFruitID)
;
Copy Properties
Then copy Properties using remembered mapping between old and new Fruit IDs.
-- Copy Properties, many rows
INSERT INTO [dbo].[Properties] ([FruitId], [PropertyText])
SELECT
F.NewFruitID
,[dbo].[Properties].PropertyText
FROM
[dbo].[Properties]
INNER JOIN #FruitIDs AS F ON F.OldFruitID = [dbo].[Properties].FruitId
;
Check results, change rollback to commit once you confirmed that the code works correctly.
SELECT * FROM [dbo].[Baskets];
SELECT * FROM [dbo].[Fruits];
SELECT * FROM [dbo].[Properties];
ROLLBACK TRANSACTION;
I had the same need as the OP: cloning sql server tables where they are hierarchical sql server tables that contain foreign keys to one another. Or in other words, cloning sql server tables that have parent-child relationships.
Starting with #Tony_O 's answer/SQL, I converted it to my needs but discovered that the last line '..from Fruit f join..' should be '..from Property f join..'. Also, #newBasket should be #iBasketId.
So along with some other minor housekeeping fixes I found were needed for it to execute, plus using #Vladimir_Baranov 's DDL (with some missing parenthesis added), as well as making both of their SQL's object names consistent, since I had done the work I thought I would post it as a refinement of their work that will allow someone to to quickly test whether this solution solves their need. Just do 'find/replace' of the table names here with values from yours.
And note that if your Properties table has more fields than the single 'PropertyText' one in this example, just make sure to join on those additional fields as noted in the comment in the script.
-----------------
--create tables--
-----------------
--Baskets
CREATE TABLE [dbo].[Baskets](
[BasketId] [int] IDENTITY(1,1) NOT NULL,
[BasketName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Baskets] PRIMARY KEY CLUSTERED
(
[BasketId] ASC
)
)
--Fruits
CREATE TABLE [dbo].[Fruits](
[FruitId] [int] IDENTITY(1,1) NOT NULL,
[BasketId] [int] NOT NULL,
[FruitName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Fruits] PRIMARY KEY CLUSTERED
(
[FruitId] ASC
)
)
ALTER TABLE [dbo].[Fruits] WITH CHECK
ADD CONSTRAINT [FK_Fruits_Baskets] FOREIGN KEY([BasketId])
REFERENCES [dbo].[Baskets] ([BasketId])
ALTER TABLE [dbo].[Fruits] CHECK CONSTRAINT [FK_Fruits_Baskets]
--Properties
CREATE TABLE [dbo].[Properties](
[PropertyId] [int] IDENTITY(1,1) NOT NULL,
[FruitId] [int] NOT NULL,
[PropertyText] [varchar](50) NOT NULL,
CONSTRAINT [PK_Properties] PRIMARY KEY CLUSTERED
(
[PropertyId] ASC
)
)
ALTER TABLE [dbo].[Properties] WITH CHECK
ADD CONSTRAINT [FK_Properties_Fruits] FOREIGN KEY([FruitId])
REFERENCES [dbo].[Fruits] ([FruitId])
ALTER TABLE [dbo].[Properties] CHECK CONSTRAINT [FK_Properties_Fruits]
-------------------------
--Fill tables with data--
-------------------------
SET IDENTITY_INSERT [dbo].[Baskets] ON
GO
INSERT [dbo].[Baskets] ([BasketId], [BasketName]) VALUES (1, N'Home Basket')
GO
SET IDENTITY_INSERT [dbo].[Baskets] OFF
GO
SET IDENTITY_INSERT [dbo].[Fruits] ON
GO
INSERT [dbo].[Fruits] ([FruitId], [BasketId], [FruitName]) VALUES (1, 1, N'Apple')
GO
INSERT [dbo].[Fruits] ([FruitId], [BasketId], [FruitName]) VALUES (2, 1, N'Orange')
GO
SET IDENTITY_INSERT [dbo].[Fruits] OFF
GO
SET IDENTITY_INSERT [dbo].[Properties] ON
GO
INSERT [dbo].[Properties] ([PropertyId], [FruitId], [PropertyText]) VALUES (1, 2, N'is juicy')
GO
INSERT [dbo].[Properties] ([PropertyId], [FruitId], [PropertyText]) VALUES (2, 2, N'hard to peel')
GO
INSERT [dbo].[Properties] ([PropertyId], [FruitId], [PropertyText]) VALUES (3, 1, N'is red')
GO
SET IDENTITY_INSERT [dbo].[Properties] OFF
GO
--------------------------------------------------------------
-- Copy 'Home Basket' to new basket named 'COPY BASKET' --
-- i.e., Copy Basket (and all fruits and their fruit properties) having basket id
-- #origBasketId to a new basket with name 'COPY BASKET'.
--------------------------------------------------------------
DECLARE #originalBasket int
select #originalBasket = 1
begin tran
INSERT INTO BASKETS(BASKETNAME)
VALUES ('COPY BASKET')
DECLARE #newBasketId int
SET #newBasketId = SCOPE_IDENTITY();
insert into Fruits (BasketId, FruitName)
select #newBasketId, FruitName
from Fruits
where BasketId = #originalBasket
declare #tabFruit table (originalFruitId int, newFruitId int)
insert into #tabFruit (originalFruitId, newFruitId)
select o.FruitId, n.FruitId
from (SELECT FruitId, FruitName from Fruits where BasketId = #originalBasket) as o
join (SELECT FruitId, FruitName from Fruits where BasketId = #newBasketId) as n
on o.FruitName = n.FruitName --if your table equivalent to Fruits has other fields, match on those as well here.
insert into Properties (FruitId, PropertyText)
select NewFruitId, PropertyText
from Properties p join #tabFruit t on t.originalFruitId = p.FruitId
commit tran
---------------
--See results--
---------------
select *
from dbo.Baskets b inner join dbo.Fruits f on b.BasketId=f.BasketId
inner join properties p on p.FruitId=f.FruitId
order by b.BasketId, f.FruitId, p.PropertyId

SQL Server dynamic pivot table

In SQL Server, I have two tables TableA and TableB, based on these I need to generate a report which is kind of very complex and after doing some research I come to a conclusion that I have to go with SQL Pivot table. Also, I tried this sample link but in my case the TableB table can have any number of child rows which makes it very complicated so, can anyone help me on this. Please see the details below:
Code
Create table TableA(
ProjectID INT NOT NULL,
ControlID INT NOT NULL,
ControlCode Varchar(2) NOT NULL,
ControlPoint Decimal NULL,
ControlScore Decimal NULL,
ControlValue Varchar(50)
)
Sample Data
ProjectID | ControlID | ControlCode | ControlPoint | ControlScore | ControlValue
P001 1 A 30.44 65 Invalid
P001 2 C 45.30 85 Valid
Code
Create table TableB(
ControlID INT NOT NULL,
ControlChildID INT NOT NULL,
ControlChildValue Varchar(200) NULL
)
Sample Data
ControlID | ControlChildID | ControlChildValue
1 100 Yes
1 101 No
1 102 NA
1 103 Others
2 104 Yes
2 105 SomeValue
Output should be in a single row for a given ProjectID with all its Control values first & followed by child control values (based on the ControlCode (i.e.) ControlCode_Child (1, 2, 3...) and it should look like this