SQL how to check prefix in cell with two prefixes - sql-server

I am learning SQL and I have a table where there are certain cells with two prefixes like this :
example1(cell) : R:8days; U:5$;
example2(cell) : R:8days;
example3(cell) : U:5$;
I want to check for that U:5$ after the first prefix, as I know how to check for prefix R:8days;. So I need to check for U:5$ and then make a new column in table.
My code looks like this:
;with cte as (
select
Employer, AmountPayd, AmountPayd as Payd
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%' **HERE I WANT TO CHECK FOR PREFIX NR2. 'U:5$' AND MAKE NEW COLUMN FOR WHICH EMPLOYER HAS U:5$ NOTE.**
)
select
Employer,
[4.00] = ISNULL([4.00],0)
,[5.00] = ISNULL([5.00],0)
,[9.00] = ISNULL([9.00],0)
,[10.00] = ISNULL([10.00],0)
,[15.00] = ISNULL([15.00],0)
,[Sum] =ISNULL([4.00],0) + ISNULL([5.00],0) + ISNULL([9.00],0) + ISNULL([10.00],0) + ISNULL([15.00],0)
from cte
pivot (
sum(AmountPayd) for Payd in ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00]))pvt;

This?
select
Employer, AmountPayd, AmountPayd as Payd,
CASE WHEN Note like '%R:8%;%U:5$%' THEN 'U:5' END U5Note
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%'

(I've corrected some mistakes in column names and refactored the query.)
I believe, you are looking for something like this:
WITH CTE AS (
SELECT
Employer,
AmountPaid,
Paid
FROM Data
LEFT JOIN (VALUES (4, 5, 9, 10, 15, 20)) V(Paid)
ON Note LIKE '%U:' + CAST(Paid AS VARCHAR(10)) + '$;%'
WHERE TypeOfTransaction LIKE 'Offline Prepaid%'
AND Note LIKE '%R:8%'
)
SELECT
Employer,
ISNULL([4.00], 0) AS [4.00],
ISNULL([5.00], 0) AS [5.00],
ISNULL([9.00], 0) AS [9.00],
ISNULL([10.00], 0) AS [10.00],
ISNULL([15.00], 0) AS [15.00],
ISNULL([4.00] + [5.00] + [9.00] + [10.00] + [15.00], 0) AS Sum
FROM CTE
PIVOT( SUM(AmountPaid)
FOR Paid IN ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00])) PVT;

Related

Create a joined Key-Value in LinqToSql

I have a GridView binded to LinqToSql-DataSource. The DataSource is Multiple-Join. I need unique Key-Values for the Grid. But all PrimaryKeys from the Tables could exist double or not because of left joins.
I have solved the problem in a pure sql-statement. There i create a ID for the TableRows by joining two PrimaryKeys an connecting with a "-". I need one of the IDs for later working with TableRows, the other could be null.
So I do in SQL-Statement:
select CAST(mitgliedschaft.id as varchar(MAX)) + '-' + CAST(ISNULL(funktion.id, '') as varchar(MAX)) as id from ...... inner join ...... etc
I need the CASTS for not producing Calculating with the "-" and the ISNULL-Function because the second ID could be Null.
Now I have to transfer this part of the scenario into Linq-Statement. I tried like this:
...
...
select new
{
...
id = mitgliedschaft.id.ToString() + "-" + (funktion.id == null ? 0 : funktion.id).ToString()
...
});
But didn't get it running in that way. Can someone help me concatenating an ID with "-" and an ID that can be NULL? If it is NULL it should be an empty String or Null-Digit or whatever.
got it now:
select new
{
id = (mitgliedschaft.id.ToString() + "-") + (funktion.id.ToString() ?? "0")
}

Coldfusion - How to parse and segment out data from an email file

