All,
I'm trying to pull off an insert from one table to another without using dynamic sql. However, the only solutions I'm coming up with at the moment use dynamic sql. It's been tricky to search for any similar scenarios.
Here are the details:
My starting point is the following legacy table:
CREATE TABLE [dbo].[_Combinations](
[AttributeID] [int] NULL,
[Value] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (16, N'1')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (16, N'2')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Red')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Orange')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Yellow')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Green')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Blue')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Indigo')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'Violet')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'A')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'B')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'C')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'D')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'E')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'F')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'G')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'H')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'I')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'J')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'K')
SELECT * FROM _Combinations
The _Combinations table contains a key for different types of attributes (AttributeID) and the possible values for each attribute (Value).
In this case, there are 3 different attributes with multiple possible values, however there can be many more (up to 10).
The requirement is then to create every possible combination of each value and store it normalized, as there will be other data stored with each possible combination. I need to store both the attribute keys and values that make up each combination, so it's not just a simple cross join to display each combination. The target table for storing each combination of attributes is this:
CREATE TABLE [dbo].[_CombinedAttributes](
[GroupKey] [int] NULL,
[AttributeID] [int] NULL,
[Value] [varchar](50) NULL
) ON [PRIMARY]
So attribute combination records using the above data would look like this in the target table:
GroupKey AttributeID Value
1 8 A
1 16 1
1 28 Red
2 8 B
2 16 1
2 28 Red
This gives me what I need. Each group has an identifier and I can track the attributeIDs and values that make up each group. I'm using two scripts to get from the _Combinations table to the format of the _CombinedAttributes table:
-- SCRIPT #1
SELECT Identity(int) AS RowNumber, * INTO #Test
FROM (
SELECT AttributeID AS Attribute1, Value AS Value1 FROM _Combinations WHERE AttributeID = 8) C1
CROSS JOIN
(
SELECT AttributeID AS Attribute2, Value AS Value2 FROM _Combinations WHERE AttributeID = 16) C2
CROSS JOIN
(
SELECT AttributeID AS Attribute3, Value AS Value3 FROM _Combinations WHERE AttributeID = 28) C3
-- SCRIPT #2
INSERT INTO _CombinedAttributes
SELECT RowNumber AS GroupKey, Attribute1, Value1
FROM #Test
UNION ALL
SELECT RowNumber, Attribute2, Value2
FROM #Test
UNION ALL
SELECT RowNumber, Attribute3, Value3
FROM #Test
ORDER BY RowNumber, Attribute1
The above two scripts work, but obviously there's some drawbacks. Namely I need to know how many attributes I'm dealing with and there's hard coding of IDs, so I can't generate this on the fly. The solution I came up with is I build the strings for Script 1 and Script 2 by looping through the attributes in the the _Combinations table and generate execution strings which is long and messy but I can post if needed. Can anyone see a way to pull off the format for the final insert without dynamic sql?
This routine wouldn't be run very much, but it's going to be run enough that I'd like to not be doing any execute string building and use straight SQL.
Thanks in advance.
UPDATE:
When I use a second dataset, Gordon's code is no longer returning correct results, it's creating groups with only 1 attribute near the end, however on this second dataset I get the correct rowcount with Nathan's routine (row count on final result should be 396). But as I stated on the comments, if I use the first dataset, I get the opposite result, Gordon's returns correctly, but Nathan's code has dups. I'm at a loss. Here is the second data set:
DROP TABLE [dbo].[_Combinations]
GO
CREATE TABLE [dbo].[_Combinations](
[AttributeID] [int] NULL,
[Value] varchar NULL
) ON [PRIMARY]
GO
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (16, N'1')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (16, N'2')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'<=39')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'40-44')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'45-49')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'50-54')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'55-64')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (28, N'65+')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'AA')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'JJ')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'CC')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'DD')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'EE')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'KK')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'BB')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'FF')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'GG')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'HH')
INSERT [dbo].[_Combinations] ([AttributeID], [Value]) VALUES (8, N'II')
I think this solves your problem.
Here is the approach. First, observe that the final data has the product of the number of each attribute -- 2*7*11 = 154 rows. Then observe that each value occurs a fixed number of times. For AttributeId = 16, each value occurs 154 / 2, because there are two values.
So, the idea is to calculate the number of times that each value appears. Then, generate the list of all the values. The final challenge is to assign the group numbers to these. For this, I use row_number() partitioned by the attribute id. To be honest, I'm not 100% that the grouping assignment is correct (it makes sense and it passed the eyeball test), but I'm worried that I'm missing a subtlety.
Here is the query:
with attributecount1 as (
select c.AttributeId, count(*) as cnt
from _Combinations c
group by c.AttributeId
),
const as (
select exp(sum(log(cnt))) as tot, count(*) as numattr
from attributecount1
),
attributecount as (
select a.*,
(tot / a.cnt) as numtimes
from attributecount1 a cross join const
),
thevalues as (
select c.AttributeId, c.Value, ac.numtimes, 1 as seqnum
from AttributeCount ac join
_Combinations c
on ac.AttributeId = c.AttributeId
union all
select v.AttributeId, v.Value, v.numtimes, v.seqnum + 1
from thevalues v
where v.seqnum + 1 <= v.numtimes
)
select row_number() over (partition by AttributeId order by seqnum, Value) as groupnum,
*
from thevalues
order by 1, 2
The SQL Fiddle is here.
EDIT:
Unfortunately, I don't have access to SQL Server today and SQL Fiddle is acting up.
The problem is solvable. The above solution works, but -- as stated in my comment -- only when the dimensions are pairwise mutually prime. The problem is the assignment of the group number to the values. It turns out that this is a problem in number theory.
Essentially, we want to enumerate the combinations. If there were 2 in two groups, then it would be:
group 0: 1 1
group 1: 1 2
group 2: 2 1
group 3: 2 2
You can see a relationship between the group number and which values are assigned -- based on the binary representation of the group number. If this were 2x3, then it would look like:
group 0: 1 1
group 1: 1 2
group 2: 1 3
group 3: 2 1
group 4: 2 2
group 5: 2 3
Same idea, but now there is not "binary" representation. Each position in the number would have a different base. No problem.
So, the challenge is mapping a number (such as the group number) to each digit. This requires appropriate division and modulo arithmetic.
The following implements this in Postgres:
with c as (
select 1 as attrid, '1' as val union all
select 1 as attrid, '2' as val union all
select 2 as attrid, 'A' as val union all
select 2 as attrid, 'B' as val union all
select 3 as attrid, '10' as val union all
select 3 as attrid, '20' as val
),
c1 as (
select c.*, dense_rank() over (order by attrid) as attrnum,
dense_rank() over (partition by attrid order by val) as valnum,
count(*) over (partition by attrid) as cnt
from c
),
a1 as (
select attrid, count(*) as cnt,
cast(round(exp(sum(ln(count(*))) over (order by attrid rows between unbounded preceding and current row))) as int)/count(*) as cum
from c
group by attrid
),
a2 as (
select a.*,
(select cast(round(exp(sum(ln(cnt)))) as int)
from a1
where a1.attrid <= a.attrid
) / cnt as cum
from a1 a
),
const as (
select cast(round(exp(sum(ln(cnt)))) as int) as numrows
from a1
),
nums as (
select 1 as n union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8
from const
),
ac as (
select c1.*, a1.cum, const.numrows
from c1 join
a1 on c1.attrid = a1.attrid cross join
const
)
select *
from nums join
ac
on (nums.n/cum) % cnt = valnum - 1
order by 1, 2;
(Note: generate_series() was not working correctly for some reason with certain joins, which is why it manually generates the sequence of numbers.)
When SQL Fiddle gets working again, I should be able to translate this back to SQL Server.
EDIT II:
Here is the version that works in SQL Server:
with attributecount1 as (
select c.AttributeId, count(*) as cnt
from _Combinations c
group by c.AttributeId
),
const as (
select cast(round(exp(sum(log(cnt))), 1) as int) as tot, count(*) as numattr
from attributecount1
),
attributecount as (
select a.*,
(tot / a.cnt) as numtimes,
(select cast(round(exp(sum(log(ac1.cnt))), 1) as int)
from attributecount1 ac1
where ac1.AttributeId <= a.AttributeId
) / a.cnt as cum
from attributecount1 a cross join const
),
c as (
select c.*, ac.numtimes, ac.cum, ac.cnt,
dense_rank() over (order by c.AttributeId) as attrnum,
dense_rank() over (partition by c.AttributeId order by Value) as valnum
from _Combinations c join
AttributeCount ac
on ac.AttributeId = c.AttributeId
),
nums as (
select 1 as n union all
select 1 + n
from nums cross join const
where 1 + n <= const.tot
)
select *
from nums join
c
on (nums.n / c.cum)%c.cnt = c.valnum - 1
option (MAXRECURSION 1000)
THe SQL Fiddle is here.
Years ago I faced a similar problem with a fixed EAV schema not unlike yours. Peter Larsson came up with the below solution to address my "dynamic combinations" query.
I've adapted it to fit your schema. Hope this helps!
SqlFiddle Here
;with cteSource (Iteration, AttributeID, recID, Items, Unq, Perm) as
(
select v.Number + 1,
s.AttributeId,
row_number() over (order by v.Number, s.AttributeID) - 1,
s.Items,
u.Unq,
f.Perm
from (select AttributeID, count(*) from _Combinations group by AttributeID) s(AttributeId, Items)
cross
join (select count(distinct AttributeID) from _Combinations) u (Unq)
join master..spt_values as v on v.Type = 'P'
outer
apply (
select top(1) cast(exp(sum(log(count(*))) over ()) as bigint)
from _Combinations as w
where w.AttributeID >= s.AttributeID
group
by w.AttributeID
having count(*) > 1
) as f(Perm)
where v.Number < (select top(1) exp(sum(log(count(*))) over()) from _Combinations as x group by x.AttributeID)
)
select s.Iteration,
s.AttributeID,
w.Value
from cteSource as s
cross
apply (
select Value,
row_number() over (order by Value) - 1
from _Combinations
where AttributeID = s.AttributeID
) w(Value, recID)
where coalesce(s.recID / (s.Perm * s.Unq / s.Items), 0) % s.Items = w.recID
order
by s.Iteration, s.AttributeId;
I've decided to post this, just for the sake of a procedural solution appearing in parallel with the CTE-based ones.
The following produces a zero-based GroupKey column. If you want it to start from 1, simply change #i to #i+1 in the last insert ... select.
-- Add a zero-based row number, partitioned by AttributeId
declare #Attrs table (AttributeId int,Value varchar(50),RowNum int)
insert into #Attrs
select
AttributeId,Value,
ROW_NUMBER()over(partition by AttributeId order by AttributeId,Value)-1
from _Combinations
-- AttributeId value counts
declare #AttCount table (AttributeId int,n int)
insert into #AttCount
select AttributeId,COUNT(*) n from #Attrs
group by AttributeID
-- Total number of combos -- Multiply all AttributeId counts
-- EXP(SUM(LOG(n))) didnt work as expected
-- so fall back to good old cursors...
declare #ncombos int,#num int
declare mulc cursor for select n from #AttCount
open mulc
set #ncombos=1
fetch next from mulc into #num
while ##FETCH_STATUS=0
begin
set #ncombos=#ncombos*#num
fetch next from mulc into #num
end
close mulc
deallocate mulc
-- Now let's get our hands dirty...
declare #i int,#m int,#atid int,#n int,#r int
declare c cursor for select AttributeId,n from #AttCount
open c
fetch next from c into #atid,#n
set #m=1
while ##FETCH_STATUS=0
begin
set #i=0
while #i<#ncombos
begin
set #r=(#i/#m)%#n
insert into _CombinedAttributes (GroupKey,AttributeId,Value)
select #i,#atid,value from #Attrs where AttributeId=#atid and RowNum=#r
set #i=#i+1
end
set #m=#m*#n
fetch next from c into #atid,#n
end
close c
deallocate c
Hint: Here's why I didn't use exp(sum(log())) to emulate a mul() aggregate.
Recursive Solution
The following is a recursive solution, SQLFiddle is here:
with a as ( -- unique AttributeIDs
select AttributeID
,Row_Number() over(order by AttributeID) as rowNo
,count(*) as cnt
from [dbo].[_Combinations]
group by AttributeID
),
r as (
-- start recursion: list all values of the first attribute
select Dense_Rank() over(order by c.[Value]) - 1 as GroupKey
,c.AttributeID
,c.[Value]
,a.cnt as factor
,1 as level
from a
join [dbo].[_Combinations] as c on a.AttributeID = c.AttributeID
where a.rowNo = 1
union all
-- recursion step: add the combinations with the values of the next attribute
select GroupKey
,case when AttributeID = 'prev' then prevAttribID else currAttribID end as AttributeID
,[Value]
,factor
,level
from (select r.Value as prev
,c.Value as curr
,(Dense_Rank() over(order by c.[Value]) - 1) * r.factor + r.GroupKey as GroupKey
,r.level + 1 as level
,r.factor * a.cnt as factor
,r.AttributeID as prevAttribID
,a.AttributeID as currAttribID
from r
join a on r.level + 1 = a.rowNo
join [dbo].[_Combinations] as c on a.AttributeID = c.AttributeID
) as p
unpivot ( Value for AttributeID in (prev, curr)) as up
)
-- get result: this is the data from the deepest level
select distinct
GroupKey + 1 as GroupKey -- start with one instead of zero
,AttributeID
,[Value]
from r
where level = (select count(*) from a)
order by GroupKey, AttributeID, [Value]
Dynamic Solution
And this is a slightly shorter version using a dynamic statement:
declare #stmt varchar(max);
with a as ( -- unique attribute keys, cast here to avoid casting when building the dynamic statement
select distinct cast(AttributeID as varchar(10)) as ID
from [dbo].[_Combinations]
)
select #stmt = 'select GroupKey, Cast(SubString(AttributeIDStr, 2, 100) as int) as AttributeID, Value
from
(
select '
+ (select ' C' + ID + '.Value as V' + ID + ', ' from a for xml path(''))
+ ' Row_Number() over(order by '
+ stuff((select ', C' + ID + '.Value' from a for xml path('')), 1, 2, '')
+ ') AS GroupKey from '
+ stuff((select ' cross join [dbo].[_Combinations] as C' + ID from a for xml path('')), 1, 11, '')
+ ' where '
+ stuff((select ' and C' + ID + '.AttributeID = ' + ID from a for xml path('')), 1, 4, '')
+ ') as p unpivot (Value for AttributeIDStr in ('
+ stuff((select ', V' + ID from a for xml path('')), 1, 2, '')
+ ')) as up'
;
exec (#stmt)
As SQL Server does not have the nice list aggregate function that other databases have, one must use the ugly stuff((select ... for xml path(''))) expression.
The statement produced for the sample data is - apart from whitespace differences - the following:
select GroupKey, Cast(SubString(AttributeIDStr, 2, 100) as int) as AttributeID, Value
from
(
select C16.Value as V16
,C28.Value as V28
,C8.Value as V8
,Row_Number() over(order by C16.Value, C28.Value, C8.Value) AS GroupKey
from [dbo].[_Combinations] as C16
cross join
[dbo].[_Combinations] as C28
cross join
[dbo].[_Combinations] as C8
where C16.AttributeID = 16
and C28.AttributeID = 28
and C8.AttributeID = 8
) as p
unpivot ( Value for AttributeIDStr in (V16, V28, V8)) as up
Both solutions avoid the multiplication aggregation workaround using exp(log()) that is used in some other answers, which is very sensitive to rounding errors.
Regarding the issue with exp(sum(log(count(*))) over ()), the answer for me seemed to be to introduce the ROUND function to the mix. Thus, the following snippet seems to produce a reliable answer (so far at least):
ROUND(exp(sum(log(count(*))) over ()), 0)
Related
Suppose I have the following table:
Key
Value
5
1.0
2
0.860
7
0.686
5
0.886
7
1.0
7
0.478
2
1.0
5
0.921
2
1.0
And want to order by Key-groups with the highest values and then by the value in descending order, as:
Key
Value
2
1.0
2
1.0
2
0.860
5
1.0
5
0.921
5
0.886
7
1.0
7
0.686
7
0.478
EDIT 1: when there is multiple groups with the same highest value, then the second highest would determine the order of the groups.
EDIT 2: updated the values in order to better represent the data better.
How can I accomplish this in SQL Server?
I might be late to a party, and solution is probably overcomplicated, but it should be suitable for all cases.
The idea is to pivot Values for Keys in columns 1,[2],... from biggest to lowest, and then just order by these columns descending.
I changed data sample a bit to make a propper tests:
create table t (
[key] int,
[value] money
)
insert into t
values
(5, 1),
(5, 0.9212),
(5, 0.8867),
(5, 0.8394),
(5, 0.8279),
(5, 0.82),
(5, 0.8047),
(5, 0.8018),
(5, 0.7997),
(5, 0.7893),
(2, 1),
(2, 1),
(2, 0.8595),
(2, 0.7872),
(2, 0.7479),
(2, 0.7455),
(2, 0.7276),
(2, 0.7202),
(2, 0.6944),
(2, 0.6925);
And a script:
declare #temp as table([key] nvarchar(64), rn int);
declare #depth as int = 99, -- how many values you would like to take into account when you sort your Keys values
#sql as varchar(max);
with cte_ordered as
(-- here we find which values from keys should be compared. rn=1 - for biggest values
select [key], [value],
row_number() over (partition by [key] order by [value] desc) as rn
from t
),
cte_columns as
(-- distinct N values to use it in select list
select STRING_AGG('['+cast(rn as varchar(max))+']', ',') as cols
from ( select distinct top (#depth) rn
from cte_ordered order by rn) as qq
),
cte_order as
(-- distinct N values to use it in Order by
select STRING_AGG('['+cast(rn as varchar(max))+'] desc', ',') as ord
from ( select distinct top (#depth) rn
from cte_ordered order by rn) as qq
),
cte_dynamic as
(
select '
select [key],
row_number() over(order by ' + ord + ', [key])
from (
select [key], [value], rn
from ( select [key], [value],
row_number() over (partition by [key] order by [value] desc) as rn
from t
) as tt ) as ttt
pivot (
sum([value])
for rn in (' + cols + ')) as pv' as query
from cte_columns
cross join cte_order
)
select #sql = query
from cte_dynamic;
insert into #temp([key], rn)
exec(#sql);
select t.[key], t.[value]
from t
inner join #temp as tt
on t.[key] = tt.[key]
order by tt.rn, t.[value] DESC
;
DBfiddle example
It's not clear from the comments if you have the solution you need, but the following ordering criteria should give your resired result:
select *
from t
order by Max([value]) over(partition by [key]) desc, [key], [value] desc;
Demo fiddle
I have two tables. The first one with all movements in twelve months and the second one with claims registered in the same period of time. When I run the following query from the first table I've got 10 records. Of course, there are other records with a different number of movements (e.g.: 7, 23, 2 movements):
select t.cod_suc
,t.cod_ramo_comercial
,t.Poliza
,t.Item
,t.id_pv
from temp_portafolio_personal_accidents as t
where t.cod_suc = 2
and t.cod_ramo_comercial = 46
and t.Poliza = 50283
and t.Item = 1
and t.id_pv = 788383;
With the second query, for the second table, I have the following results:
select c.cod_suc
,c.cod_ramo_comercial
,c.[No. Policy]
,c.Item
,c.[ID Incident]
,max(c.id_pv) as id_pv
,count(distinct [No. Incident]) as 'Conteo R12'
from #claims as c
where c.[ID Incident] = 343632
group by c.cod_suc
,c.cod_ramo_comercial
,c.[No. Policy]
,c.Item
,c.[ID Incident];
Now, I need to update the first table but only one record. I'm using the following query, but all records are being updated. When I sum results I have 10 but is just one claim, as the second query shows.
update p
set [No. Siniestros R12] = b.[Conteo R12]
from temp_portafolio_personal_accidents p
left join
(select c.cod_suc
,c.cod_ramo_comercial
,c.[No. Policy]
,c.Item
,c.[ID Incident]
,max(c.id_pv) as id_pv
,count(distinct [No. Incident]) as 'Conteo R12'
from
#claims as c
where c.[ID Incident] = 343632
group by c.cod_suc
,c.cod_ramo_comercial
,c.[No. Policy]
,c.Item
,c.[ID Incident]
) b
on p.id_pv = b.id_pv
and p.cod_suc = b.cod_suc
and p.cod_ramo_comercial = b.cod_ramo_comercial
and p.Poliza = b.[No. Policy]
and p.Item = b.Item
where p.id_pv = 788383;
You can use a CTE with a ROW_NUMBER() function to do this. Simple example:
DECLARE #TABLE AS TABLE (Testing INT, Testing2 VARCHAR(55), Testing3 BIT);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
INSERT INTO #TABLE VALUES (1, '1', 1);
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY Testing) AS RowID
,Testing
,Testing2
,Testing3
FROM #TABLE
)
UPDATE CTE
SET Testing = 2, Testing2 = '2', Testing3 = 0
WHERE RowID = 1
;
SELECT * FROM #TABLE
;
I have two tables, master and child. The master's primary key MM is an INT. The child table has a compound key of two columns and value column:
MM (INT)
POS (INT, values 1-32)
VV (INT, values 1-9)
Sample master table data:
(1, other data)
(2, other data)
(3, other data)
Sample child table data
(1, 1,2)
(1, 2,2)
(1, 4,1)
(1,15,1)
(2, 4,5)
(2, 5,3)
(2,31,7)
(3,3,1)
(4,18,2)
{4,19,5)
For a report I could like to de-normalize the data with an output like this:
(1,'22010000000000010000000000000000')
(2,'00053000000000000000000000000070')
(3,'00100000000000000000000000000000')
(4,'00000000000000000025000000000000')
I was thinking to use a select query with coalesce like this but the output is not not exactly what I want:
(1,'22110')
(2,'537')
(3,'1')
(4,'25')
How do I fill in the missing data with zeros?
One way I can think to do this uses a decimal value with a precision of 32 and sum() and then convert back to a zero-padded string:
select mm,
right(replicate('0', 32) + cast(sum(val) as varchar(32)), 32)
from (select c.*,
cast(cast(val as varchar(32)) + replicate('0', 32 - pos) as decimal(32, 0)) as val
from child c
) c
group by mm;
EDIT:
The above isn't generalizable (say, above 38 characters or to use letters as well as digits). Here is a more generalizable, but longer version:
select c.mm,
(max(case when pos = 1 then valc else '0' end) +
max(case when pos = 2 then valc else '0' end) +
max(case when pos = 3 then valc else '0' end) +
. . .
max(case when pos = 32 then valc else '0' end) +
)
from (select c.*, cast(val as varchar(255)) as valc
from child c
) c
group by c.mm;
I should note that if you want to handle a master with no children, then use a left join. That aspect of the problem seems less interesting than combining the values in the appropriate positions.
Try it like this
DECLARE #master TABLE(MM INT,OtherData VARCHAR(100));
INSERT INTO #master VALUES
(1, 'Other Data 1')
,(2, 'Other Data 2')
,(3, 'Other Data 3');
DECLARE #child TABLE(MM INT, POS INT, VV INT)
INSERT INTO #child VALUES
(1, 1,2)
,(1, 2,2)
,(1, 4,1)
,(1,15,1)
,(2, 4,5)
,(2, 5,3)
,(2,31,7)
,(3,3,1)
,(4,18,2)
,(4,19,5);
--One CTE to get 32 numbers
WITH Numbers(Nr) AS
(SELECT TOP 32 ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM sys.objects) --get 32 numbers
--another CTE to get distinct MMs
,MMs AS
(
SELECT c.MM
,m.OtherData
FROM #child AS c
LEFT JOIN #master AS m ON c.MM=m.MM
GROUP BY c.MM,m.OtherData
)
--In this CTE The CROSS JOIN with the Numbers will create a list of 32 rows, which carry in all positions with a corresponding child its number. COALESCE will set a zero in the place of all NULLs
,Masked AS
(
SELECT MMs.MM
,MMs.OtherData
,Nr
,COALESCE(VV,0) AS Val
FROM MMs
CROSS JOIN Numbers
LEFT JOIN #child AS c1 ON c1.MM=MMs.MM AND c1.POS=Nr
)
-The final SELECT uses FOR XML PATH to get the 32 numbers in rows back to a string
SELECT *
,(
SELECT Masked.Val AS [*]
FROM Masked
WHERE Masked.MM=MMs.MM
FOR XML PATH('')
)
FROM MMs
The result
1 22010000000000100000000000000000
2 00053000000000000000000000000070
3 00100000000000000000000000000000
4 00000000000000000250000000000000
Hi I currently have a tables with a column that I would like to split.
ID Serial
1 AAA"-A01-AU-234-U_xyz(CY)(REV-002)
2 AAA"-A01-AU-234-U(CY)(REV-1)
3 AAA"-A01-AU-234-U(CY)(REV-101)
4 VVV"-01-AU-234-Z_ww(REV-001)
5 VVV"-01-AU-234-Z(REV-001)_xyz(CY)
6 V-VV"-01-AU-234-Z(REV-03)_xyz(CY)
7 V-VV"-01-AU-234-Z-ZZZ(REV-004)_xyz(CY)
I would like to split this column into 2 field via a select statement
The first field would consist of the text from the start and end when this scenario is satisfied
After the first "-
take all text till the next 3 hypen (-)
Take the first letter after the last hypen(-)
The second field would want to store the Value(Int) inside the (REV) bracket. Rev is always stored inside a compassing bracket (Rev-xxx) the number may stretch from 0-999 and have different form of representation
Example of output
Field 1 Field 2
AAA"-A01-AU-234-U 2
AAA"-A01-AU-234-U 1
AAA"-A01-AU-234-U 101
VVV"-01-AU-234-Z 1
VVV"-01-AU-234-Z 1
V-VV"-01-AU-234-Z 3
V-VV"-01-AU-234-Z 4
Maybe it is possible to make it better and faster, but at least it does work. If i will have some time more i will look at this again to think of better solution, but it do the job.
create table #t
(
id int,
serial nvarchar(255)
)
go
insert into #t values (1, 'AAA"-A01-AU-234-U_xyz(CY)(REV-002)')
insert into #t values (2, 'AAA"-A01-AU-234-U(CY)(REV-1)')
insert into #t values (3, 'AAA"-A01-AU-234-U(CY)(REV-101)')
insert into #t values (4, 'VVV"-01-AU-234-Z_ww(REV-001)')
insert into #t values (5, 'VVV"-01-AU-234-Z(REV-001)_xyz(CY)')
insert into #t values (6, 'VVV"-01-AU-234-Z(REV-03)_xyz(CY)')
insert into #t values (7, 'VVV"-01-AU-234-Z(REV-004)_xyz(CY)')
go
select id, serial,
left(serial,charindex('-', serial, charindex('-', serial, charindex('-', serial, charindex('"',serial) + 2) +1) + 1) + 1) as 'Field2'
,cast( replace(left(right(serial, len(serial) - charindex('REV',serial) +1 ), CHARINDEX(')',right(serial, len(serial) - charindex('REV',serial) +1 )) - 1), 'REV-', '')as int) as 'Field1'
from #t
go
gives me:
id serial Field2 Field1
1 AAA"-A01-AU-234-U_xyz(CY)(REV-002) AAA"-A01-AU-234-U 2
2 AAA"-A01-AU-234-U(CY)(REV-1) AAA"-A01-AU-234-U 1
3 AAA"-A01-AU-234-U(CY)(REV-101) AAA"-A01-AU-234-U 101
4 VVV"-01-AU-234-Z_ww(REV-001) VVV"-01-AU-234-Z 1
5 VVV"-01-AU-234-Z(REV-001)_xyz(CY) VVV"-01-AU-234-Z 1
6 VVV"-01-AU-234-Z(REV-03)_xyz(CY) VVV"-01-AU-234-Z 3
7 VVV"-01-AU-234-Z(REV-004)_xyz(CY) VVV"-01-AU-234-Z 4
I came up with a solution in php using regular expressions.I am trying to convert it into posix standards supported by mysql.Anyways in the meanwhile you can have a look at this and it works perfect.
/The first script select the values for fields 1 namely AAA"-A01-AU-234-U/
<?php
$txt='VVV"-01-AU-234-Z(REV-001)_xyz(CY)';
$re1='((?:[a-z][a-z0-9_]*))';
$re2='.*?';
$re3='(\\d+)';
$re4='.*?';
$re5='((?:[a-z][a-z0-9_]*))';
$re6='.*?';
$re7='(\\d+)';
$re8='.*?';
$re9='([a-z])';
echo $re1.$re2.$re3.$re4.$re5.$re6.$re7.$re8.$re9;
if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6.$re7.$re8.$re9."/is", $txt, $matches))
{
$var1=$matches[1][0];
$int1=$matches[2][0];
$var2=$matches[3][0];
$int2=$matches[4][0];
$w1=$matches[5][0];
print "($var1) ($int1) ($var2) ($int2) ($w1) \n";
}
?>
/*The second script selects values for field 2 namely the last integer*/
<?php
$txt='VVV"-01-AU-234-Z_ww(REV-001)';
$re1='.*?';
$re2='\\d';
$re3='.*?';
$re4='\\d';
$re5='.*?';
$re6='\\d';
$re7='.*?';
$re8='\\d';
$re9='.*?';
$re10='\\d';
$re11='.*?';
$re12='\\d';
$re13='.*?';
$re14='\\d';
$re15='(\\d)';
if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6.$re7.$re8.$re9.$re10.$re11.$re12.$re13.$re14.$re15."/is", $txt, $matches))
{
$d1=$matches[1][0];
print "($d1) \n";
}
?>
OUTPUT:
(VVV) (01) (AU) (234) (Z) //script 1
(1) //script 2
You can add database connection to the script and store the results in a new table.You can aslo iterate each row as input to the script and store corresponding results in the table.
Note:
The regular expression used for selecting field 1:
((?:[a-z][a-z0-9_]*)).*?(\d+).*?((?:[a-z][a-z0-9_]*)).*?(\d+).*?([a-z])
The regular expression used for selecting field 2:
.*?\d.*?\d.*?\d.*?\d.*?\d.*?\d.*?\d(\d)
If anybody can convert the above expressions to posix standards then the user can write a simple query like
select t.serial as field 1 from table t
where t.serial regexp 'converted exp' join
(select t1.serial as field 2 from table t1
where t1.serial regexp 'converted exp')q
on q.id=t.id;
I tried to convert it but the matching constraints were lost.You should actually change ?: to ^ and ? to [^>] and //d to [0-9] or digit.Hope it helps.
Try this solution. It uses a combination of charindex and the substring function.
DECLARE #TempTable table
(
id int,
serial nvarchar(255)
)
insert into #TempTable values (1, 'AAA"-A01-AU-234-U_xyz(CY)(REV-002)')
insert into #TempTable values (2, 'AAA"-A01-AU-234-U(CY)(REV-1)')
insert into #TempTable values (3, 'AAA"-A01-AU-234-U(CY)(REV-101)')
insert into #TempTable values (4, 'VVV"-01-AU-234-Z_ww(REV-001)')
insert into #TempTable values (5, 'VVV"-01-AU-234-Z(REV-001)_xyz(CY)')
insert into #TempTable values (6, 'VVV"-01-AU-234-Z(REV-03)_xyz(CY)')
insert into #TempTable values (7, 'VVV"-01-AU-234-Z(REV-004)_xyz(CY)')
select
id,
serial,
substring(serial, 1, P4.Pos+1) as field1,
convert(int, substring(Serial, P6.Pos , P7.Pos - P6.Pos)) as field2
from #TempTable
cross apply (select (charindex('-', Serial))) as P1(Pos)
cross apply (select (charindex('-', Serial, P1.Pos+1))) as P2(Pos)
cross apply (select (charindex('-', Serial, P2.Pos+1))) as P3(Pos)
cross apply (select (charindex('-', Serial, P3.Pos+1))) as P4(Pos)
cross apply (select (charindex('REV-', Serial,P1.Pos+1)+4)) as P6(Pos)
--+4 because 'REV-' is 4 chars long
cross apply (select (charindex(')', Serial,P6.Pos+1))) as P7(Pos);
I have updated my answer. Is this better now?
DECLARE #Table table(ID int, SERIAL nvarchar(100));
INSERT INTO #Table(ID, SERIAL)
VALUES ('1', 'AAA"-A01-AU-234-U_xyz(CY)(REV-002)'),
('2', 'AAA"-A01-AU-234-U(CY)(REV-1)'),
('3', 'AAA"-A01-AU-234-U(CY)(REV-101)'),
('4', 'VVV"-01-AU-234-Z_ww(REV-001)'),
('5', 'VVV"-01-AU-234-Z(REV-001)_xyz(CY)'),
('6', 'VVV"-01-AU-234-Z(REV-03)_xyz(CY)'),
('7', 'VVV"-01-AU-234-Z(REV-004)_xyz(CY)'),
('8', 'AAA"-A01-AU-234-U-1111-(REV-111)'),
('9', 'AAA"-A01-AU-234-U-111111-5555(CY)(REV-101)'),
('10', 'V-VV"-01-AU-234-Z-ZZZ(REV-004)_xyz(CY)')
SELECT
ID,
SERIAL,
LEFT(SERIAL, P5.Pos + 1) AS Field1,
CONVERT(int, SUBSTRING(SERIAL, P6.Pos, CHARINDEX(')', RIGHT(SERIAL, LEN(SERIAL) - P6.Pos)))) AS Field2
FROM #Table
CROSS APPLY (SELECT CHARINDEX('"-', SERIAL)) AS P1(Pos)
CROSS APPLY (SELECT CHARINDEX('-', SERIAL, P1.Pos + 1)) AS P2(Pos)
CROSS APPLY (SELECT CHARINDEX('-', SERIAL, P2.Pos + 1)) AS P3(Pos)
CROSS APPLY (SELECT CHARINDEX('-', SERIAL, P3.Pos + 1)) AS P4(Pos)
CROSS APPLY (SELECT CHARINDEX('-', SERIAL, P4.Pos + 1)) AS P5(Pos)
CROSS APPLY (SELECT CHARINDEX('REV-', SERIAL, P5.Pos + 1) + 4) AS P6(Pos)
I have the following problem to solve and I can't seem to be able to come up with an algorithm yet, nevermind an actual solution.
I have a table of similar structure/data as the following, where IDs are not always in sequence for the same Ticker/QuouteType:
ID Ticker PriceDateTime QuoteType OpenPrice HighPrice LowPrice ClosePrice
------- ------ ---------------- --------- --------- --------- -------- ----------
2036430 ^COMP 2012-02-10 20:50 95/Minute 2901.57 2905.04 2895.37 2901.71
2036429 ^COMP 2012-02-10 19:15 95/Minute 2909.63 2910.98 2899.95 2901.67
2036428 ^COMP 2012-02-10 17:40 95/Minute 2905.9 2910.27 2904.29 2909.64
2036427 ^COMP 2012-02-10 16:05 95/Minute 2902 2908.29 2895.1 2905.89
2036426 ^COMP 2012-02-09 21:00 95/Minute 2926.12 2928.01 2925.53 2927.21
The information I need to extract from this data is the following:
How many consecutive rows are there? Counting downwards from the most recent (as recorded in PriceDateTime), looking at ClosePrice?
IE: For the current example the answer should be 2. ClosePrice (row 1) = 2901.71 which is greater than ClosePrice (row 2) = 2901.67 but lower than ClosePrice (row 3) = 2909.64. As such, looking back from the most recent price, we have 2 rows that "go in the same direction".
Of course I have to do this across a lot of other names, so speed is quite important.
PS: Thank you all for your help, I've drawn inspiration from all your answers when building the final procedure. You're all very kind!
Try this: (I have simplified the test data I'm using as it only requires 2 columns to demonstrate the logic).
CREATE TABLE #Test (PriceDateTime DATETIME, ClosePrice DECIMAL(6, 2))
INSERT #Test VALUES
('20120210 20:50:00.000', 2901.71),
('20120210 19:15:00.000', 2901.67),
('20120210 17:40:00.000', 2900.64),
('20120210 16:05:00.000', 2905.89),
('20120209 21:00:00.000', 2927.21)
-- FIRST CTE, JUST DEFINES A VIEW GIVING EACH ENTRY A ROW NUMBER
;WITH CTE AS
( SELECT *,
ROW_NUMBER() OVER(ORDER BY PriceDateTime DESC) [RowNumber]
FROM #Test
),
-- SECOND CTE, ASSIGNES EACH ENTRY +1 OR -1 DEPENDING ON HOW THE VALUE HAS CHANGED COMPARED TO THE PREVIOUS RECORD
CTE2 AS
( SELECT a.*, SIGN(a.ClosePrice - b.ClosePrice) [Movement]
FROM CTE a
LEFT JOIN CTE b
ON a.RowNumber = b.RowNumber - 1
),
-- THIRD CTE, WILL LOOP THROUGH THE DATA AS MANY TIMES AS POSSIBLE WHILE THE PREVIOUS ENTRY HAS THE SAME "MOVEMENT"
CTE3 AS
( SELECT *, 1 [Recursion]
FROM CTE2
UNION ALL
SELECT a.PriceDateTime, a.ClosePrice, a.RowNumber, a.Movement, b.Recursion + 1
FROM CTE2 a
INNER JOIN CTE3 b
ON a.RowNumber = b.RowNumber - 1
AND a.Movement = b.Movement
)
SELECT MAX(Recursion) + 1 -- ADD 1 TO THE RECORD BECAUSE THERE WILL ALWAYS BE AT LEAST TWO ROWS
FROM CTE3
WHERE RowNumber = 1 -- LATEST ENTRY
DROP TABLE #Test
I've tried to comment the answer to explain as I go. If anything is not clear from the comments let me know and I will try and explain further
Solution below should be efficient enough, but it will fail if there are gaps in ID sequence.
Please update your topic, if it is the point.
DECLARE #t TABLE (
ID INT,
ClosePrice DECIMAL(10, 5)
)
INSERT #t (ID, ClosePrice)
VALUES (2036430, 2901.71), (2036429, 2901.67), (2036428, 2909.64), (2036427, 2905.89), (2036426, 2927.21)
;WITH CTE AS (
SELECT TOP 1 ID, ClosePrice, 1 AS lvl
FROM #t
ORDER BY ID DESC
UNION ALL
SELECT s.ID, s.ClosePrice, CTE.lvl + 1
FROM #t AS s
INNER JOIN CTE
ON s.ID = CTE.ID - 1 AND s.ClosePrice < CTE.ClosePrice
)
SELECT MAX(lvl) AS answer
FROM CTE
I'd join your data on itself (with +1 on your primary key / ordering key) then use a simple CASE to track the change (assuming i've understood your question properly).
For example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_NumericSequence](
[ID] [int] NULL,
[Value] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (1, 1)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (2, 2)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (3, 3)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (4, 2)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (5, 1)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (6, 3)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (7, 3)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (8, 8)
GO
INSERT [dbo].[tbl_NumericSequence] ([ID], [Value]) VALUES (9, 1)
GO
WITH RawData ( [ID], [Value] )
AS ( SELECT [ID] ,
[Value]
FROM [Test].[dbo].[tbl_NumericSequence]
)
SELECT RawData.ID ,
RawData.Value ,
CASE WHEN RawDataLag.Value = RawData.Value THEN 'No Change'
WHEN RawDataLag.Value > RawData.Value THEN 'Down'
WHEN RawDataLag.Value < RawData.Value THEN 'Up'
END AS Change
FROM RawData
LEFT OUTER JOIN RawData RawDataLag ON RawData.ID = RawDataLag.iD + 1
ORDER BY RawData.ID ASC
I would approach it with recursive common table expressions:
CREATE TABLE #MyTable (ID INT, ClosePrice MONEY)
INSERT INTO #MyTable ( ID, ClosePrice )
VALUES (2036430,2901.71),
(2036429,2901.67),
(2036428,2909.64),
(2036427,2905.89),
(2036426,2927.21)
WITH CTE AS (
SELECT TOP 1 id, closeprice, 1 Consecutive
FROM #MyTable
ORDER BY id DESC
UNION ALL
SELECT A.id, A.closeprice, CASE WHEN A.ClosePrice < B.ClosePrice THEN Consecutive+1 ELSE 1 END
FROM #MyTable A INNER JOIN cte B ON A.ID=B.id -1
)
SELECT * FROM cte
--OR to just get the max consecutive
--select max(Consecutive) from cte
DROP TABLE #MyTable