Address1,
Address2,
TownCity,
Region,
Postcode,
Country,
Hi guys and gals,
I got a SQL problem.if you could help me with it that'd be awesome.
The table(softc) on top has couple of columns that id like to merge into a single column called "contactinfo"
Columns that needed to be merged:
Address1,
Address2,
TownCity,
Region,
Postcode,
Country,
I've tried UNION but it filters out rows with NULL values.I have 618 records.when i do a UNION it comes up with 750.(some records might contain all NULLs.but they are necessary to map the single into another table)
appreciate your help.thanks
I'm Working with mySQL
Try this
select ISNULL(Address1,'') + ISNULL(' '+Address2,'') + ISNULL(', '+TownCity,'')
+ ISNULL(', '+Region,'') + ISNULL(', '+Postcode,'') + ISNULL(', '+Country,'') as ContactInfo from Softc
You can combine combine / merge cells with Concat command
Example :
CONCAT([Firstname],',',[lastname]) as Fullname.
expression = concat[fieldname/seperator], [fieldname/seperator], ............... etc
Part of database normalization is to break data into it's most discrete components. You have that now. Don't bollocks it up.
A good long term solution to your problem is to update all your null values to empty strings. Then alter those columns so that they don't allow nulls and have a default value of empty strings. This will allow your concatonation queries to run faster because you won't have to check for null values.
Also, if the requirement to return a contact info string is frequent, you can write a database function that returns it.
select IFNull(Address1,'') + IFNull(Address2,'') + IFNull(TownCity,'') + IFNull(Region,'') + IFNull(Postcode,'') + IFNull(Country,'') as ContactInfo from Softc
That should be what you want...
Related
I have two databases. One database is in Mysql and other is in SQL Server.
The structure of both databases is same.
Now the issue is i want to search one value from multiple columns of a table.
what is the best approach and i don't want to use sub-queries in where clause.
I want to search from all columns but which 'll meet the condition.
I am trying with this (MySQL) query. Currently I am placing the hard-coded value than i 'll have to use the stored procedure.
Please correct. thank you
SELECT ID,
NAME,
IFNULL(ADDRESS1, '') ADDRESS1,
IFNULL(PHONE_NO, '') PHONE_NO,
IFNULL(Speciality, '') Speciality
FROM company
WHERE
countryId = 158 AND
('Makeup'='' OR NAME LIKE CONCAT('%','Makeup','%')) AND
('Makeup'='' OR ADDRESS1 LIKE CONCAT('%','Makeup','%')) AND
('Makeup'='' OR PHONE_NO LIKE CONCAT('%','Makeup','%')) AND
CASE
WHEN ''='' THEN 1=1
ELSE (Speciality LIKE CONCAT('%','','%'))
END
ORDER BY NAME ASC;
If you have to write code that works with multiple databases, I would suggest doing more work in the application layer. Simply do:
SELECT ID, NAME, COALESCE(ADDRESS1, '') as ADDRESS1,
COALESCE(PHONE_NO, '') as PHONE_NO,
COALESCE(Speciality, '') as Speciality
FROM company
WHERE countryId = 158 AND
NAME like '%Makeup%' AND
ADDRESS1 like '%Makeup%' AND
PHONE_NO like '%Makeup%' AND
Specialty LIKE '%%'
ORDER BY NAME Asc;
Then, put the wildcards in the "Makeup" string in the application. Two wildcards %% is the same as one %. This will do exactly your logic . . . assuming the various columns are not null.
Also, use ANSI standard functions where possible. COALESCE() is ANSI standard. The above code should work across both databases.
I'm very new to access. I have a data in my column that looks similar to this:
JONES/KEN
SMITH/TAMMY
MILLER FRED
PICARD.JOHN
Am I able to grab the letters before the first non-alphanumeric?
So my result would be:
JONES
SMITH
MILER
PICARD
How about a derived table:
SELECT Left([Surname],InStr([Surname],[NonAlpha])-1) AS LeftName,
MainTable.Surname
FROM MainTable,
(SELECT " " As NonAlpha From Table1
UNION
SELECT "." As NonAlpha From Table1
UNION
SELECT "," As NonAlpha From Table1
UNION
SELECT "/" As NonAlpha From Table1) AS n
WHERE (((MainTable.Surname) Like "*" & [nonalpha] & "*"));
Table1 is a scratch table, it does contain records but the query will only
return the four assigned rows (,./ )
Maintable is the table with a field Surname, which is the field to be split.
Unfortunately, I don't know of a "Word" function that's available in some languages. I would do it with brute force checking using Instr and then Mid to extract the code. The construct would be very convoluted to get every kind of character.
I've used the iif function and nested it - this the basic format here:
iif (instr (fieldname,"{the character}") > 0,
mid(fieldname,1, instr(fieldname,"{the character}")-1,
fieldname{or go further into ifs})
Using your sample data with Client Name as the field and 3 conditions - space, / and period. IT does work, but it's ugly - you will have to scroll pretty far to the right to get everything:
ShortName: IIf(InStr(1,[client_name]," ")>0,
mid(client_name,1,InStr(1,[client_name]," ")-1),
IIf(InStr(1,[client_name],"/")>0,
mid(client_name,1,InStr(1,[client_name],"/")-1),
IIf(InStr(1,[client_name],".")>0,
mid(client_name,1,InStr(1,client_name],".")-1),
Client_Name)))
Put this in a query based on your table.
I want to display two columns of different types or two column data of same type that will be displayed in one column.
The types are date + time, or varchar + varchar etc
I know how to concat strings (add a string to one column) but can't seem to do it for two columns data.
Say I want to display two columns both varchar type, fname + lname = Ajay Punja
Or
Lname + DOB = Punja 01/01/2001
I tried using single and double pipes, plus signs etc but always returns 0.
Is it because I need to convert two different data types into one matching data type? But, both varchar types returns 0.
I think it will help you.
SELECT CONCAT(2, ' test') as result form table_name;
It is also possible to convert a number to a string explicitly using the CAST() function. Conversion occurs implicitly with the CONCAT() function because it expects string arguments. e.g.
SELECT 38.8, CAST(38.8 AS CHAR);
My answer thanks to everyone here :)
SELECT CONCAT(fname, ' ', DOB) as Results FROM Person;
SELECT CONCAT(fname, ' ', lname) as Results FROM Person;
Now I understand how to use CONCAT properly. Before I thought for each bracket it must contain only one attribute (or string) and then CONCAT it with enough bracket of data, but clearly that's wrong.
Wrong example (fail attempt):
SELECT CONCAT(fname, '') + (' ', lname)) as Results FROM Person;
I'm inserting into my database here with parameters from the form.
The form has 4 input fields (current_no, current_street, current_city, current_state). I've set it up so that the client can display each of these values on the web page, but what they want is to be able to view these values in a single column.
so basically from...
current_no | current_street | current_city | current_state
to...
| current_no current_street current_city current_state |
I decided I'd add another column to the table that'll store this "full" value and I figured that populating it would probably be easy but I think I'm missing something here:
insert into customers(current_address) values (current_no + ' ' + current_street + ' ' + current_city + ' ' + current_state)
Although this doesn't give me any errors, it only inserts the current_no value into the column.
How can I concatenate all the values (string types) into the column on database side?
Thanks in advance for any help!
in mySQL use CONCAT()
insert into customers(current_address) values
(
(CONCAT(current_no,' ',current_street,' ',current_city,' ',current_state)
)
or CONCAT_WS()
insert into customers(current_address) values
(
(CONCAT_WS(' ', current_no,current_street,current_city,current_state)
)
Try using
INSERT INTO customers (current_address)
SELECT
CONCAT_WS(' ', current_no, current_street, current_city, current_state)
Others have suggested CONCAT_WS and that's right. The + operator the SQL language doesn't concatenate strings, as you have discovered.
But, please think about your plan of adding a new column to your table for this. New columns with redundant data aren't usually a great idea.
If you already have the columns with the data in them, I suggest you use a SELECT query when you read the table to create your concatenated column. This will take advantage of the data you already have without placing redundant data in the table.
SELECT CONCAT_WS(' ', current_no,current_street,current_city,current_state)
AS current_address
I am solving in these days following situation:
In my DB table I have columns for name and surname.
On my page I have input for searching people, and I am struggling with a problem, how to search the name in database that is stored in two columns and I have the name as string ("Joe Green").
For example, in database I have followings:
Joe New
Joe Blue
Joe Green
Joe Francois Green
What could be the best way, how this problem to solve? I am currently working with MySQL database and Rails 3.
EDIT: Thank you guys for you replies, but I don't know, how to make the query in Rails 3 notation, is it possible to use "concat"?
if your database table engine is myISAM then use FULLTEXT search
first create FULLTEXT index by
CREATE FULLTEXT INDEX fx_name ON pages (name, surname)
then use below query to retrieve required data
SELECT *
FROM table
WHERE MATCH(name,surname) AGAINST ('keyword' IN BOOLEAN MODE)
update
alternative:use CONCAT
first create index
CREATE INDEX users_firstandlast ON users(name, surname);
option1: repeat the CONCAT in your WHERE clause (because AS doesn't create a name you can use in the WHERE clause):
SELECT CONCAT(name, ' ', surname) as fullname
FROM users
WHERE CONCAT(name, ' ', surname) LIKE '%joe green%';
option 2:
SELECT CONCAT(name, ' ', surname) as fullname
FROM users
WHERE name LIKE '%joegreen%' or surname LIKE '%joegreen%';
More information
A lot of this would be significantly simpler if you had given some indication of what language is being used at the interface between the input and the database (since Rails is usually associated with Ruby I'll assume you mean that), however....
SELECT *
FROM yourtable
WHERE CONCAT(name, ' ', surname)
LIKE CONCAT('%',REPLACE(?,' ', '%'),'%')
ORDER BY LEVENSTEIN(CONCAT(name, ' ', surname), ?)
(where '?' is replaced by your search string, and the levenstein function is described here)
Performance will be poor - a better solution would be to split the string Ruby and attempt matches of varying combinations.
One way is:
* split user's input to words
* search each word in name and surname columns
first use the split function to split the string
namearr = name.split
namestr = ""
namearr.each do |i|
namestr = namestr + i
end
then use the values in your query
stmt = "select * from mytable where CONCAT(firstname,surename)= " + namestr
you can use the sql server full text search which i do not recommend because of the performance is very bad ,or use the lucin .net which is more powerful and her are some links :
http://incubator.apache.org/lucene.net/
http://msdn.microsoft.com/en-us/library/ms142571.aspx
mark as answered if it helps :)