I am trying to parse email files that will be coming periodically for data that is contained within. We plan to setup cfmail to get the email within the box within CF Admin to run every minute.
The data within the email consists of name, code name, address, description, etc. and will have consistent labels so we are thinking of performing a loop or find function for each field of data. Would that be a good start?
Here is an example of email data:
INCIDENT # 12345
LONG TERM SYS# C12345
REPORTED: 08:39:34 05/20/19 Nature: FD NEED Address: 12345 N TEST LN
City: Testville
Responding Units: T12
Cross Streets: Intersection of: N Test LN & W TEST LN
Lat= 39.587453 Lon= -86.485021
Comments: This is a test post. Please disregard
Here's a picture of what the data actually looks like:
So we would like to extract the following:
INCIDENT
LONG TERM SYS#
REPORTED
Nature
Address
City
Responding Units
Cross Streets
Comments
Any feedback or suggestions would be greatly appreciated!
Someone posted this but it was apparently deleted. Whoever it was I want to thank you VERY MUCH as it worked perfectly!!!!
Here is the function:
<!---CREATE FUNCTION [tvf-Str-Extract] (#String varchar(max),#Delimiter1
varchar(100),#Delimiter2 varchar(100))
Returns Table
As
Return (
with cte1(N) as (Select 1 From (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))
N(N)),
cte2(N) as (Select Top (IsNull(DataLength(#String),0)) Row_Number() over (Order By
(Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A
),
cte3(N) as (Select 1 Union All Select t.N+DataLength(#Delimiter1) From cte2 t
Where Substring(#String,t.N,DataLength(#Delimiter1)) = #Delimiter1),
cte4(N,L) as (Select S.N,IsNull(NullIf(CharIndex(#Delimiter1,#String,s.N),0)-
S.N,8000) From cte3 S)
Select RetSeq = Row_Number() over (Order By N)
,RetPos = N
,RetVal = left(RetVal,charindex(#Delimiter2,RetVal)-1)
From ( Select *,RetVal = Substring(#String, N, L) From cte4 ) A
Where charindex(#Delimiter2,RetVal)>1
)
And here is the CF code that worked:
<cfquery name="body" datasource="#Application.dsn#">
Declare #S varchar(max) ='
INCIDENT 12345
LONG TERM SYS C12345
REPORTED: 08:39:34 05/20/19 Nature: FD NEED Address: 12345 N TEST
LN City: Testville
Responding Units: T12
Cross Streets: Intersection of: N Test LN & W TEST LN
Lat= 39.587453 Lon= -86.485021
Comments: This is a test post. Please disregard
'
Select Incident = ltrim(rtrim(B.RetVal))
,LongTerm = ltrim(rtrim(C.RetVal))
,Reported = ltrim(rtrim(D.RetVal))
,Nature = ltrim(rtrim(E.RetVal))
,Address = ltrim(rtrim(F.RetVal))
,City = ltrim(rtrim(G.RetVal))
,RespUnit = ltrim(rtrim(H.RetVal))
,CrossStr = ltrim(rtrim(I.RetVal))
,Comments = ltrim(rtrim(J.RetVal))
From (values (replace(replace(#S,char(10),''),char(13),' ')) )A(S)
Outer Apply [dbo].[tvf-Str-Extract](S,'INCIDENT' ,'LONG
TERM' ) B
Outer Apply [dbo].[tvf-Str-Extract](S,'LONG TERM SYS'
,'REPORTED' ) C
Outer Apply [dbo].[tvf-Str-Extract](S,'REPORTED:' ,'Nature'
) D
Outer Apply [dbo].[tvf-Str-Extract](S,'Nature:'
,'Address' ) E
Outer Apply [dbo].[tvf-Str-Extract](S,'Address:' ,'City'
) F
Outer Apply [dbo].[tvf-Str-Extract](S,'City:'
,'Responding ') G
Outer Apply [dbo].[tvf-Str-Extract](S,'Responding Units:','Cross'
) H
Outer Apply [dbo].[tvf-Str-Extract](S,'Cross Streets:' ,'Lat'
) I
Outer Apply [dbo].[tvf-Str-Extract](S+'|||','Comments:' ,'|||'
) J
</cfquery>
<cfoutput>
B. #body.Incident#<br>
C. #body.LongTerm#<br>
D. #body.Reported#<br>
SQL tends to have limited string functions, so it isn't the best tool for parsing. If the email content is always in that exact format, you could use either plain string functions or regular expressions to parse it. However, the latter is more flexible.
I suspect the content actually does contain new lines, which would make for simpler parsing. However, if you prefer searching for content in between two labels, regular expressions would do the trick.
Build an array of the label names (only). Loop through the array, grabbing a pair of labels: "current" and "next". Use the two values in a regular expression to extract the text in between them:
label &"\s*[##:=](.*?)"& nextLabel
/* Explanation: */
label - First label name (example: "Incident")
\s* - Zero or more spaces
[##:=] - Any of these characters: pound sign, colon or equal sign
(.*?) - Group of zero or more characters (non-greedy)
nextLabel - Next label (example: "Long Term Sys")
Use reFindNoCase() to get details about the position and length of matched text. Then use those values in conjunction with mid() to extract the text.
Note, newer versions like ColdFusion 2016+ automagically extract the text under a key named MATCH
The newer CF2016+ syntax is slicker, but something along these lines works under CF10:
emailBody = "INCIDENT # 12345 ... etc.... ";
labelArray = ["Incident", "Long Term Sys", "Reported", ..., "Comments" ];
for (pos = 1; pos <= arrayLen(labelArray); pos++) {
// get current and next label
hasNext = pos < arrayLen(labelArray);
currLabel = labelArray[ pos ];
nextLabel = (hasNext ? labelArray[ pos+1 ] : "$");
// extract label and value
matches = reFindNoCase( currLabel &"\s*[##:=](.*?)"& nextLabel, emailBody, 1, true);
if (arrayLen(matches.len) >= 2) {
results[ currLabel ] = mid( emailBody, matches.pos[2], matches.len[2]);
}
}
writeDump( results );
Results:

Can Any one help me to convert this sql query into linq

I need to convert this SQL Query to Link :
"Select * FROM [Register]
where RegisterId IN (SELECT MyId
FROM Friends
WHERE FriendId='" + Session["CurrentProfileId"] + "'
AND Status=1
UNION
SELECT FriendId
FROM Friends
WHERE MyId='" + Session["CurrentProfileId"] + "'
AND Status=1) ";
It may be look like this??? but this is incorrect and having errors
(from u in db.Register
where RegisterId).Contains
(from f in db.Freinds
where f.MyId == Id && m.Status == 1
select new { m.MyId })
.Union(from m in db.Freinds
where f.FreindId == Id && m.Status == 1
select new { m.CreateDate } ));
You have a few problems with the linq above and here are a few:
In the query in the Union you select the CreateDate whereas in the top on you select the MyId. I assume you meant to select FreindId.
In these 2 queries you create an anonymous class instance with the field but then compare it to the RegisterId which is probably a guid/string/int - but for sure not of the type you just created.
You are using the Contains method wrong. Linq syntax can be similar to sql but it is not the same. Check here for Contains
The correct Linq way of doing it is:
var idsCollection = ((from f in db.Freinds
where f.StatusId == 1 && f.MyId == Id
select f.MyId)
.Union(from m in db.Friends
where m.StatusId == 1 && f.FreindId == Id
select m.FriendId)).ToList();
var result = (from u in db.Register
where idsCollection.Contains(u.RegisterId)
select u).ToList();
Notice that the .ToList() is not a must and is here just to ease in debugging. For more information about this .ToList() and Linq in general check MSDN

T-SQL Concatenating

I need to concatenate the following statement in SQL.
I am joining 2 tables, the MEDINFO table and the IMMUNIZE table.
There should be one record for each of the shot code dates as long as it is not null or 01/01/1901.
The output must look like this:
"Admin-" + medinfo_field_31 + ", Manuf-" + medinfo_field_32 + ", Lot-" + medinfo_field_33 + ", Exp-" + medinfo_field_34 + ", Site-" + medifno_field_35 + ", Dose-" + medinfo_field_36
Here is the criteria for the SQL statement I must create:
IF immunize_shot_code = 'FLU',
then concatenate medinfo_field_12 and medinfo_field_19 thru medinfo_field_24
IF immunize_shot_code = 'MENI',
then concatenate medinof_field_11 and medinfo_field_25 thru medinof_field_30
IF immunize_shot_code = 'TETA',
then concatenate medinfo_field_13 thru medinfo_field_18 and medinfo_field_31 thru medinfo_field_36"
Thanks for any ideas.
This would look something like the followning:
SELECT
(CASE WHEN Immunize_shot_code='Flu'
THEN medinfo_field_12+', '+med_info_field_19+ ', '+med_info_field_20+', '+med_info_field_21+ ', '+med_info_field_22+', '+med_info_field_23+', 'med_info_field_24
WHEN immunize_shot_code='MENI'
THEN [CONCATINATE AS PER ABOVE]
.....
.....
END) as ImmuCode
FROM TABLE_1
Like some of them mentioned above, you could use CASE statement something like this:
select
case when i.immunize_shot_Code = 'FLU'
then concat(m.medinfo_field_12,',',m.medinfo_field_19,',',m.medinfo_field_24...)
when i.immunize_Shot_Code = 'MENI'
then concat(m.medinfo_field_11,',',m.medinfo_field_11)
when i.immunize_Shot_code = 'TETA'
then concat(m.medinfo_field_13,',',m.medinfo_field18,',')
end as concat_value
from medinfo m
join immunize i on m.id = i.medinfo_id --change this to match your join
where (shot_code_date is not null or shot_code_date <> '01-01-1901');

Oracle split text into multiple rows

Inside a varchar2 column I have text values like :
aaaaaa. fgdfg.
bbbbbbbbbbbbbb ccccccccc
dddddd ddd dddddddddddd,
asdasdasdll
sssss
if i do select column from table where id=... i get the whole text in a single row, normally.
But i would like to get the result in multiple rows, 5 for the example above.
I have to use just one select statement, and the delimiters will be new line or carriage return (chr(10), chr(13) in oracle)
Thank you!
Like this, maybe (but it all depends on the version of oracle you are using):
WITH yourtable AS (SELECT REPLACE('aaaaaa. fgdfg.' ||chr(10)||
'bbbbbbbbbbbbbb ccccccccc ' ||chr(13)||
'dddddd ddd dddddddddddd,' ||chr(10)||
'asdasdasdll ' ||chr(13)||
'sssss '||chr(10),chr(13),chr(10)) AS astr FROM DUAL)
SELECT REGEXP_SUBSTR ( astr, '[^' ||chr(10)||']+', 1, LEVEL) data FROM yourtable
CONNECT BY LEVEL <= LENGTH(astr) - LENGTH(REPLACE(astr, chr(10))) + 1
see: Comma Separated values in Oracle
The answer by Kevin Burton contains a bug if your data contains empty lines.
The adaptation below, based on the solution invented here, works. Check that post for an explanation on the issue and the solution.
WITH yourtable AS (SELECT REPLACE('aaaaaa. fgdfg.' ||chr(10)||
'bbbbbbbbbbbbbb ccccccccc ' ||chr(13)||
chr(13)||
'dddddd ddd dddddddddddd,' ||chr(10)||
'asdasdasdll ' ||chr(13)||
'sssss '||chr(10),chr(13),chr(10)) AS astr FROM DUAL)
SELECT REGEXP_SUBSTR ( astr, '([^' ||chr(10)||']*)('||chr(10)||'|$)', 1, LEVEL, null, 1) data FROM yourtable
CONNECT BY LEVEL <= LENGTH(astr) - LENGTH(REPLACE(astr, chr(10))) + 1;

Resources