I have 1 table called BSFolks that contains:
Name Number
---- ------
Sam Jackson BS001
Sam Jackson BS003
Sam Jackson null
Miley Cyrus BS666
Miley Cyrus BS069
Miley Cyrus BS013
C. Agulera BS420
And would like to return
Name Number
---- ------
Sam Jackson BS001,BS003
Miley Cyrus BS666,BS069,BS013
C. Agulera BS420
I've been having a hard time finding the correct search terms for this operation so please excuse me if this has already been answered.
I am using SQL Server 2008 BTW.
Thanks y'all!
EDIT:
Here's the solution.
SELECT Name, STUFF((SELECT DISTINCT ',' + Number FROM BSFolks
WHERE Name = X.Name
AND (Number != '' AND Number IS NOT NULL)
FOR XML PATH ('')), 1, 1, '') AS Numbers
FROM BSFolks X
GROUP BY Name
SELECT Name, STUFF((SELECT DISTINCT ',' + Number FROM BSFolks
WHERE Name = X.Name
AND (Number != '' AND Number IS NOT NULL)
FOR XML PATH ('')), 1, 1, '') AS Numbers
FROM BSFolks X
GROUP BY Name
Related
I have a concatenated string in a field that I now need to pull statistics from.
What is needed is a count of how many records are from each county in Maryland.
fieldname county_city is stored as follows:
Frederick,MD - Frederick County - 21701
//State
trim(substring(SUBSTRING_INDEX(county_city,',',-1),1,3)) as state
//city
SUBSTRING_INDEX(county_city,'-',1) as city_state
//zip code
SUBSTRING_INDEX(county_city,'-',-1) as zipcode,
but getting the county has been eluding me!
I have an idea that getting the count will elude me as well.
With string functions is a 2 step procedure:
set #s = 'Frederick,MD - Frederick County - 21701';
SELECT TRIM(SUBSTRING_INDEX(SUBSTRING(#s, LENGTH(SUBSTRING_INDEX(#s, '-' ,1)) + 2), '-', 1));
See the demo.
Result:
Frederick County
How to make an SQL query for a table based on the following conditions:
Result is a single column that concatenates all fields delimited by a dash into a single string (ex: FieldA-FieldB-FieldC-FieldD-FieldE)
If a given field is NULL or if the field's value is a string such as "EMPTY" or "NA", do not concatenate that field's value into the result string
Example Table Person (FirstName, LastName, Street, City, State):
Bob | Dylan | 555 Street | Mountain View | California
Ally | M | NULL | Seattle | Washington
Jan | Van | EMPTY | EMPTY | Oregon
Nancy | Finn | EMPTY | EMPTY | NA
Don | William | NULL | EMPTY | Illinois
Result:
Bob-Dylan-555 Street-Mountain View-California
Ally-M-Seattle-Washington
Jan-Van-Oregon
Nancy-Finn
Don-William-Illinois
I know this can be done programatically, but wanted to know if this can be done in SQL and if it would be more efficient to do so in the query itself.
Fully-baked solution for SQL Server 2017 and above:
SELECT *
FROM Person p
OUTER APPLY (
SELECT STRING_AGG(NULLIF(NULLIF(val, 'EMPTY'), 'NA'), '-')
WITHIN GROUP (ORDER BY n) AS val
FROM (VALUES (1, p.FirstName), (2, p.LastName),(3, p.Street),
(4,p.City), (5, p.State)) z(n, val)
)sub;
DBFiddle Demo
MySQL version using CONCAT_WS:
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is NULL, the result is NULL.
CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.
SELECT CONCAT_WS('-',
NULLIF(NULLIF(FirstName, 'EMPTY'), 'NA'),
NULLIF(NULLIF(LastName, 'EMPTY'), 'NA'),
NULLIF(NULLIF(Street, 'EMPTY'), 'NA'),
NULLIF(NULLIF(City, 'EMPTY'), 'NA'),
NULLIF(NULLIF(State, 'EMPTY'), 'NA')) AS r
FROM Person p;
DBFiddle Demo2
first, use CONCAT to concatenate the fields.
then use REPLACE to replace NULL values
SELECT REPLACE( CONCAT( field1, "-", field2 , "-", field3) , "NULL", "EMPTY" )
FROM `table`
Try This
SELECT ISNULL(FirstName,'') + '-' +
ISNULL (LastName,'') + '-' +
ISNULL (City,'') + '-' +
ISNULL (State,'')
FROM Person
OR LIKE THIS
SELECT CASE WHEN ISNULL(FirstName,'') = '' THEN '' ELSE FirstName + '-' +
CASE WHEN ISNULL(LastName,'') = '' THEN '' ELSE LastName + '-' +
CASE WHEN ISNULL(City,'') = '' THEN '' ELSE City + '-' +
CASE WHEN ISNULL(State,'') = '' THEN '' ELSE State + '-' END AS
ColumnName
FROM Person
Your select should be something like this:
select isnull(FieldA,'')+ '-' + isnull (FieldB,'') + '-' + isnull (FieldC,'') ....
and so on ..
This will work on MS SQL server if you don't want '-' if previous field is null than you should use case statement.
If you want to replace also 'Empty' or 'NULL' strings than you should use:
select replace(replace( isnull(FieldA+'-','') , 'Empty' , ''),'Null', '')
I have modified isnull() by Nitin_g3 observation.
I have a table with some problem data. For example, the table is as follow :
ID NAME JOB
--- --------------------------- ---------------
1 Peter Teacher
2 John Programmer
3 Tom**He is a Teacher
4 Alan**He is a Accountant
The problem is some data has been correctly inserted but some hasn't. Now I want to execute an SQL in order to make the table looks like below :
ID NAME JOB
--- --------------------------- ---------------
1 Peter Teacher
2 John Programmer
3 Tom Teacher
4 Alan Accountant
I am not familiar with SQL Statement so I can just think of using the following PHP Script to fix this problem.
$sql1 = "SELECT NAME FROM MY_TABLE WHERE JOB = '' AND NAME LIKE '%He is a %'";
$res1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($res1)){
$new_data = explode("**He is a ", $row1["NAME"]);
$sql2 = "UPDATE MY_TABLE SET NAME = '".$data[0]."', JOB = '".$data[1]."' WHERE ID = '".$data["ID"]."'";
mysql_query($sql2);
}
Can anyone suggest a better way for me to fix this problem with one or a few SQL Statement ? Thanks
UPDATE
SET NAME = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 1), ' ', -1),
job = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 2), ' ', -1)
WHERE NAME LIKE '%**He is a %'
You can use the substring_index function to break up the string, and apply all the changes in a single update statement:
UPDATE my_table
SET JOB = SUBSTRING_INDEX (name, '**He is a ', -1),
name = SUBSTRING_INDEX (name, '**He is a ', 1),
WHERE name LIKE '%**He is a %' AND
(job IS NULL OR job = '') -- Just to be on the safe side
I have a table like this
id value
------- ---------------
1 ind.kolkatta
2 ind.pune
3 ind.mumbai
4 pak.lahore
5 pak.karachi
6 uae.sharjah
I want to return the following table:
id contry place
------- --------- ----------
1 ind kolkatta
2 ind pune
3 ind mumbai
4 pak lahore
5 pak karachi
6 uae sharjah
how can i do that using MSSQL.? I have already done in MYSQL using SUBSTRING_INDEX function
My MySql query
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 1), '.', -1) as contry,
SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 2), '.', -1) as place
FROM `table`
Try following query:-
SELECT ID, SUBSTRING(value, 1, CHARINDEX('.', value)-1) AS contry,
SUBSTRING(value, CHARINDEX(',', value)+1, LEN(value)) AS place
FROM YOUR_TABLE;
This might be helpful to you.
Hope the Below Query helps you.
SELECT id, SUBSTRING(value,1,3) as Country,SUBSTRING(value,4,LEN(value))AS Place FROM TableName
Try this:
SELECT Id,
LEFT(Value, CHARINDEX('.', Value)-1) AS Country,
STUFF(Value, 1, CHARINDEX('.', Value), '') AS Place
FROM Table
As per King King comment I checked the following
SELECT Id,
PARSENAME(value, 2) AS Country,
PARSENAME(Value, 1) AS Place
FROM Table
The above one worked, but I not sure about the version supported (I am using SSMS 2012).
Or just loop and it will parse out how ever many periods you have in your name.
DECLARE #FILE VARCHAR(55) = 'ind.kol.katta.test1.test2.test3.test4'
DECLARE #FILEFUN AS VARCHAR(55) = LEFT(#FILE,CHARINDEX('.',#FILE))
DECLARE #FILENAMEOUTPUT AS TABLE(Name Varchar(55))
WHILE LEN(#FILE) > 0
BEGIN
INSERT INTO #FILENAMEOUTPUT
SELECT REPLACE(#FILEFUN,'.','')
SET #FILE = REPLACE(#FILE,#FILEFUN,'')
SET #FILEFUN = iif(CHARINDEX('.',#FILE)=0,#FILE,LEFT(#FILE,CHARINDEX('.',#FILE)))
END
SELECT * FROM #FILENAMEOUTPUT
I'm using this MySQL query
SELECT COUNT(pros_a) + COUNT(pros_b) + COUNT(pros_c) + COUNT(pros_d) + COUNT(pros_e) AS pros_total FROM my_table WHERE contentid = 'id'
to count and sum fields in each column. But this returns ALL fields (full and empty). I want to count only filled fields, excluding empty fields. How can I do that? Just a little bit... confused! :)
Any help would be very appreciated!
Thanks
EDIT:
my_table
pros_a pros_b pros_c pros_d pros_e
------- ------ ------ ------ ------
good (empty) good good (empty)
expected result
pros_total
----------
3
The COUNT(column) function does not count fields that are NULL. It counts empty (zero-length) strings though.
You can change these into:
COUNT( CASE WHEN column <> '' THEN column END )
or:
SUM(column <> '')
The last works in MySQL because TRUE is evaluated as 1 and FALSE as 0.
SELECT COUNT(DISTINCT pros_a) + COUNT(DISTINCT pros_b) + COUNT(DISTINCT pros_c) + COUNT(DISTINCT pros_d) + COUNT(DISTINCT pros_e) FROM my_table WHERE contentid = 'id'
The above one should work.
Use where condition for empty fields, for example WHERE pros_a != '' or pros_a != '0' if is NULL. pros_a != '' AND pros_b != ''