How do I count rows where a column value starts with a another column value ?
For example, I have table products shown below
---------------------------
id code abbreviation
---------------------------
1 AA01 AA
2 AB02 AB
3 AA03 AA
4 AA04 AB
---------------------------
I want to get the count of products whose code starts with abbreviation. A query like this
select count(*) from products where code ilike abbreviation+'%'
I am using postgresql 9.5.3
The string concatenation operator in postgresql is: ||
select count(*) from products where code like abbreviation || '%';
You can try:
select count(*) from products where code like '%'+abbreviation+'%'
But i am not sure why do you need this type of query.
Related
I have a table with two columns item_name, value where item_names looks like "abracadabra_prefix.tag_name". And I need to select rows with tag_names from a list that doesn't have a prefix.
Should be somthing like:
tag_names = ['f1', 'k500', '23_g']
SELECT * FROM table WHERE item_name IN (LIKE "%{tag_names});
input table:
item_name
value
fasdaf.f1
1
asdfe.f2
2
eywvs.24_g
2
asdfe.l500
2
asdfe.k500
2
eywvs.23_g
2
output table:
item_name
value
fasdaf.f1
1
asdfe.k500
2
eywvs.23_g
2
I have tried concatenating a string in a loop to get a query like this:
SELECT * FROM table WHERE item_name LIKE '%f1' OR item_name LIKE '%k500' OR item_name LIKE '%23_g';
But I can have from 1 to 200 tags, and with a large number of tags, this makes the query too complicated,as I understand it.
You can extract the suffix of item_name using substring with regexp and then use the any operator for comparison in the where clause.
select * from the_table
where substring (item_name from '\.(\w+)$') = any('{f1,k500,23_g}'::text[]);
SQL fiddle demo
If you intend to use the query as a parameterized one then it will be convenient to replace '{f1,k500,23_g}'::text[] with string_to_array('f1,k500,23_g', ','), i.e. pass the list of suffixes as a comma-separated string. Please note that this query will result in a sequential scan.
You can use:
UNNEST to extract tag values from your array,
CROSS JOIN to associate tag value to each row of your table
LIKE to make a comparison between your item_name and your tag
SELECT item_name, value_
FROM tab
CROSS JOIN UNNEST(ARRAY['f1', 'k500', '23_g']) AS tag
WHERE item_name LIKE '%' || tag || '%'
Output:
item_name
value_
fasdaf.f1
1
asdfe.k500
2
eywvs.23_g
2
Check the demo here.
I have one table like this.
SQL> SELECT * FROM FRUIT;
F_NAME
----------
APPLE
PPPALEP
APLEE
PPAALLEEPP
ornPpfpP
PPdhppPP
Above one is my source table and I want to below output.If i am giving 'P' in multiform like including capital and small both.
I want to count only 'P' from each row.
OUTPUT
------
F_NAME COUNT
------ -----
APPLE 2
PPPALEP 4
APLEE 1
PPAALLEEPP 4
ornPpfpP 4
PPdhppPP 6
Thanks in advance.
Oracle has the very convenient regexp_count(). So:
select f_name, regexp_count(f_name, 'P') as cnt
from fruit;
You can count the number of occurrences by replacing P with blanks and subtracting the length of the replaced string from the original string.
select f_name,length(f_name)-length(replace(f_name,'P','')) cnt
from fruit
Edit: Per OP's comment, to count both P and p, use upper or lower when replacing the character with an empty string.
select f_name,length(f_name)-length(replace(upper(f_name),'P','')) cnt
from fruit
My table structure is as follows :
id category
1 1&2&3
2 18&2&1
3 11
4 1&11
5 3&1
6 1
My Question: I need a sql query which generates the result set as follows when the user searched category is 1
id category
1 1&2&3
2 18&2&1
4 1&11
5 3&1
6 1
but i am getting all the results not the expected one
I have tried regexp and like operators but no success.
select * from mytable where category like '%1%'
select * from mytable where category regexp '([.]*)(1)(.*)'
I really dont know about regexp I just found it.
so please help me out.
For matching a list item separated by &, use:
SELECT * FROM mytable WHERE '&'||category||'&' LIKE '%&1&%';
this will match entire item (ie, only 1, not 11, ...), whether it is at list beginning, middle or end.
Lets say I have the following data in the Employee table: (nothing more)
ID FirstName LastName x
-------------------------------------------------------------------
20 John Mackenzie <A>te</A><b>wq</b><a>342</a><d>rt21</d>
21 Ted Green <A>re</A><b>es</b><1>t34w</1><4>65z</4>
22 Marcy Nate <A>ds</A><b>tf</b><3>fv 34</3><6>65aa</6>
I need to search in the X column and get highest number in <> these brackets
What sort of SELECT statement can get me, for example, the number 6 like in <6>, in the x column?
This type of query generally works on finding patterns, I consider that the <6> is at the 9th position from left.
Please note if the pattern changes the below query will not work.
SELECT A.* FROM YOURTABLE A INNER JOIN
(SELECT TOP 1 ID,Firstname,Lastname,SUBSTRING(X,LEN(X)-9,1) AS [ORDER]
FROM YOURTABLE
WHERE ISNUMERIC(SUBSTRING(X,LEN(X)-9,1))=1
ORDER BY SUBSTRING(X,LEN(X)-9,1))B
ON
A.ID=B.ID AND
A.FIRSTNAME=B.FIRSTNAME AND
A.LASTNAME=B.LASTNAME
I'm quite new into SQL and I'd like to make a SELECT statement to retrieve only the first row of a set base on a column value. I'll try to make it clearer with a table example.
Here is my table data :
chip_id | sample_id
-------------------
1 | 45
1 | 55
1 | 5986
2 | 453
2 | 12
3 | 4567
3 | 9
I'd like to have a SELECT statement that fetch the first line with chip_id=1,2,3
Like this :
chip_id | sample_id
-------------------
1 | 45 or 55 or whatever
2 | 12 or 453 ...
3 | 9 or ...
How can I do this?
Thanks
i'd probably:
set a variable =0
order your table by chip_id
read the table in row by row
if table[row]>variable, store the table[row] in a result array,increment variable
loop till done
return your result array
though depending on your DB,query and versions you'll probably get unpredictable/unreliable returns.
You can get one value using row_number():
select chip_id, sample_id
from (select chip_id, sample_id,
row_number() over (partition by chip_id order by rand()) as seqnum
) t
where seqnum = 1
This returns a random value. In SQL, tables are inherently unordered, so there is no concept of "first". You need an auto incrementing id or creation date or some way of defining "first" to get the "first".
If you have such a column, then replace rand() with the column.
Provided I understood your output, if you are using PostGreSQL 9, you can use this:
SELECT chip_id ,
string_agg(sample_id, ' or ')
FROM your_table
GROUP BY chip_id
You need to group your data with a GROUP BY query.
When you group, generally you want the max, the min, or some other values to represent your group. You can do sums, count, all kind of group operations.
For your example, you don't seem to want a specific group operation, so the query could be as simple as this one :
SELECT chip_id, MAX(sample_id)
FROM table
GROUP BY chip_id
This way you are retrieving the maximum sample_id for each of the chip_id.