appending row number in sql select statement with row value - sql

I am trying to concatenate the select statment results in one row.
For eg :
For this select statement output :
Name
ABC
DEF
GHI
I needed following Output :
Name
1 ABC, 2 DEF, 3 GHI
(Means row number should be appended in front for each row)
I am using wm_concat() function but it is giving me the following o/p : ABC,DEF,GHI
Can anyone help ?

It sounds like you want something similar to this. The listagg() function is available in Oracle 11g+:
select listagg(cast(rownum as varchar2(20))||' '|| name, ', ')
within group (order by name) name
from yourtable
See SQL Fiddle with Demo
Results:
| NAME |
-----------------------
| 1 ABC, 2 DEF, 3 GHI |
If you do not have Oracle 11g, then you can use wm_concat():
select wm_concat(cast(rownum as varchar2(20))||' '|| name) name
from yourtable

Additionaly you could use WITH clause:
WITH tmp AS
(
:your_select_statement
)
SELECT
LISTAGG(rownum || ' ' || :your_column, ', ')
WITHIN GROUP (ORDER BY :your_column) tmp
FROM tmp;
Then rownum is from tmp temporary table which have results of :your_select_statement not from primary table.

Related

Pivot in SQL by Distinct Values

I have a table in BigQuery that looks like this:
Team
Team Id
1
AAAA
2
BBBBB
And I want to get a table that looks like this
Game Id
AAA
BBB
1
1
0
2
0
1
I've tried using PIVOT, but no such luck. Let me know if someone knows how to do this in SQL. Note that there are hundreds of team IDs so I need to dynamically define the team IDs in the pivot statement.
Consider below approach
execute immediate (
select '''
select * from your_table
pivot(count(*) for team_id in (''' || list || "))"
from (
select string_agg("'" || team_id || "'", "," order by team_id) as list
from (select distinct team_id from your_table)
))
if applied to sample data in your question - output is

Merge text in a single column

I have a table, sample records are shown below -
Name ID C.NO Text
---- ---- ---- ----
ABC A 1 first
ABC A 2 xyz
ABC A 3 AMD
ZSD B 1 hoho
ZSD B 2 hihi
now my output would be like -------
Name ID Text
---- --- ----
ABC A firstxyzAMD
ZSD B hohohihi
kindly help me providing sql statement
In SAP Hana, you would use string_agg():
select name, id, string_agg(text, '')
from t
group by name, id;
The equivalent function in MySQL is group_concat(); in Oracle, listagg().
MySQL:
SELECT
GROUP_CONCAT(`text`, '' SEPARATOR '') AS `newtext`
FROM [table]
GROUP BY `name`;
Well, following query worked in my table (MySQL) and I got the exact result as per your specification
select
Name,
ID,
group_concat(Text SEPARATOR '')
from table_name
group by ID

SQL Server: Select multiple records in one select statement

In a query like this one:
SELECT *
FROM `Order`
WHERE `CustID` = '1'
My results are displayed like so:
| CustID| Order |
-----------------
| 1 | Order1|
| 1 | Order2|
| 1 | Order3|
-----------------
How do I write SQL statement, to get a result like this one?:
| CustID| Order |
---------------------------------
| 1 | Order1, Order2, Order3|
---------------------------------
In mySQL it's possible with Group_Concat, but in SQL Server it gives error like syntax error or some.
Use xml path (see fiddle)
SELECT distinct custid, STUFF((SELECT ',' +[order]
FROM table1 where custid = t.custid
FOR XML PATH('')), 1, 1, '')
FROM table1 t
where t.custid = 1
STUFF replaces the first , with an empty string, i.e. removes it. You need a distinct otherwise it'll have a match for all orders since the where is on custid.
FOR XML
PATH Mode
STUFF
You can use Stuff function and For xml clause like this:
SELECT DISTINCT CustId, STUFF((
SELECT ','+ [Order]
FROM [Order] T2
WHERE T2.CustId = T1.CustId
FOR XML PATH('')
), 1, 1, '')
FROM [Order] T1
fiddle here
Note: Using order as a table name or a column name is a very, very bad idea. There is a reason why they called reserved words reserved.
See this link for my favorite way to avoid such things.
try this.
Change table name and column names for what you need;
SELECT custID,
LISTAGG(Order, ', ') WITHIN GROUP (ORDER BY Order) text
FROM table_name
GROUP BY custID
edit for MSSQL . You should use group_concat function.
SELECT custID, GROUP_CONCAT(Order)
FROM table_name
WHERE CustID = 1
GROUP BY custID;

