Phrase Search in SQL Server 2008 (T-SQL) - tsql

I have a varchar column with 3 rows:
i eat orange,
orange,
oranges are nice
I want SELECT query to return the result in this order:
orange, oranges are nice, i eat orange
i.e. those matches that start with the 'keyword'=orange should come before those that contain the keyword which again should come before those that ends with the keyword.
How can I do this using T-SQL? I tried using the LIKE keyword but no success so far.

WHERE column LIKE '%' + keyword + '%'
ORDER BY CASE WHEN column = keyword THEN 0
WHEN column LIKE keyword + '%' THEN 1
WHEN column LIKE '%' + keyword + '%' THEN 2 END
But really, for this kind of search you want to use a full-text index.

Try the following order by clause (assuming your WHERE clause returns only matches)
ORDER BY charIndex(keyword,col_name),length(col_name)
This will put the earliest occurrence of the keyword first.

Related

postgres coalesce fields, sum and group by

maybe someone can help me out with a postgres query.
the table structure looks like this
nummer nachname vorname cash
+-------+----------+----------+------+
2 Bert Brecht 0,758
2 Harry Belafonte 1,568
3 Elvis Presley 0,357
4 Mark Twain 1,555
4 Ella Fitz 0,333
…
How can I coalesce the fields where "nummer" are the same and sum the cash values?
My output should look like this:
2 Bert, Brecht 2,326
Harry, Belafonte
3 Elvis, Presley 0,357
4 Mark, Twain 1,888
Ella, Fitz
I think the part to coalesce should work something like this:
array_to_string(array_agg(nachname|| ', ' ||coalesce(vorname, '')), '<br />') as name,
Thanks for any help,
tony
SELECT
nummer,
string_agg(nachname||CASE WHEN vorname IS NULL THEN '' ELSE ', '||vorname END, E'\n') AS name,
sum(cash) AS total_cash
FROM Table1
GROUP BY nummer;
See this SQLFiddle; note that it doesn't display the newline characters between names, but they're still there.
The CASE statement is used instead of coalesce so you don't have a trailing comma on entries with a last name but no first name. If you want a trailing comma, use format('%s, %s',vorname,nachname) instead and avoid all that ugly string concatenation business:
SELECT
nummer, string_agg(format('%s, %s', nachname, vorname), E'\n'),
sum(cash) AS total_cash
FROM Table1
GROUP BY nummer;
If string_agg doesn't work, get a newer PostgreSQL, or mention the version in your questions so it's clear you're using an obsolete version. The query is trivially rewritten to use array_to_string and array_agg anyway.
If you're asking how to sum numbers that're actually represented as text strings like 1,2345 in the database: don't do that. Fix your schema. Format numbers on input and output instead, store them as numeric, float8, integer, ... whatever the appropriate numeric type for the job is.

select first letter of different columns in oracle

I want a query which will return a combination of characters and number
Example:
Table name - emp
Columns required - fname,lname,code
If fname=abc and lname=pqr and the row is very first of the table then result should be code = ap001.
For next row it should be like this:
Fname = efg, lname = rst
Code = er002 and likewise.
I know that we can use substr to retrieve first letter of a colume but I don't know how to use it to do with two columns and how to concatenate.
OK. You know you can use substr function. Now, to concatenate you will need a concatenation operator ||. To get the number of row retrieved by your query, you need the rownum pseudocolumn. Perhaps you will also need to use to_char function to format the number. About all those functions and operators you can read in SQL reference. Anyway I think you need something like this (I didn't check it):
select substr(fname, 1, 1) || substr(lname, 1, 1) || to_char(rownum, 'fm009') code
from emp

Select from any of multiple values from a Postgres field

I've got a table that resembles the following:
WORD WEIGHT WORDTYPE
a 0.3 common
the 0.3 common
gray 1.2 colors
steeple 2 object
I need to pull the weights for several different words out of the database at once. I could do:
SELECT * FROM word_weight WHERE WORD = 'a' OR WORD = 'steeple' OR WORD='the';
but it feels ugly and the code to generate the query is obnoxious. I'm hoping that there's a way I can do something like (pseudocode):
SELECT * FROM word_weight WHERE WORD = 'a','the';
You are describing the functionality of the in clause.
select * from word_weight where word in ('a', 'steeple', 'the');
If you want to pass the whole list in a single parameter, use array datatype:
SELECT *
FROM word_weight
WHERE word = ANY('{a,steeple,the}'); -- or ANY('{a,steeple,the}'::TEXT[]) to make explicit array conversion
If you are not sure about the value and even not sure whether the field will be an empty string or even null then,
.where("column_1 ILIKE ANY(ARRAY['','%abc%','%xyz%']) OR column_1 IS NULL")
Above query will cover all possibility.

TSQL syntax for enclosing search terms within brackets

I believe [ and ] are special characters when using with LIKE clause in TSQL( SQlserver 2005 if it matters). How do i escape the search term in the stored procedure, i did below but does not return valid records even while exists
SELECT * FROM Table WHERE Column LIKE '%['+ #searchedTerm +']'
So which is the valid thing to do, when searching like above??
You need to escape the opening (not the closing) bracket like this:
LIKE '%[[]' + #searchedTerm + ']'
The MSDN page for LIKE has a section "Using Wildcard Characters As Literals"
Edit, after comment
LIKE '[[]cap]%' searches for a name containing the string [cap]
LIKE '[wel]%' searches for a name containing one of the letters w, e or l
Try this:
DECLARE #searchedTerm as varchar(50);
SET #searchedTerm = 'TEST VALUE'
SELECT * FROM Table WHERE Column LIKE '%[[]' + #searchedTerm +']'
try this:
SELECT * FROM Table WHERE Column LIKE '%/['+ #searchedTerm +']' {escape '/'}

A Query to return Alphanumeric

Does any have any query that returns apha numerice values only
Sample
Select FirstName,Surname,NationalID From Contacts
Results
FirstName|Surname|NationalID
Tony |Smith |934&#fdsaf$34£51
Mary |Jones |655^!ffdat#389£2
Expected results
FirstName|Surname|NationalID
Tony |Smith |934fdsaf34£51
Mary |Jones |655ffdat389£2
In other words i want the query to return numbers and text only :. A-Z and 0-9 only remving '$%^&*(~>
You could try the patindex function. For example with just selecting the FirstName this will remove the first occurrence of non alphanumeric:
SELECT replace(FirstName, substring(FirstName, patindex('%[^a-zA-Z0-9]%', FirstName), 1), '') FROM CONTACTS
To expand this to removing all occurrences, move the patindex call into a function as mentioned here:
CREATE FUNCTION CleanVarchar(#Temp VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^a-zA-Z0-9]%', #Temp) > 0
SET #Temp = STUFF(#Temp, PATINDEX('%[^a-z^0-9]%', #Temp), 1, '')
RETURN #TEmp
END
Finally call the function
Select CleanVarchar(FirstName),CleanVarchar(Surname),CleanVarchar(NationalID) From Contacts
I don't think this is possible with T-SQL only in a neat way.
But you could easily expose such a functionality through a .NET Assembly to the SQL-Server.
There several examples on this topic over the net.
use Replace function of sql server
Sql Server Tips – Removing or Replacing non-alphanumeric characters in strings