Recursive Matching using CTE Query in SQL Server - sql

I have two tables (they are defined below and you can use the SQL below to build them)
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ETab')
DROP TABLE ETab;
GO
CREATE TABLE ETab
([MRN] varchar(20), [LSPEC] varchar(2), [ADT] DATETIME, [SDT] DATETIME, [Source] varchar(20), [Enum] varchar(20));
GO
INSERT INTO ETab ([MRN], [LSPEC], [ADT], [SDT], [Source], [Enum])
VALUES
('HOMECARE', 'HM', CONVERT(datetime, '2017-04-01 00:00:00.000', 20), CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD04'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-05-01 00:00:00.000', 20), CONVERT(datetime, '2017-05-31 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD05'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), CONVERT(datetime, '2017-06-30 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD06'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-07-01 00:00:00.000', 20), CONVERT(datetime, '2017-07-31 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD07'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-08-01 00:00:00.000', 20), CONVERT(datetime, '2017-08-31 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD08'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-09-01 00:00:00.000', 20), CONVERT(datetime, '2017-09-30 00:00:00.000', 20), 'PRODPAT', 'HOMEBLD09'),
('HOMECARE', 'HQ', CONVERT(datetime, '2017-04-01 00:00:00.000', 20), CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG04HM'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-05-01 00:00:00.000', 20), CONVERT(datetime, '2017-05-31 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG05HM'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), CONVERT(datetime, '2017-06-30 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG06HM'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-07-01 00:00:00.000', 20), CONVERT(datetime, '2017-07-31 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG07HM'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-08-01 00:00:00.000', 20), CONVERT(datetime, '2017-08-31 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG08HM'),
('HOMECARE', 'HM', CONVERT(datetime, '2017-09-01 00:00:00.000', 20), CONVERT(datetime, '2017-09-30 00:00:00.000', 20), 'PRODPAT', 'HOMEDRG09HM'),
('111824', 'UR', CONVERT(datetime, '2017-09-22 00:00:00.000', 20), CONVERT(datetime, '2017-09-22 00:00:00.000', 20), 'OP', 'OP1118240003'),
('111824', 'NL', CONVERT(datetime, '2017-04-19 00:00:00.000', 20), CONVERT(datetime, '2017-04-19 00:00:00.000', 20), 'OP', 'OP1118240001'),
('111824', 'MS', CONVERT(datetime, '2017-06-30 00:00:00.000', 20), CONVERT(datetime, '2017-06-30 00:00:00.000', 20), 'OP', 'OP1118240002'),
('111824', 'MS', CONVERT(datetime, '2017-04-24 00:00:00.000', 20), CONVERT(datetime, '2017-04-24 00:00:00.000', 20), 'IP', 'IP1118240001'),
('111824', 'MS', CONVERT(datetime, '2017-04-28 00:00:00.000', 20), CONVERT(datetime, '2017-04-28 00:00:00.000', 20), 'IP', 'IP1118240005'),
('111824', 'MS', CONVERT(datetime, '2017-04-27 00:00:00.000', 20), CONVERT(datetime, '2017-04-27 00:00:00.000', 20), 'IP', 'IP1118240004'),
('111824', 'MS', CONVERT(datetime, '2017-04-26 00:00:00.000', 20), CONVERT(datetime, '2017-04-26 00:00:00.000', 20), 'IP', 'IP1118240003'),
('111824', 'MS', CONVERT(datetime, '2017-04-25 00:00:00.000', 20), CONVERT(datetime, '2017-04-25 00:00:00.000', 20), 'IP', 'IP1118240002');
GO
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'UTab')
DROP TABLE UTab;
GO
CREATE TABLE UTab
(MRN varchar(20), SIDate DATETIME, LSPEC varchar(2), Source varchar(20), Enum varchar(20), Iteration varchar(20));
GO
INSERT INTO UTab
(MRN, SIDate, LSPEC, Source, Enum, Iteration)
VALUES
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-17 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HQ', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-04-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-01 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-06-26 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-30 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('HOMECARE', CONVERT(datetime, '2017-05-04 00:00:00.000', 20), 'HM', 'N', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-21 00:00:00.000', 20), 'MS', 'IP', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-24 00:00:00.000', 20), 'NL', 'OP', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-27 00:00:00.000', 20), 'NL', 'OP', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'NL', 'OP', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'NL', 'OP', NULL, NULL),
('111824', CONVERT(datetime, '2017-04-20 00:00:00.000', 20), 'NL', 'OP', NULL, NULL);
GO
SELECT * FROM ETab
WHERE Source = 'PRODPAT' AND LSPEC = 'HM'
GO
SELECT * FROM UTab
WHERE LSPEC = 'HM';
GO
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '__Tmp')
DROP TABLE __Tmp;
GO
I have a C# application in which the user requests certian matching clauses at run-time. Using the information specified by the user, I generate some SQL that is executed and updates UTab.
Via the generated SQL, I wish to perform some matching which updates the [UTab].[Enum] based on the link field [MRN] and whether [UTab].[SIDate] lies within [ETab].[ADT] and [ETab].[SDT] +- some days before or after which are specified by the user. So, the user might specify two commands, the first:
MatchCmd:MRN,LSPEC:ETab:UTab:ADT:SDT:SIDate:0:1:'Iteration#1':WHERE [UTab].[Source] = 'OP' AND [UTab].[LSPEC] = [ETab].[LSPEC]
This says, match on MRN AND LSPEC from source table ETab, updating UTab where SIDate > ADT - 0 day(s) and SIDate < SDT + 1 day(s) and where [UTab].[Source] = 'OP' - any matches I mark with the "iteration number" Iteration#1.
My code generates the following SQL:
;WITH cte AS (
SELECT [ETab].[Enum] AS Enum,
[ETab].[MRN] AS Link,
[ETab].[ADT] AS ADT,
[ETab].[SDT] AS SDT,
[UTab].[SIDate] AS DT,
[ETab].[MRN] AS [MRN],
[ETab].[LSPEC] AS [LSPEC],
[ETab].[Source] AS [Source],
ROW_NUMBER() OVER (PARTITION BY [UTab].[MRN], [UTab].[LSPEC], [UTab].[SIDate]
ORDER BY ABS(DATEDIFF(mi, [UTab].[SIDate], [ETab].[ADT]))) AS Idx,
ABS(DATEDIFF(mi, [UTab].[SIDate], [ETab].[ADT])) AS Diff
FROM [UTab]
LEFT JOIN [ETab] ON [UTab].[MRN] = [ETab].[MRN]
WHERE ([UTab].[SIDate] BETWEEN
DATEADD(dd, -0, [ETab].[ADT]) AND
DATEADD(dd, 1, [ETab].[SDT]) AND [Iteration] IS NULL)
AND ETab.Source = 'OP'
) SELECT *
INTO __Tmp
FROM cte;
GO
To get all the records that match the criteria (laying within the time window and abiding by custom where clauses). Then I Update the [UTab].[Enum] and [UTab].[Iteration] via another generated query
UPDATE [UTab]
SET [ENum] = [__Tmp].[ENum], [Iteration] = N'Iteration#1'
--SELECT __Tmp.ENum, __Tmp.Link, __Tmp.LSPEC, __Tmp.ADT, __Tmp.SDT, __Tmp.DT, __Tmp.Idx
FROM [UTab] AS up
INNER JOIN [__Tmp]
ON [up].[MRN] = [__Tmp].[Link]
AND [up].[SIDate] = [__Tmp].[DT]
AND [up].[LSPEC] = [__Tmp].[LSPEC]
WHERE __Tmp.Idx = 1;
This seems to work okay, but some questions:
Q. Is there anything clearly ary with the method/SQL I am using?
Thanks for your time.

