Aggregating date in one column - sql

For a purpose of reporting I need to present data from table:
table A (column1, column2, date1, date2, date3,...,dateN)
My query need to present all dates in one column separated with # .
(YYYY-MM-DD# YYYY-MM-DD#..)
But problem is that number of date columns is not fixed, because from product to product can be different number of dates.
Any idea ?

This statement works for postgresql, but you can replace the || with + for sql-server I think, just try and it should work, you should be able to figure out the rest.
|| is the concatenation symbol in postgres or you could also use the concatenation function available.
SELECT column1 || CASE WHEN column2 IS NOT NULL THEN '#' || column2 ELSE '' END || ... FROM tablehere
Hope it helps!

After consideration, I want to change my answer. Perhaps a little lighter
Declare #YourTable table (Column1 int,Column2 int,date1 date,date2 date,date3 date)
Insert Into #YourTable values
(1,25,'2016-01-15','2016-03-22',null),
(2,50,'2016-04-15','2016-07-29','2016-09-30')
Select Column1
,Column2
,Dates=Replace(Replace((
Select x=format(date1,'yyyy-MM-dd# ')
,x=format(date2,'yyyy-MM-dd# ')
,x=format(date3,'yyyy-MM-dd# ')
--x=format(dateNN,'yyyy-MM-dd# ')
For XML Path('')
) ,'<x>',''),'</x>','')
From #YourTable
Returns
Column1 Column2 Dates
1 25 2016-01-15# 2016-03-22#
2 50 2016-04-15# 2016-07-29# 2016-09-30#

Related

Find the frequency of all words from a concatenated column

I have concatenated text column derived from three columns in a table. I need to have frequency of all single words from that concatenated column.
Column1 Column2 column3
This is Test 1
This was Test two
What I need is concatenation of all three i.e. This is Test 1, This was Test two and then count of each word ie.
This - 2
is - 1
was -1
Test - 2
1- 1
two - 1
You can use string_split and cross apply to achieve the required result. try the following:
Code:
declare #tab table (col1 varchar(100), col2 varchar(100), col3 varchar(100))
insert into #tab
select 'This is', 'Test', '1'
union
select 'This was','Test','two'
select value, count(*) rec_count
from #tab
cross apply string_split((col1+' '+col2+' '+col3), ' ')
group by value

Efficient way to merge alternating values from two columns into one column in SQL Server

I have two columns in a table. I want to merge them into a single column, but the merge should be done taking alternate characters from each columns.
For example:
Column A --> value (1,2,3)
Column B --> value (A,B,C)
Required result - (1,A,2,B,3,C)
It should be done without loops.
You need to make use of the UNION and get a little creative with how you choose to alternate. My solution ended up looking like this.
SELECT ColumnA
FROM Table
WHERE ColumnA%2=1
UNION
SELECT ColumnB
FROM TABLE
WHERE ColumnA%2=0
If you have an ID/PK column that could just as easily be used, I just didn't want to assume anything about your table.
EDIT:
If your table contains duplicates that you wish to keep, use UNION ALL instead of UNION
Try This;
SELECT [value]
FROM [Table]
UNPIVOT
(
[value] FOR [Column] IN ([Column_A], [Column_B])
) UNPVT
If you have SQL 2016 or higher you can use:
SELECT QUOTENAME(STRING_AGG (cast(a as varchar(1)) + ',' + b, ','), '()')
FROM test;
In older versions, depending on how much data you have in your tables you can also try:
SELECT QUOTENAME(STUFF(
(SELECT ',' + cast(a as varchar(1)) + ',' + b
FROM test
FOR XML PATH('')), 1, 1,''), '()')
Here you can try a sample
http://sqlfiddle.com/#!18/6c9af/5
with data as (
select *, row_number() over order by colA) as rn
from t
)
select rn,
case rn % 2 when 1 then colA else colB end as alternating
from data;
The following SQL uses undocumented aggregate concatenation technique. This is described in Inside Microsoft SQL Server 2008 T-SQL Programming on page 33.
declare #x varchar(max) = '';
declare #t table (a varchar(10), b varchar(10));
insert into #t values (1,'A'), (2,'B'),(3,'C');
select #x = #x + a + ',' + b + ','
from #t;
select '(' + LEFT(#x, LEN(#x) - 1) + ')';

How to concatenate columns without null value in sql

This question is asked many time here but i am not getting the proper output as i am expecting:
I have a table in which i need to concatenate columns but i don't want NULL value in it. I want it in sql server 2008 concate function does not work in 2008.
Example:
OrderTable
Customer_Number order1 order2 order3 order4
1 NULL X Y NULL
2 NULL A B NULL
3 V NULL H NULL
Now want i want is the data in concatenated manner for order only like this:
Customer_Number Order
1 X,Y
2 A,B
3 V,H
This is the code i used
Select Customer_number, ISNULL(NULLIF(order1,' ')+',','')+
ISNULL(NULLIF(order2,' ')+',','')+
ISNULL(NULLIF(order3,' ')+',','')+
ISNULL(NULLIF(order4,' ')+',','')
as Order from Ordertable
I got the below output
Customer_Number Order
1 NULL,X,Y,NULL
2 NULL,A,B,NULL
3 V,NULL,H,NULL
I already try Coalesce, Stuff, ISNULL, NULLIF but all have same result
Thanks in advance !!!
Another variation, for fun and profit, demonstrating the FOR XML trick to concatenate values pre-SQL Server 2012.
SELECT Customer_Number, STUFF(
(SELECT ',' + order1, ',' + order2, ',' + order3, ',' + order4 FOR XML PATH('')),
1, 1, ''
)
This is slight overkill for a constant number of columns (and not particularly efficient), but an easy to remember pattern for concatenation. Also, it shows off STUFF, a function any SQL developer should learn to love.
Example
Declare #YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into #YourTable Values
(1,NULL,'X','Y',NULL)
,(2,NULL,'A','B',NULL)
,(3,'V',NULL,'H',NULL)
Select Customer_Number
,[Order] = IsNull(stuff(
IsNull(','+order1,'')
+IsNull(','+order2,'')
+IsNull(','+order3,'')
+IsNull(','+order4,'')
,1,1,''),'')
From #YourTable
Returns
Customer_Number Order
1 X,Y
2 A,B
3 V,H
EDIT - IF the "NULL" are strings and NOT NULL Values
Declare #YourTable Table ([Customer_Number] varchar(50),[order1] varchar(50),[order2] varchar(50),[order3] varchar(50),[order4] varchar(50))
Insert Into #YourTable Values
(1,'NULL','X','Y','NULL')
,(2,'NULL','A','B','NULL')
,(3,'V','NULL','H','NULL')
Select Customer_Number
,[Order] = IsNull(stuff(
IsNull(','+nullif(order1,'NULL'),'')
+IsNull(','+nullif(order2,'NULL'),'')
+IsNull(','+nullif(order3,'NULL'),'')
+IsNull(','+nullif(order4,'NULL'),'')
,1,1,''),'')
From #YourTable
This is a bit unpleasant, it needs to be in a subquery to remove the trailing comma efficiently (though you could use a CTE):
SELECT
Customer_number,
SUBSTRING([Order], 0, LEN([Order])) AS [Order]
FROM(
SELECT
Customer_number,
COALESCE(order1+',', '') +
COALESCE(order2+',', '') +
COALESCE(order3+',', '') +
COALESCE(order4+',', '') AS [Order]
FROM
OrderTable) AS SubQuery
You were on the right track with the Coalesce, or IsNull. Instead of trying to track the length and use substring, left or stuff, I just used a replace to remove the trailing comma that would show up from the coalesce.
Select Customer_number,
Replace(
Coalesce(Order1 + ',','')+
Coalesce(Order2 + ',','')+
Coalesce(Order3 + ',','')+
Coalesce(Order4 + ',','')
+',',',,','') --Hack to remove the Last Comma
as [Order] from Ordertable

how to replace a comma with single quote comma in SQLIN clause

Hi all I have a an where clause like below
select * from table1
where colum1 IN (?parameter)
when I pass the values to the parameter they show up like below
('1,2,3') but to execute the query I need to change the values as ('1','2','3')
is there a way to replace the commas with single quotes comma in IN clause directly?
There is one hack to do what you want, using like:
select *
from table1
where ',' || column1 || ',' like '%,' || (?parameter) || ',%';
This functions, but it will not make use of an index on column1. You should think about other solutions, such as:
Parsing the string into a table variable.
Using in with a fixed number of parameters.
Storing the values in a table.
There may be other Oracle-specific solutions as well.
Use MS SQL, you can convert it into table value and using join for your condition, I am not familiar oracle but you can find same way to do it.
DECLARE #IDs varchar(max) ='1,2,3';
;WITH Cte AS
(
SELECT
CAST('<ID>' + REPLACE( #IDs, ',' , '</ID><ID>') + '</ID>' AS XML) AS IDs
)
SELECT '''' + Split.a.value('.', 'VARCHAR(100)') +'''' AS ID FROM Cte
CROSS APPLY Cte.IDs.nodes('/ID') Split(a)
You can achieve it using with clause. Logic here is to convert each comma separated value into different row.
with temp_tab as (
select replace(regexp_substr(parameter, '[^,]+',1, level),'''','') as str
from dual
connect by level<= length(regexp_replace(parameter, '[^,]+'))+1 )
select * from table1 where column1 in (select str from temp_tab);

Select 2 columns in one and combine them

Is it possible to select 2 columns in just one and combine them?
Example:
select something + somethingElse as onlyOneColumn from someTable
(SELECT column1 as column FROM table )
UNION
(SELECT column2 as column FROM table )
Yes, just like you did:
select something + somethingElse as onlyOneColumn from someTable
If you queried the database, you would have gotten the right answer.
What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.
Yes,
SELECT CONCAT(field1, field2) AS WHOLENAME FROM TABLE
WHERE ...
will result in data set like:
WHOLENAME
field1field2
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer
Yes it's possible, as long as the datatypes are compatible. If they aren't, use a CONVERT() or CAST()
SELECT firstname + ' ' + lastname AS name FROM customers
The + operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL result. Instead, combine + with the function COALESCE and you'll be set.
Here is an example:
SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1.
For this example, if column1 is NULL, then the results of column2 will show up, instead of a simple NULL.
Hope this helps!
To complete the answer of #Pete Carter, I would add an "ALL" on the UNION (if you need to keep the duplicate entries).
(SELECT column1 as column FROM table )
UNION ALL
(SELECT column2 as column FROM table )
DROP TABLE IF EXISTS #9
CREATE TABLE #9
(
USER1 int
,USER2 int
)
INSERT INTO #9
VALUES(1, 2), (1, 3), (1, 4), (2, 3)
------------------------------------------------
(SELECT USER1 AS 'column' from #9)
UNION ALL
(SELECT USER2 AS 'column' from #9)
Would then return : Result
Yes, you can combine columns easily enough such as concatenating character data:
select col1 | col 2 as bothcols from tbl ...
or adding (for example) numeric data:
select col1 + col2 as bothcols from tbl ...
In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.
if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.
eg:
select (id + name) as one from table 1; (id is numeric)
throws invalid number exception
in such case you can || operator which is concatenation.
select (id || name) as one from table 1;
Your syntax should work, maybe add a space between the colums like
SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable
I hope this answer helps:
SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;
select column1 || ' ' || column2 as whole_name FROM tablename;
Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.
SELECT firstname || ' ' || lastname FROM users;