Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

parent/child query help

$
0
0

Hello All,

I have a parent table tbl_trade and a child table tbl_allocation. A trade can have many allocations. I'm trying to write a query which calculates the tbl_trade.isRec value. This should be true if all the child allocations have a match key. So, in this example, tbl_trade.isrec would be true for the first trade and false for the second. How would I do this via sql ?

e.g. something like this

update tbl_trade set isrec = 1

where not exists

(

select match_key from tbl_allocation where tbl_trade.trade_id = tbl_allocation.trade_id and match_key is null

)

GO

/****** Object:  Table [dbo].[tbl_trade]    Script Date: 08/29/2013 13:28:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tbl_trade](
    [trade_id] [int] IDENTITY(1,1) NOT NULL,
    [cusip] [varchar](9) NOT NULL,
    [qty] [float] NOT NULL,
    [isRec] [bit] NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[tbl_trade] ADD  CONSTRAINT [DF_tbl_trade_isRec]  DEFAULT ((0)) FOR [isRec]
GO

USE [mtge]
GO

/****** Object:  Table [dbo].[tbl_allocation]    Script Date: 08/29/2013 13:28:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tbl_allocation](
    [alloc_id] [int] IDENTITY(1,1) NOT NULL,
    [trade_id] [nchar](10) NOT NULL,
    [qty] [int] NOT NULL,
    [match_key] [int] NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[tbl_allocation] ADD  CONSTRAINT [DF_tbl_allocation_isRec]  DEFAULT ((0)) FOR [match_key]
GO

I have the following records:

INSERT INTO tbl_trade (cusip, QTY)
values ('912828AA1', 500)

INSERT INTO tbl_trade (cusip, QTY)
values ('912828AA2', 200)

INSERT INTO tbl_allocation (trade_id, qty, match_key)
values (1, 300, 1)

INSERT INTO tbl_allocation (trade_id, qty, match_key)
values (1, 200, 2)

INSERT INTO tbl_allocation (trade_id, qty, match_key)
values (2, 100, 3)

--------------------------------------------------------------------------------------------------------------------



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>