SQL Query - Display Count & All ID's With Same Name

I'm trying to display the amount of table entries with the same name and the unique ID's associated with each of those entries.
So I have a table like so...
Table Names
------------------------------
ID Name
0 John
1 Mike
2 John
3 Mike
4 Adam
5 Mike
I would like the output to be something like:
Name | Count | IDs
---------------------
Mike 3 1,3,5
John 2 0,2
Adam 1 4
I have the following query which does this except display all the unique ID's:
select name, count(*) as ct from names group by name order by ct desc;
select name,
count(id) as ct,
group_concat(id) as IDs
from names
group by name
order by ct desc;
You can use GROUP_CONCAT for that
Depending on version of MSSQL you are using (2005+), you can use the FOR XML PATH option.
SELECT
Name,
COUNT(*) AS ct,
STUFF((SELECT ',' + CAST(ID AS varchar(MAX))
FROM names i
WHERE i.Name = n.Name FOR XML PATH(''))
, 1, 1, '') as IDs
FROM names n
GROUP BY Name
ORDER BY ct DESC
Closest thing to group_concat you'll get on MSSQL unless you use the SQLCLR option (which I have no experience doing). The STUFF function takes care of the leading comma. Also, you don't want to alias the inner SELECT as it will wrap the element you're selecting in an XML element (alias of TD causes each element to return as <TD>value</TD>).
Given the input above, here's the result I get:
Name ct IDs
Mike 3 1,3,5
John 2 0,2
Adam 1 4
EDIT: DISCLAIMER
This technique will not work as intended for string fields that could possibly contain special characters (like ampersands &, less than <, greater than >, and any number of other formatting characters). As such, this technique is most beneficial for simple integer values, although can still be used for text if you are ABSOLUTELY SURE there are no special characters that would need to be escaped. As such, read the solution posted HERE to ensure these characters get properly escaped.
Here is another SQL Server method, using recursive CTE:
Link to SQLFiddle
; with MyCTE(name,ids, name_id, seq)
as(
select name, CAST( '' AS VARCHAR(8000) ), -1, 0
from Data
group by name
union all
select d.name,
CAST( ids + CASE WHEN seq = 0 THEN '' ELSE ', ' END + cast(id as varchar) AS VARCHAR(8000) ),
CAST( id AS int),
seq + 1
from MyCTE cte
join Data d
on cte.name = d.name
where d.id > cte.name_id
)
SELECT name, ids
FROM ( SELECT name, ids,
RANK() OVER ( PARTITION BY name ORDER BY seq DESC )
FROM MyCTE ) D ( name, ids, rank )
WHERE rank = 1

Postgres - How to check for an empty array

I'm using Postgres and I'm trying to write a query like this:
select count(*) from table where datasets = ARRAY[]
i.e. I want to know how many rows have an empty array for a certain column, but postgres doesn't like that:
select count(*) from super_eds where datasets = ARRAY[];
ERROR: syntax error at or near "]"
LINE 1: select count(*) from super_eds where datasets = ARRAY[];
^
The syntax should be:
SELECT
COUNT(*)
FROM
table
WHERE
datasets = '{}'
You use quotes plus curly braces to show array literals.
You can use the fact that array_upper and array_lower functions, on empty arrays return null
, so you can:
select count(*) from table where array_upper(datasets, 1) is null;
If you find this question in 2020, like I did, the correct answer is
select count(*) from table where cardinality(datasets) = 0
cardinality was added in PostgreSQL 9.4, which is ~2015
https://www.postgresql.org/docs/9.4/functions-array.html
Solution Query:
select id, name, employee_id from table where array_column = ARRAY[NULL]::array_datatype;
Example:
table_emp:
id (int)| name (character varying) | (employee_id) (uuid[])
1 | john doe | {4f1fabcd-aaaa-bbbb-cccc-f701cebfabcd, 2345a3e3-xxxx-yyyy-zzzz-f69d6e2edddd }
2 | jane doe | {NULL}
select id, name, employee_id from tab_emp where employee_id = ARRAY[NULL]::uuid[];
-------
2 | jane doe | {NULL}
SELECT COUNT(*)
FROM table
WHERE datasets = ARRAY(SELECT 1 WHERE FALSE)