Please take a look at this simple SQL server database :
I want the result to have 3 column, and the column "CountString" is the total number of string that matches ('this','is', 'count', 'example').
I have managed to detect those words using this query, but it can`t detect multiple words :
SELECT
productid,
NAME,
((CASE
WHEN Concat(' ', NAME, ' ') LIKE '% this %' THEN 1
ELSE 0
END) + (CASE
WHEN Concat(' ', NAME, ' ') LIKE '% is %' THEN 1
ELSE 0
END) + (CASE
WHEN Concat(' ', NAME, ' ') LIKE '% count %' THEN 1
ELSE 0
END) + (CASE
WHEN
Concat(' ', NAME, ' ') LIKE '% example %' THEN 1
ELSE 0
END)) AS CountString
FROM product;
However, if the name for productID 1 is "this is count this example". I want it to be counted as 5. Could you solve this ?
Create Table product(productid int, NAME varchar(100))
Insert Into product Values(1,'this is this example')
Insert Into product Values(2,'this is this this count this example')
SELECT productid,count(*) as CountString
FROM
(
SELECT A.[productid],
Split.a.value('.', 'VARCHAR(100)') AS String
FROM (SELECT [productid],
CAST ('<M>' + REPLACE([NAME], ' ', '</M><M>') + '</M>' AS XML) AS String
FROM product) AS A
CROSS APPLY String.nodes ('/M') AS Split(a)
) As Word
WHERE String in ('this','is','count','example')
Group by productid
Try this
DECLARE #TableString TABLE(ID INT IDENTITY,String nvarchar(max))
INSERT INTO #TableString(String)
SELECT 'this is count this example' UNION ALL
SELECT 'Bearing Ball' UNION ALL
SELECT 'BB Ball Bearing ' UNION ALL
SELECT 'this is example'
-- Here the delimeter is space
SELECT id AS productid, COUNT(stringValue) AS StringValueCount FROM
(
SELECT id ,
Split.a.value('.', 'VARCHAR(1000)') AS stringValue
FROM (
SELECT id,CAST('<S>' + REPLACE(String, ' ', '</S><S>') + '</S>' AS XML) AS String
FROM #TableString
) AS A
CROSS APPLY String.nodes('/S') AS Split(a)
)Dt
WHERE dt.stringValue in ('this','is','count','example')
GROUP BY id
Result
productid StringValueCount
-----------------------------
1 5
4 3
Related
I am writing a query that roughly has this structure:
SELECT Name, <calculated-valued> as Version FROM <tables>
This calculated value needs to work like so: I have a varchar column 'Name' that could contain something like 'ABC' and I want to convert each letter into ASCII, and append them back together to form '65.66.67' in this example. (An empty string should return '0') Is there any way to do this?
My approach wasn't very good, but up to 5 characters I could do the following:
SELECT
CASE WHEN LEN(Name) = 0 THEN '0'
ELSE CAST(ASCII(SUBSTRING(Name, 1, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 1 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 2, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 2 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 3, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 3 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 4, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 4 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 5, 1)) as varchar(max))
END
END
END
END
END AS MyColumn
FROM <tables>
Is there a better way to do this? Ideally a method that can take any length of string?
Either that or can I cast letters into a hierarchyid datatype? I need to create things like 1/2/a/bc/4// or whatever, but hierarchyid doesn't support that. So instead I'm trying to convert it to 1/2/97/98.99/4/0 so I can convert and maintain the correct order. This column is only used for sorting.
Thanks for any help!
One method is a recursive CTE:
with cte as (
select Name, 1 as lev
cast(ascii(substring(name, 1, 1)) as varchar(max)) as ascii_name
from t
union all
select Name, lev + 1,
ascii_name + '.' + cast(ascii(substring(name, lev + 1, 1)) as varchar(max))
from cte
where len(Name) > lev
)
select Name, ascii_name
from cte;
Another option is with an ad-hoc tally table and a CROSS APPLY
Declare #YourTable table (Name varchar(25))
Insert Into #YourTable values
('ABC'),
('Jack'),
('Jill'),
('')
Select A.Name
,Version = isnull(B.String,'0')
From #YourTable A
Cross Apply (
Select String=Stuff((Select '.' +cast(S as varchar(5))
From (Select Top (len(A.Name))
S=ASCII(substring(A.Name,Row_Number() Over (Order By (Select NULL)),1))
From master..spt_values ) S
For XML Path ('')),1,1,'')
) B
Returns
Name String
ABC 65.66.67
Jack 74.97.99.107
Jill 74.105.108.108
0
I have this output:
Contact_Type Category_Type Category_Count
---------------------------------------------------
Window Admissions 1775
Window Financial Aid 17377
Window Miscellaneous 2720
Window Student Financials 14039
Phone Admissions 5758
Phone Financial Aid 10048
Phone Miscellaneous 4497
Phone Registration 11
Phone Student Financials 4857
and this is my query:
SELECT
Contact_Type, Category_Type1, Category_Type2, Category_Type3,
Category_Type4, Category_Type5
FROM
(SELECT
CASE
WHEN event.contact_type = 0 THEN 'Window'
WHEN event.contact_type = 1 THEN 'Phone'
END AS Contact_Type,
cat.category_type AS Category_Type,
COUNT(ec.category_id) AS Category_Count,
'Category_Type' + CAST(ROW_NUMBER() OVER (PARTITION BY Contact_Type
ORDER BY Contact_Type) AS varchar(20)) AS ColumnSequence
FROM
yLines.ylines_event AS Event
JOIN
ylines.ylines_event_category AS ec ON ec.event_id = event.event_id
JOIN
ylines.ylines_category AS cat ON ec.category_id = cat.category_id
WHERE /*event.contact_type = '0' AND*/
CAST(FORMAT(event.event_date_time, 'yyyy') AS int) BETWEEN 2014 AND dateadd(year, 1, event.event_date_time)
GROUP BY
Category_Type, Contact_Type) a
PIVOT
(MAX(Contact_Type)
FOR ColumnSequence IN (Category_Type1, Category_Type2, Category_Type3,
Category_Type4, Category_Type5)) as piv;
If I run this it gives me an error:
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Contact_Type'
and I can't seem to fix this. I am trying to transpose it so I see two rows only with 'Windows' and 'Phone' and the five Category Types transposed as five columns with the count in each. I am writing T-SQL statements. Please help!
I would try do it in dynamic
; WITH [CONTACT]
AS (
SELECT *
FROM (
VALUES
('Window', 'Admissions ', ' 1775')
, ('Window', 'Financial Aid ', '17377')
, ('Window', 'Miscellaneous ', ' 2720')
, ('Window', 'Student Financials', '14039')
, ('Phone ', 'Admissions ', ' 5758')
, ('Phone ', 'Financial Aid ', '10048')
, ('Phone ', 'Miscellaneous ', ' 4497')
, ('Phone ', 'Registration ', ' 11')
, ('Phone ', 'Student Financials', ' 4857')
) X ([Contact_Type], [Category_Type], [Category_Count])
)
SELECT *
INTO #TEMP_PIVOT
FROM [CONTACT]
DECLARE #TYPE VARCHAR(MAX)
SET #TYPE = STUFF(
(SELECT DISTINCT ', ' + QUOTENAME(RTRIM(LTRIM([CATEGORY_TYPE])))
FROM #TEMP_PIVOT
FOR XML PATH('')
)
, 1, 1, '')
DECLARE #SQL VARCHAR(MAX)
SET #SQL = ' SELECT [CONTACT_TYPE] '
+ ' , ' + #TYPE
+ ' FROM #TEMP_PIVOT '
+ ' PIVOT ( '
+ ' MAX([CATEGORY_COUNT]) '
+ ' FOR [CATEGORY_TYPE] IN (' + #TYPE + ')'
+ ' ) P '
EXECUTE (#SQL)
In the group by clause you say
`group by Category_Type, Contact_Type`
However, you have defined a calculated column as contact_type which is not available in the group by clause. You should use
GROUP BY Category_Type, -- Contact_Type
case
when event.contact_type=0 then 'Window'
when event.contact_type=1 then 'Phone'
end
It is a better approach to name your calculated columns different than the columns in any of your tables.
Use case statements for pivoting:
SELECT CONTACT_TYPE,
SUM(CASE WHEN CATEGORY_TYPE='Admissions' THEN CATEGORY_COUNT END) ADMISSIONS,
SUM(CASE WHEN CATEGORY_TYPE='Financial Aid' THEN CATEGORY_COUNT END) FINANCIAL_AID,
SUM(CASE WHEN CATEGORY_TYPE='Miscellaneous' THEN CATEGORY_COUNT END) MISCELLANEOUS,
SUM(CASE WHEN CATEGORY_TYPE='Student Financials' THEN CATEGORY_COUNT END) STUDENT_FINANCIALS,
SUM(CASE WHEN CATEGORY_TYPE='Registration' THEN CATEGORY_COUNT END) REGISTRATION
FROM TEST_3 GROUP BY CONTACT_TYPE;
Output:
CONTACT_TYPE ADMISSIONS FINANCIAL_AID MISCELLANEOUS STUDENT_FINANCIALS REGISTRATION
Phone 5758 10048 4497 4857 11
Window 1775 17377 2720 14039 null
I have so many long database so I used seq_no in commas separate using more than one sequence store in single column but now I want all sequence in a single column so I am confused how to create this sql result for this.
For example:
TABLE STRUCTURE
SR_NO IS INT ,
SEQ_NO IS VARCHAR(MAX)
SR_NO SEQ_NO
---------------------------------
1 1839073,
2 1850097,1850098,
3 1850099,1850100,1850110
I need to get this result:
SEQ_NO
--------------
1839073
1850097
1850098
1850099
1850100
1850110
Thanks!
declare #t table(Id int,seq varchar(100))
insert into #t (Id,seq) values (1,'1839073,'),(2,'1839073,1850098,'),(3,'1850099,1850100,1850110 ')
;With Cte as (
SELECT A.Id,
Split.a.value('.', 'VARCHAR(100)') AS Seq
FROM
(
SELECT Id,
CAST ('<M>' + REPLACE(seq, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM #t
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) )
Select ID,Seq from Cte Where Seq > ''
Try splitting it with XML
SELECT SR_NO, t.c.value('.', 'VARCHAR(2000)') COL1
FROM (
SELECT SR_NO, x = CAST('<t>' +
REPLACE(SEQ_NO, ',', '</t><t>') + '</t>' AS XML)
FROM
(values(1,'1839073'),(2, '1850097,1850098'),
(3, '1850099,1850100,1850110')) y(SR_NO, SEQ_NO)
) a
CROSS APPLY x.nodes('/t') t(c)
Result:
SR_NO COL1
1 1839073
2 1850097
2 1850098
3 1850099
3 1850100
3 1850110
You can replace this with your table:
(values (1,'1839073'),(2, '1850097,1850098'),
(3, '1850099,1850100,1850110')) y(SR_NO, SEQ_NO)
This should do it: (Replace YourTableName with your table name)
;WITH CTE(NEW_SEQ_NO, SEQ_NO) as (
SELECT LEFT(SEQ_NO, CHARINDEX(',',SEQ_NO + ',') -1),
STUFF(SEQ_NO, 1, CHARINDEX(',',SEQ_NO + ','), '')
FROM YourTableName
WHERE SEQ_NO <> '' AND SEQ_NO IS NOT NULL
UNION all
SELECT LEFT(SEQ_NO, CHARINDEX(',',SEQ_NO + ',') -1),
STUFF(SEQ_NO, 1, CHARINDEX(',',SEQ_NO + ','), '')
FROM CTE
WHERE SEQ_NO <> '' AND SEQ_NO IS NOT NULL
)
SELECT NEW_SEQ_NO from CTE ORDER BY NEW_SEQ_NO
You can check this topic for more information:
Turning a Comma Separated string into individual rows
I have written the following query after referring Turning a Comma Separated string into individual rows
It will work for you
create table STRUCTURE(SR_NO int, SEQ_NO varchar(max))
insert STRUCTURE select 1, '1839073,'
insert STRUCTURE select 2, '1850097,1850098,'
insert STRUCTURE select 3, '1850099,1850100,1850110'
;with tmp(SR_NO, DataItem, SEQ_NO) as (
select SR_NO, LEFT(SEQ_NO, CHARINDEX(',',SEQ_NO+',')-1),
STUFF(SEQ_NO, 1, CHARINDEX(',',SEQ_NO+','), '')
from STRUCTURE
union all
select SR_NO, LEFT(SEQ_NO, CHARINDEX(',',SEQ_NO+',')-1),
STUFF(SEQ_NO, 1, CHARINDEX(',',SEQ_NO+','), '')
from tmp
where SEQ_NO > ''
)
Select DataItem as SEQ_NO from tmp order by SEQ_NO;
I've got a stored procedure with a pivot where data fields become columns. Data that is presently returned has some redundancies and would like to see if there is a way to correct this. The stored procedure is actually feeding a .rdlc report and current output looks like this:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
12 1
18 1
18 1
18 1
19 1
19 1
2 1
2 1
This is what it needs to look like:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
2 1 1
12 1
18 1 1 1
19 1 1
Period column needs to sorted in ascending fashion and repeating instances need to be added to the same line.
The stored procedure and corresponding view responsible for output is as follows:
BEGIN
DECLARE #cols NVARCHAR(MAX)
DECLARE #query NVARCHAR(MAX)
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SELECT #cols = STUFF((SELECT '],[' + [Description]
FROM vQualScoringGrade
GROUP BY [Description]
ORDER BY MAX([orderby]), [Description]
FOR XML PATH('')), 1,2,'') + ']'
SET #query = N'SELECT Period, ' + #cols + ' FROM
(SELECT Period, Description, Value, OrderBy FROM
vQualScoringGrade) p
PIVOT (SUM([Value]) for [Description] IN ( ' + #cols + ' )) AS pvt ORDER BY Period'
execute(#query)
end
SELECT TOP (100) PERCENT Period, Description, GradeCount AS Value, OrderBy
FROM (SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'NoOfInterim' AS Description, COUNT(Number) AS
GradeCount, 1 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Excellent' AS Description, COUNT(Description) AS
GradeCount, 2 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent_1
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'VeryGood' AS Description, COUNT(Description) AS
GradeCount, 3 AS OrderBy
FROM vQualScoringVeryGood AS vQualScoringVeryGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Good' AS Description, COUNT(Description) AS
GradeCount, 4 AS OrderBy
FROM vQualScoringGood AS vQualScoringGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Satisfactory' AS Description, COUNT(Description) AS
GradeCount, 5 AS OrderBy
FROM vQualScoringSatisfactory AS vQualScoringSatisfactory
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Unsatisfactory' AS Description, COUNT(Description) AS
GradeCount, 6 AS OrderBy
FROM vQualScoringUnsatisfactory AS vQualScoringUnsatisfactory
GROUP BY Number, Description) AS QualScoringGrade
ORDER BY OrderBy
I am guessing that the problem is due to the OrderBy column in your PIVOT query. This line is the cause of your problem:
SELECT Period, Description, Value, OrderBy
I would alter the query to be:
SELECT #cols = STUFF((SELECT '],[' + [Description]
FROM vQualScoringGrade
GROUP BY [Description]
ORDER BY MAX([orderby]), [Description]
FOR XML PATH('')), 1,2,'') + ']'
SET #query = N'SELECT Period, ' + #cols + '
FROM
(
SELECT Period, Description, Value
FROM vQualScoringGrade
) p
PIVOT
(
SUM([Value])
for [Description] IN ( ' + #cols + ' )
) AS pvt
ORDER BY Period'
execute(#query);
The OrderBy column is not being used in the outer select or the PIVOT but you include it in the subquery. This column is being used in the grouping that takes place during a PIVOT. If the values are distinct, then you will get multiple rows.
You can easily test this by including the OrderBy on the final select list.
I have a problem splitting single column values to multiple column values.
For Example:
Name
------------
abcd efgh
ijk lmn opq
asd j. asdjja
asb (asdfas) asd
asd
and I need the output something like this:
first_name last_name
----------------------------------
abcd efgh
ijk opq
asd asdjja
asb asd
asd null
The middle name can be omitted (no need for a middle name) The columns are already created and need to insert the data from that single Name column.
Your approach won't deal with lot of names correctly but...
SELECT CASE
WHEN name LIKE '% %' THEN LEFT(name, Charindex(' ', name) - 1)
ELSE name
END,
CASE
WHEN name LIKE '% %' THEN RIGHT(name, Charindex(' ', Reverse(name)) - 1)
END
FROM YourTable
An alternative to Martin's
select LEFT(name, CHARINDEX(' ', name + ' ') -1),
STUFF(name, 1, Len(Name) +1- CHARINDEX(' ',Reverse(name)), '')
from somenames
Sample table
create table somenames (Name varchar(100))
insert somenames select 'abcd efgh'
insert somenames select 'ijk lmn opq'
insert somenames select 'asd j. asdjja'
insert somenames select 'asb (asdfas) asd'
insert somenames select 'asd'
insert somenames select ''
insert somenames select null
;WITH Split_Names (Name, xmlname)
AS
(
SELECT
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
FROM somenames
)
SELECT
xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
What you need is a split user-defined function. With that, the solution looks like
With SplitValues As
(
Select T.Name, Z.Position, Z.Value
, Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
From Table As T
Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
)
Select Name
, FirstName.Value
, Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
Left Join SplitValues As SecondName
On S2.Name = S1.Name
And S2.Num = 2
Left Join SplitValues As ThirdName
On S2.Name = S1.Name
And S2.Num = 3
Where FirstName.Num = 1
Here's a sample split function:
Create Function [dbo].[udf_Split]
(
#DelimitedList nvarchar(max)
, #Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(#DelimitedList, Len(#Delimiter)) <> #Delimiter Then #Delimiter Else '' End
+ #DelimitedList
+ Case When Right(#DelimitedList, Len(#Delimiter)) <> #Delimiter Then #Delimiter Else '' End
As List
, Len(#Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(#DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(#Delimiter, CL.list, N.Value + 1)
- ( CharIndex(#Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = #Delimiter
)
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 1), ' ', -1) AS currency,
SUBSTRING_INDEX(SUBSTRING_INDEX(rent, ' ', 3), ' ', -1) AS rent
FROM tolets
I used it recently:
select
substring(name,1,charindex(' ',name)-1) as Col1,
substring(name,charindex(' ',name)+1,len(name)) as Col2
from TableName
Here is how I did this on a SQLite database:
SELECT SUBSTR(name, 1,INSTR(name, " ")-1) as Firstname,
SUBSTR(name, INSTR(name," ")+1, LENGTH(name)) as Lastname
FROM YourTable;
Hope it helps.