The CTE usage was a bit strange to me, since you're not really doing much with it in the subsequent query. I'd move that to the UPDATE.
The query doesn't really join on the Source. I'm not sure if it's meant to do that or not. If UTab has multiple sources for MRN/LSPEC combination, that might result in an issue.
So, I come up with something like:
DECLARE #ADT_Adjustment INT = 0;
DECLARE #SDT_Adjustment INT = 1;
DECLARE #Iteration INT = 1;
WITH SequencedJoin AS (
SELECT
ETab.MRN, ETab.LSPEC, ETab.ADT, ETab.SDT, UTab.SIDate, ETab.Enum, ETab.[Source], UTab.Enum AS WriteEnum, UTab.Iteration AS WriteIteration
, DENSE_RANK() OVER (
PARTITION BY UTab.MRN, UTab.LSPEC, UTab.[Source], UTab.SIDate
ORDER BY ABS( DATEDIFF( MINUTE, UTab.SIDate, ETab.ADT ) )
) AS Ordinal
FROM
#UTab AS UTab
JOIN #ETab AS ETab ON (
ETab.MRN = UTab.MRN
AND ETab.LSPEC = UTab.LSPEC
AND ETab.[Source] = UTab.[Source]
AND UTab.SIDate BETWEEN DATEADD( dd, -#ADT_Adjustment, ETab.ADT ) AND DATEADD( dd, #SDT_Adjustment, ETab.SDT )
)
WHERE
UTab.Iteration IS NULL
)
UPDATE
SequencedJoin
SET
WriteEnum = SequencedJoin.Enum
, WriteIteration = N'Iteration#' + CAST( #Iteration AS VARCHAR( 2 ) )
WHERE
SequencedJoin.[Source] = 'OP'
AND SequencedJoin.Ordinal = 1

up.L != cte.L since you are looking for anything conforming your conditions and filtering by rn.
SELECT cte.E, [Iteration] = N'00-00-00-CA', *
FROM [Up]
INNER JOIN cte ON [Up].[M] = [cte].[M] AND [cte].[rn] = 1
WHERE [cte].[E] IS NOT NULL AND (
[Up].[DTE] BETWEEN
DATEADD(dd, -0, [cte].[ADT]) AND
DATEADD(dd, 0, [cte].[SDT]))
AND [Up].[F] = 'Y'
AND [Up].[S] = 'HC'
----comment this line
--AND [Up].[L] = [cte].[L]; -- <<<<<<<<<<<<<<<<
http://sqlfiddle.com/#!18/d1483/2/0
I modified some data: added ZZ which broke your query totally. Only two rows became matching.
ps
fixed insert issue with length of E column and col name listed in first insert.

Not a complete answer as such, but this index will speed up you CTE:
CREATE INDEX T1 ON UTAB (
MRN,
SIDATE
)
INCLUDE
(
LSPEC,
Iteration
)

Related

PSQL / PgAdmin query issue

Learning Sql, this query returns a syntax error in Pgadmin and Sql shell says there are more entries than target yet there are 8 entries for 8 columns in my table. I've tried specifying the target columns as i've read its good practice to no avail. I'm going off of a course for this, its another random exercise, but the course is frankly useless mixes commands for psql oracle or straight up incorrect ones, basically nothing in it works as it describes. While i'm used to it can't say it helps and leaves me stuck on what's overwhelmingly likely basic syntax written wrong.
Ty for your time.
INSERT INTO EMP(noemp, nomemp, emploi, mgr, dateemb, sal, comm, nodept)
VALUES (
(7369, 'SERGE', 'FONCTIONNAIRE', 7902, TO_DATE('17-DEC-1980', 'DD-MON-YYYY'), 800, NULL, 20),
(7499, 'BRAHIM', 'VENDEUR', 7698, TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30),
(7521, 'NASSIMA', 'VENDEUR', 7698, TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30),
(7566, 'LUCIE', 'GESTIONNAIRE', 7839, TO_DATE('12-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20),
(7654, 'MARTIN', 'VENDEUR', 7698, TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30),
(7698, 'BENJAMIN', 'GESTIONNAIRE', 7839, TO_DATE('01-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30),
(7782, 'DAYANE', 'GESTIONNAIRE', 7839, TO_DATE('09-JUNE-1981', 'DD-MON-YYYY'), 2450, NULL, 10),
(7788, 'ARIJ', 'ANALYSTE', 7566, TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3050, NULL, 20),
(7839, 'MAYAR', 'PRESIDENT', NULL, TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10),
(7844, 'ROI', 'VENDEUR', 7698, TO_DATE('08-SEP-1981', 'DD-MON-YYYY'), 1500, 0, 30),
(7876, 'VIRGINIE', 'FONCTIONNAIRE', 7788, TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20),
(7900, 'LYNA', 'FONCTIONNAIRE', 7698, TO_DATE('03-DEC-1981', 'DD-MON-YYYY'), 950, NULL, 30),
(7902, 'ASMA', 'ANALYSTE', 7566, TO_DATE('03-DEC-1981', 'DD-MON-YYYY'), 3000, NULL, 20),
(7934, 'SIMONE', 'FONCTIONNAIRE', 7782, TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10)
);
Edit: Adding parenthseses (which i add at some point, cf below gets) rid of line 4 error and returns line 11 error instead, same text.
Edit2: TLdr there was a typo on one month and lacked proper formatting. Ty all.
I found a french month name in your SQL Code (JUIN) :
7782, ’DAYANE’, ’GESTIONNAIRE’, 7839, TO_DATE(’9-**JUIN**-1981', ’DD-MON-YYYY’), 2450, NULL, 10,
it must be remplaced by 'JUNE'.
Try to put each record between parenthesis like that :
INSERT INTO EMP(noemp, nomemp, emploi, mgr, dateemb, sal, comm, nodept)
VALUES (7369, 'SERGE', 'FONCTIONNAIRE', 7902, TO_DATE('17-DEC-1980', 'DD-MON-YYYY'), 800, NULL, 20),
(7499, 'BRAHIM', 'VENDEUR', 7698, TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30),
(7521, 'NASSIMA', 'VENDEUR', 7698, TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30),
(7566, 'LUCIE', 'GESTIONNAIRE', 7839, TO_DATE('12-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20),
(7654, 'MARTIN', 'VENDEUR', 7698, TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30),
(7698, 'BENJAMIN', 'GESTIONNAIRE', 7839, TO_DATE('01-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30),
(7782, 'DAYANE', 'GESTIONNAIRE', 7839, TO_DATE('9-JUNE-1981', 'DD-MON-YYYY'), 2450, NULL, 10),
(7788, 'ARIJ', 'ANALYSTE', 7566, TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3050, NULL, 20),
(7839, 'MAYAR', 'PRESIDENT', NULL, TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10),
(7844, 'ROI', 'VENDEUR', 7698, TO_DATE('08-SEP-1981', 'DD-MON-YYYY'), 1500, 0, 30),
(7876, 'VIRGINIE', 'FONCTIONNAIRE', 7788, TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20),
(7900, 'LYNA', 'FONCTIONNAIRE', 7698, TO_DATE('03-DEC-1981', 'DD-MON-YYYY'), 950, NULL, 30),
(7902, 'ASMA', 'ANALYSTE', 7566, TO_DATE('03-DEC-1981', 'DD-MON-YYYY'), 3000, NULL, 20),
(7934, 'SIMONE', 'FONCTIONNAIRE', 7782, TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10)
You can verify it with this link

i want to replace series of numbers in my sql file how can i if i am using sublime text

(4197, 282, '342', 19, 1, 12, '0', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4194, 282, '331', 19, 1, 12, '1', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4189, 282, '336', 19, 1, 11, '0', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4193, 282, '332', 19, 1, 12, '1', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4192, 282, '333', 19, 1, 11, '0', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4160, 282, '350', 19, 3, 11, '0', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 1),
(4190, 282, '335', 19, 1, 12, '1', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4188, 282, '337', 19, 1, 12, '0', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
(4187, 282, '338', 19, 1, 12, '1', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, NULL),
Here is some sample of the series 4197 to 4187 how can i replace it???
To replace multiple instance of a same word in sublime you have to press Ctrl + D and select the multiple instance and you can edit all of them at once.
Alternatively you can use find and replace feature
Read more about multiple selection in sublime here: http://www.sublimetext.com/docs/3/multiple_selection_with_the_keyboard.html

Deriving the first instance of a specific node type in a tree structure query using SQL

I am designing an Electrical design software that will model an electrical utility system from the incoming Power Utility right down to the individual circuits such as computers and coffee machines.
I want to give each component of the system a dedicated table. eg. Transformers, Loads, cables, PowerPanels (called buses in this example).
Each component can be connected to one or many other components. I am using a parent/child table to manage the connections and plan to use a CTE to derive the hierarchical tree structure for a given component.
The voltage supplying any component in the system will be derived by finding the first instance of a transformer or a utility in the tree.
I have developed a query that can handle this as demonstrated below.
However, this only works for selecting one component in the CTE. I am looking for a way to select all buses and their connected voltage (nearest trafo or Utility). The only solution I can come up with is to use a table function on the above query. Is there a better way of doing this.
CREATE TABLE #componentConnection
(componentConnectionID int, parentComponentID varchar(4), childComponentID int)
;
INSERT INTO #componentConnection
(componentConnectionID, parentComponentID, childComponentID)
VALUES
(1, '13', 18),
(2, '13', 19),
(3, '13', 20),
(4, '13', 21),
(5, '13', 22),
(6, '13', 23),
(7, '14', 24),
(8, '14', 25),
(9, '14', 26),
(10, '14', 27),
(11, '14', 28),
(12, '14', 29),
(13, '15', 30),
(14, '15', 31),
(15, '15', 32),
(16, '15', 33),
(17, '15', 34),
(18, '15', 35),
(19, '16', 36),
(20, '16', 37),
(21, '16', 38),
(22, '16', 39),
(23, '16', 40),
(24, '16', 41),
(25, '1', 5),
(27, '5', 13),
(28, NULL, 1),
(29, '18', 6),
(30, '6', 11),
(31, '11', 7),
(32, '7', 14)
;
CREATE TABLE #component
(componentID int, componentName varchar(8), componentType varchar(7))
;
INSERT INTO #component
(componentID, componentName, componentType)
VALUES
(1, 'Utility1', 'utility'),
(2, 'Utility2', 'utility'),
(3, 'utility3', 'utility'),
(4, 'utility4', 'utility'),
(5, 'Cable1', 'cable'),
(6, 'Cable2', 'cable'),
(7, 'Cable3', 'cable'),
(8, 'Cable4', 'cable'),
(9, 'Cable5', 'cable'),
(10, 'Cable6', 'cable'),
(11, 'Trafo1', 'trafo'),
(12, 'Trafo2', 'trafo'),
(13, 'Bus1', 'bus'),
(14, 'Bus2', 'bus'),
(15, 'Bus3', 'bus'),
(16, 'Bus4', 'bus'),
(17, 'Bus5', 'bus'),
(18, 'cub1', 'cir'),
(19, 'cub2', 'cir'),
(20, 'cub3', 'cir'),
(21, 'cub4', 'cir'),
(22, 'cub5', 'cir'),
(23, 'cub6', 'cir'),
(24, 'cub1', 'cir'),
(25, 'cub2', 'cir'),
(26, 'cub3', 'cir'),
(27, 'cub4', 'cir'),
(28, 'cub5', 'cir'),
(29, 'cub6', 'cir'),
(30, 'cub1', 'cir'),
(31, 'cub2', 'cir'),
(32, 'cub3', 'cir'),
(33, 'cub4', 'cir'),
(34, 'cub5', 'cir'),
(35, 'cub6', 'cir'),
(36, 'cub1', 'cir'),
(37, 'cub2', 'cir'),
(38, 'cub3', 'cir'),
(39, 'cub4', 'cir'),
(40, 'cub5', 'cir'),
(41, 'cub6', 'cir')
;
CREATE TABLE #utility
([utilityID] int, [componentID] int, [utlityKV] float)
;
INSERT INTO #utility
([utilityID], [componentID], [utlityKV])
VALUES
(1, 1, 0.4),
(2, 2, 0.208),
(4, 3, 0.48),
(5, 4, 0.208)
;
CREATE TABLE #transformer
([transformerID] int, [componentID] int, [facilityID] int, [transformerName] varchar(4), [transformerPrimaryTapKv] float, [transformerSecondaryTapKv] float, [transformerPrimaryKv] float, [transformerSecondaryKv] float)
;
INSERT INTO #transformer
([transformerID], [componentID], [facilityID], [transformerName], [transformerPrimaryTapKv], [transformerSecondaryTapKv], [transformerPrimaryKv], [transformerSecondaryKv])
VALUES
(3, 11, 1, NULL, 0.48, 0.208, 0.48, 0.208),
(4, 12, 2, NULL, 0.48, 0.4, 0.48, 0.4)
;
CREATE TABLE #Bus
([busID] int, [busTypeID] int, [componentID] int, [bayID] int, [busName] varchar(4), [busConductorType] varchar(6), [busRatedCurrent] int)
;
INSERT INTO #Bus
([busID], [busTypeID], [componentID], [bayID], [busName], [busConductorType], [busRatedCurrent])
VALUES
(8, 1, 13, 1, 'bus1', 'Copper', 60),
(9, 1, 14, 1, 'bus2', 'copper', 50),
(10, 2, 15, 1, 'bus3', 'copper', 35),
(11, 2, 16, 1, 'bus4', 'copper', 35),
(13, 1, 17, 1, 'bus5', 'copper', 50)
;
WITH CTE AS (SELECT childComponentID AS SourceID, childComponentID, 0 AS depth
FROM #ComponentConnection
UNION ALL
SELECT C1.SourceID, C.childComponentID, c1.depth + 1 AS depth
FROM #ComponentConnection AS C INNER JOIN
CTE AS C1 ON C.parentComponentID = C1.childComponentID)
SELECT childComponentID,b.busName, min(depth)
--,c.componentType
,isnull(t.transformerSecondaryKv,u.utlityKV) kV
FROM CTE AS CTE1
join #Component c
on CTE1.SourceID = c.componentID
left join #Utility u
on CTE1.SourceID = u.componentID
left join #Transformer t
on CTE1.SourceID = t.componentID
LEFT JOIN #Bus b
on cte1.childComponentID = b.componentID
where busName is not null and c.componentType in ('Utility','trafo')
group by childComponentID,b.busName,isnull(t.transformerSecondaryKv,u.utlityKV)
order by depth
The desired result would be as follows for a Bus. I want to list all Buses and their associated Voltage. I would select all from the Bus table and derive the voltage from the heirarchical structure
Result
BusName | Voltage
Bus 1 | 0.4
Bus 2 | 0.208
Bus 3 | etc

nested select TOP 1 statement

I am working on a system currently for Asset Management within our company.
The system allows users to sign in/out items on either a permenant or temporary basis.
I am working on some reporting on the system and have hit a stumbling block with returning the relevent data.
So i know that i need a nested Select TOP 1 statement within my main query but i cant get it to work.
The main query is as follows:
SELECT [Asset-User].ID, [Asset-User].Asset_ID, [Assets].ID, [Assets].Signed_Out, [Assets].Asset_Tag_Serial_Num, [Assets].Name_Hostname, [Assets].Type_ID, [Asset_Type].ID, [Asset_Type].Name_Model, [Asset-User].User_ID, [Company_Users].ID, [Asset-User].Sign_Out_Date, [Asset-User].Return_Date, [Asset-User].[Perm_Signout?]
FROM [Asset-User], [Assets], [Asset_Type], [Company_Users]
WHERE ([User_ID] = '1') AND [Asset-User].Asset_ID = [Assets].ID AND [Assets].Type_ID = [Asset_Type].ID AND [Asset-User].User_ID = [Company_Users].ID AND [Assets].Signed_Out = '1'
So this query returns everything that is currently marked as "Signed Out" that has ever been signed out by User 1.
Somewhere in here i need to add a nested Select TOP 1 on Asset-User.ID so that it only returns items that are marked as permanent sign outs, OR if not permanent that they have most recently been signed out by User 1.
This would then only give me a list of items currently assigned to that user and not display the Asset if someone else has signed it out since
Any help would be greatly appreciated
As per request Sample data below:
https://docs.google.com/spreadsheets/d/1o4T6bsxyO-1dGE0-FUtWFboRupcq4o4V9i2Em0_BjyU/edit?usp=sharing
First sheet shows actual results, second sheet shows roughly what should be expected
As you will see here, this user has signed out a few items multiple times (and those items may not most recently have been signed out by this user)
Its hard to get the sample data but in essence there should be no duplicate Asset_ID's in the list as only the most recent ID (sign out ID this relates to) should be displayed for each Asset_ID.
Does that help?
Thanks again
As per request here is the Schema build code that will create a sample DB to work with
CREATE TABLE Asset_Type
([ID] int, [Global_ID] int, [Name_Model] varchar(30), [Description_Spec] varchar(54))
;
INSERT INTO Asset_Type
([ID], [Global_ID], [Name_Model], [Description_Spec])
VALUES
(1, 1, 'Dell Optiplex 3020', 'Windows 7 Professional, Intel Core i3 3.40GHz,4Gb RAM'),
(2, 3, 'Viewsonic VA2231wa', 'Viewsonic Widescreen Monitor'),
(3, 3, 'Samsung S24B150BL', 'Samsung LED 24" Widescreen Monitor')
;
CREATE TABLE Assets
([ID] int, [Asset_Tag_Serial_Num] varchar(29), [Type_ID] int, [Purchase_Date] varchar(10), [Purchase_Price] varchar(7), [Name_Hostname] varchar(36), [Signed_Out] int)
;
INSERT INTO Assets
([ID], [Asset_Tag_Serial_Num], [Type_ID], [Purchase_Date], [Purchase_Price], [Name_Hostname], [Signed_Out])
VALUES
(1, '0206', 1, '2013-11-29', '323.30', 'WS0206', 1),
(3, '0226', 2, NULL, NULL, 'Viewsonic VA2231wa - 0226', 1),
(4, '0204', 1, '2013-11-29', '323.00', 'WS0204', 1),
(5, '0205', 1, '2013-11-29', '323.00', 'WS0205', 1),
(6, '0108', 1003, NULL, NULL, 'Small Office Sat Nav', 1),
(7, '0092', 1004, NULL, NULL, 'Large Office Sat Nav', 1),
(8, 'GWC36-DHDBC-J2MXY-H2BGY-8C79G', 1005, '1900-01-01', '0.00', 'MS Office for WS0020', 1),
(9, '0020', 1006, '1900-01-01', '0.00', 'WS0020', 1),
(10, '0173', 2, '1900-01-01', '0.00', 'Viewsonic VA2231wa - 0173', 1),
(11, '0172', 1007, '1900-01-01', '0.00', 'Dell 19" Monitor 0172', 1),
(12, '00104926EC6B', 1008, '1900-01-01', '0.00', 'Shortel 230 - EC6B', 1),
(13, '0227', 1009, NULL, NULL, 'Blue - Yeti Mic', 0),
(14, '0221', 1, NULL, NULL, 'WS0221', 1),
(15, '0222', 1, '2013-11-29', '323.00', 'WS0222', 1),
(16, '0223', 1, NULL, NULL, 'WS0223', 1),
(17, '0220', 1, '2013-11-29', '323.00', 'WS0220', 1),
(18, '0217', 1, '2013-11-29', '323.00', 'WS0217', 1),
(19, '0218', 1, NULL, NULL, 'WS0218', 1),
(20, '0219', 1, '2013-11-29', '323.00', 'WS0219', 1),
(21, '0228', 2, NULL, NULL, 'Viewsonic VA2231wa - 0228', 1),
(22, '0229', 1010, NULL, NULL, 'Dell 19" Monitor 0229', 1),
(23, '00104931AA16', 1011, NULL, NULL, 'Shortel 115 - AA16', 1),
(24, '0093 - DYTJ18X4DJ8T', 1012, NULL, NULL, 'Office IPad 3', 1),
(25, '0095', 1013, '1900-01-01', '0.00', '320Gb External HDD', 1),
(26, '0071', 1014, NULL, NULL, '0071 - NEC Projector', 0),
(27, '0072', 1015, NULL, NULL, '0072 - Black Dell Projector', 0),
(28, '0073', 1016, '1900-01-01', '0.00', '0073 - Dell Projector', 0),
(29, '0230', 1017, '1900-01-01', '0.00', '0230 - Silver Dell Projector', 0),
(30, '0064', 1018, NULL, NULL, 'WS0064', 0),
(31, '0231', 1019, NULL, NULL, 'Freecom 1GB Pen - 0231', 1),
(47, '0165', 2, NULL, NULL, 'Viewsonic VA2231wa - 0165', 1),
(48, '0232', 1010, '1900-01-01', '0.00', 'Dell 19" Monitor 0232', 1),
(49, '0233', 1010, '1900-01-01', '0.00', 'Dell 19" Monitor 0233', 1),
(50, '0137', 1022, NULL, NULL, 'Viewsonic VA2248-LED - 0137', 1),
(51, '0234', 1010, '1900-01-01', '0.00', 'Dell 19" Monitor 0234', 1),
(52, '0235', 1010, '1900-01-01', '0.00', 'Dell 19" Monitor 0235', 1),
(53, '0134', 1010, NULL, NULL, 'Dell 19" Monitor 0134', 0),
(54, '0135', 1022, NULL, NULL, 'Viewsonic VA2248-LED - 0135', 1),
(55, '0236', 3, '1900-01-01', '0.00', 'Samsung S24B150BL - 0236', 1),
(56, '001049201D9A', 1008, '1900-01-01', '0.00', 'Shortel 230 - 1D9A', 1),
(57, '0010492015AE', 1008, '1900-01-01', '0.00', 'Shortel 230 - 15AE', 1),
(93, '0269', 1029, '1900-01-01', '0.00', 'TP-Link Switch - 0269', 0),
(94, '0058', 1030, NULL, NULL, 'WS0058', 1),
(95, '0270', 1031, NULL, NULL, 'MeetingRoom3', 1),
(96, '0243', 1032, NULL, NULL, 'MeetingRoom2', 1),
(97, '0271', 1027, NULL, NULL, 'Dynamode SW80010-D Switch - 0271', 0),
(123, '0281', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0281', 0),
(124, '0282', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0282', 1),
(125, '0283', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0283', 0),
(126, '0284', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0284', 1),
(127, '0285', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0285', 1),
(128, '0286', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0286', 1),
(129, '0287', 1045, '2014-07-18', '104.50', 'Philips 23.6" Monitor 0287', 1),
(143, '0280', 1, '2014-07-03', '403.80', 'WS0280', 1),
(144, '0296', 1, '2014-07-03', '403.80', 'WS0296', 1),
(145, '0297', 1, '2014-07-03', '403.80', 'WS0297', 1),
(146, '0298', 1, '2014-07-03', '403.80', 'WS0298', 1),
(147, '0299', 1, '2014-07-03', '403.80', 'WS0299', 1),
(148, '0052', 1036, '1900-01-01', '0.00', 'WS0052', 1),
(168, '0312', 1047, NULL, NULL, 'Epson White HD - 0312', 1),
(169, '0201', 1049, '1900-01-01', '0.00', 'Ipad 4 - 0201', 0),
(170, 'HP27J-2C496-83KXB-RGMX6-8QJQG', 1020, '1900-01-01', '0.00', 'MS Office for Jonny D', 1),
(171, '7N4QY-DFGWD-P6662-CFCHG-QYFP2', 1021, '1900-01-01', '0.00', 'MS Office for WS0215 (Simeon Laptop)', 1),
(172, '0140', 1022, '1900-01-01', '0.00', 'Viewsonic VA2248-LED - 0140', 1),
(198, '0109', 1037, '1900-01-01', '0.00', 'WS0109', 1),
(199, '0324', 1052, '1900-01-01', '0.00', 'Philips 23.6" Monitor 0324', 1)
;
CREATE TABLE [Asset-User]
([ID] int, [Asset_ID] int, [User_ID] int, [Sign_Out_Date] datetime, [Return_Date] datetime, [Perm_Signout] int)
;
INSERT INTO [Asset-User]
([ID], [Asset_ID], [User_ID], [Sign_Out_Date], [Return_Date], [Perm_Signout])
VALUES
(2, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(3, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(4, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(5, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(6, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(7, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(8, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(9, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(10, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(11, 1, 1, '2014-03-29 00:00:00', '2014-03-29 00:00:00', 0),
(1002, 1, 1, '2014-04-01 00:00:00', '2014-04-01 00:00:00', 0),
(1003, 1, 1, '2014-01-01 00:00:00', '2014-01-01 00:00:00', 1)
;
CREATE TABLE Company_Users
([ID] int, [Name] varchar(14), [Domain_Username] varchar(14), [Dept] varchar(16), [Email] varchar(25), [DD_Ext] int, [Job_Title] varchar(30), [Deleted_Left] int)
;
INSERT INTO Company_Users
([ID], [Name], [Domain_Username], [Dept], [Email], [DD_Ext], [Job_Title], [Deleted_Left])
VALUES
(1, 'Neil Smithson', 'Neil.Smithson', '2nd Line Support', 'neil.smithson#dezrez.com', 3041, 'Second Line Support Technician', 0)
;
CREATE TABLE Global_Types
([ID] int, [Name] varchar(13), [Description] varchar(54))
;
INSERT INTO Global_Types
([ID], [Name], [Description])
VALUES
(1, 'PC', 'Desktop PC')
;
This is not really an answer but will show you how you could rework this query using aliases and the (not really) newer join style.
SELECT au.ID
, au.Asset_ID
, a.ID
, a.Signed_Out
, a.Asset_Tag_Serial_Num
, a.Name_Hostname
, a.Type_ID
, at.ID
, at.Name_Model
, au.User_ID
, cu.ID
, au.Sign_Out_Date
, au.Return_Date
, au.[Perm_Signout?]
FROM [Asset-User] au
join Assets a on au.Asset_ID = a.ID
join Asset_Type at on a.Type_ID = at.ID
join Company_Users cu on au.User_ID = cu.ID
WHERE au.User_ID = '1'
AND a.Signed_Out = '1'

Properly using the Count Function

In the Enrollment_Changes table, the phone model listed is the phone the subscriber changed FROM on that date.
If there is no subsequent change on Enrollment_Changes, the phone the subscriber changed TO is listed on the P_Enrollment table
For example, subscriber 12345678 enrolled on 1/5/2011 with a RAZR. On 11/1/2011 he changed FROM the RAZR. You can see what he changed TO with the next transaction on Enrollment_Changes on 05/19/2012.
How would you find the Count of subs that first enrolled with the iPhone 3?
Here is the code I have for creating the tables
Create Tables: TBL 1
USE [Test2]
GO
/****** Object: Table [dbo].[P_ENROLLMENT] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[P_ENROLLMENT](
[Subid ] [float] NULL,
[Enrollment_Date] [datetime] NULL,
[Channel] [nvarchar](255) NULL,
[Region] [nvarchar](255) NULL,
[Active_Status] [float] NULL,
[Drop_Date] [datetime] NULL,
[Phone_Model] [nvarchar](255) NULL
) ON [PRIMARY]
GO
TBL 2
USE [Test2]
GO
/****** Object: Table [dbo].[ENROLLMENT_CHANGES] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ENROLLMENT_CHANGES](
[Subid] [float] NULL,
[Cdate] [datetime] NULL,
[Phone_Model] [nvarchar](255) NULL
) ON [PRIMARY]
GO
Insert TBL1
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12345678, '2011-01-05 00:00:00', 'Retail', 'Southeast', 1, NULL, 'iPhone 4');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12346178, '2011-03-13 00:00:00', 'Indirect Dealers', 'West', 1, NULL, 'HTC Hero');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12346679, '2011-05-19 00:00:00', 'Indirect Dealers', 'Southeast', 0, '2012-03-15 00:00:00', 'Droid 2');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12347190, '2011-07-25 00:00:00', 'Retail', 'Northeast', 0, '2012-05-21 00:00:00', 'iPhone 4');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12347701, '2011-08-14 00:00:00', 'Indirect Dealers', 'West', 1, NULL, 'HTC Hero');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12348212, '2011-09-30 00:00:00', 'Retail', 'West', 1, NULL, 'Droid 2');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12348723, '2011-10-20 00:00:00', 'Retail', 'Southeast', 1, NULL, 'Southeast');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12349234, '2012-01-06 00:00:00', 'Indirect Dealers', 'West', 0, '2012-02-14 00:00:00', 'West');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12349745, '2012-01-26 00:00:00', 'Retail', 'Northeast', 0, '2012-04-15 00:00:00', 'HTC Hero');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12350256, '2012-02-11 00:00:00', 'Retail', 'Southeast', 1, NULL, 'iPhone 4');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12350767, '2012-03-02 00:00:00', 'Indirect Dealers', 'West', 1, NULL, 'Sidekick');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12351278, '2012-04-18 00:00:00', 'Retail', 'Midwest', 1, NULL, 'iPhone 3');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12351789, '2012-05-08 00:00:00', 'Indirect Dealers', 'West', 0, '2012-07-04 00:00:00', 'iPhone 3');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12352300, '2012-06-24 00:00:00', 'Retail', 'Midwest', 1, NULL, 'Droid 2');
INSERT INTO [P_ENROLLMENT]([Subid ], [Enrollment_Date], [Channel], [Region], [Active_Status], [Drop_Date], [Phone_Model])
VALUES(12352811, '2012-06-25 00:00:00', 'Retail', 'Southeast', 1, NULL, 'Sidekick');
Insert TBL2
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12345678, '2011-11-01 00:00:00', 'RAZR');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12346178, '2012-01-07 00:00:00', 'HTC Hero');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12348723, '2012-01-28 00:00:00', 'RAZR');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12350256, '2012-02-21 00:00:00', 'Blackberry Bold');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12349745, '2012-05-05 00:00:00', 'HTC Hero');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12345678, '2012-05-19 00:00:00', 'Palm Pre');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12347190, '2012-05-20 00:00:00', 'HTC Hero');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12350256, '2012-05-21 00:00:00', 'Blackberry Bold');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12349234, '2012-06-04 00:00:00', 'Palm Pre');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12346178, '2012-06-05 00:00:00', 'iPhone 3');
INSERT INTO [ENROLLMENT_CHANGES]([Subid], [Cdate], [Phone_Model])
VALUES(12350767, '2012-06-10 00:00:00', 'iPhone 3');
For the count
select COUNT(*) Total
from
(
select e.*,
rn = row_number() over (partition by e.subid order by c.cdate desc),
first_model = coalesce(c.phone_model, e.phone_model)
from [P_ENROLLMENT] e
left join [ENROLLMENT_CHANGES] c on c.subid = e.subid
) x
where rn=1 and first_model = 'iPhone 3'
For all the records
select *
from
(
select e.*,
rn = row_number() over (partition by e.subid order by c.cdate desc),
first_model = coalesce(c.phone_model, e.phone_model)
from [P_ENROLLMENT] e
left join [ENROLLMENT_CHANGES] c on c.subid = e.subid
) x
where rn=1 and first_model = 'iPhone 3'
order by subid
You want to know if the first record in the table is an iPhone 3. Something like this:
select count(*)
from (select e.*,
row_number() over (partition by subid order by enrollment_date) as seqnum
from p_enrollment e
) e
where seqnum = 1 and phone_model = 'iPhone 3'
Perhaps I'm thinking too simply, but wouldn't either of the following do what you're looking for?:
SELECT Phone_Model
, COUNT(*) AS Initially_Enrolled
FROM p_enrollment
GROUP BY Phone_Model
(working SQLFiddle: http://sqlfiddle.com/#!3/68258/4)
or
SELECT COUNT(*) AS Initially_Enrolled
FROM p_enrollment
WHERE Phone_Model = 'iPhone 3'
(working SQLFiddle: http://sqlfiddle.com/#!3/68258/3)
Since you only want initial enrollment, the ENROLLMENT_CHANGES table is irrelevant.