SQL query to extract a number and its decimal variations [closed] - sql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have column with all kinds of numbers, I am specifically trying to extract numbers that have either
555
or
555.xx
or
555.x
The output should look like this
555
555.1
555.5
555.9
555.58
555.22
.
.
IE I need an sql query that will return the rows that have just the number 555 with any decimal fraction from my column of arbitrary numbers.

You can try LIKE statement
WHERE Col LIKE '555.%'
OR Col = '555'

As a fast approach I would do
CAST((ValueOfTable * 100.00) AS DECIMAL(18, 2))
my table name is Diagnosis and the column name is code, where should I
add the table name and column name in this code ?
In your situation:
SELECT
CAST((code * 100.00) AS DECIMAL(18, 2))
FROM Diagnosis ;
I'm expecting this to be an integer. You can find out executing:
\d Diagnosis ;
one of the output lines should look similar to
(...)
code | integer |
(...)

Assuming the column contains numbers (not as string/varchar), search for "number>=555 and number<556". This would give you 555, 555.01... etc.

If the CODE column is a varchar (which I understand it to be from your comments, but you might want clarify that in the question body itself), and can/does contain values that are not numbers, then you have to be very careful about using functions which only accept a number.
With this sample data, you can see that having one value that can't be cast to a number will cause the whole query to error out.
select * from diagnosis order by code;
CODE
-----------
555
555.0
555.43
555.99
Not a Num
(5 rows)
select code + 1 from diagnosis;
ERROR: pg_atoi: error in "Not a Num": can't parse "Not a Num"
The usual solution to this is to either match the column value via regular expression, or use a function to test whether or now the value in each row is a number.
Here are two solutions, each of which depends on a function that is provided with Netezza, but not necessarily installed by default. Your administrator can install these for you.
The first uses the regexp_instr from the SQL Extension Toolkit. Here you use a regular expression to match the values you want without having to do an actual CAST (implicit or explicit) to a numeric.
SELECT code FROM diagnosis
WHERE regexp_instr(code, '^555(\.\d+)?$') > 0;
CODE
--------
555
555.0
555.43
555.99
(4 rows)
The second solution, which is a bit more involved, uses the isnumeric() UDF provided as part of the Netezza InDatabase Analytics package (in the /nz/extensions/nz/nzlua/examples directory when installed), to test whether the CODE column is a numeric before casting CODE as a numeric.
SELECT code
FROM (
SELECT code
FROM diagnosis
WHERE isnumber(code)
)
foo
WHERE floor(code::NUMERIC(38,2)) = 555;
CODE
--------
555
555.0
555.43
555.99
(4 rows)
Both of these functions are included with Netezza, but both require installation by your administrator before you can use them. In each case this is a simple task for the administrator, although they may not be aware of their availability.

Related

I want to collect duplicated values in SQL and convert them to a number [duplicate]

This question already has answers here:
How to use count and group by at the same select statement
(11 answers)
Closed 6 months ago.
I want to count a certain value in a column and output it as a number.
Here is an example:
id
job
1
police
2
police
3
ambulance
Now I want to count the value "police" in the "job" column and make the result in a number, so because there are two entries with "police" in the column it would be as output the number two. With the value "ambulance" it is only one entry so the result would be 1.
Can anyone tell me how to write this as code?
I have now searched a lot on the Internet and tried myself but I have found nothing that worked.
You're saying you want to count how many of each type of job there is, right?
SELECT COUNT(*), job
FROM tablename
GROUP BY job

SQL Server: DISTINCT with joins [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I want to print total number of orders of each state year-wise. But this is printing multiple states and not distinct.
SELECT DISTINCT
customer_state,
COUNT(*),
YEAR(order_purchase_timestamp) AS year
FROM
olist_orders_dataset
JOIN
olist_customers_dataset ON olist_orders_dataset.customer_id = olist_customers_dataset.customer_id
GROUP BY
YEAR(order_purchase_timestamp), customer_state
I am getting this output:
State
Year
Num_orders
AC
2020
123
AC
2020
1234
AC
2019
234
Here is the Required Output:
State
Year
Num_orders
AC
2020
19995
CA
2020
188891
AL
2019
11999
Firstly, I don't think it should be necessary to point out that your "output" doesn't match your query. Different column order and names. And somehow 2 rows for CA (123 and 1234) become 1 row (19995)? Math isn't that difficult. Simple oversights of that nature suggest a lack of effort.
Your output suggests that the two values you see as "AC" are not actually the same. Typically this means there is a trailing character that is not displayable (e.g., tab or linefeed). If that is the case, then you must first "fix" your data and then fix the process that is populating your table.
To verify that this is the problem, you can convert the column to varbinary to see the hex values stored in it. Example:
select customer_state, cast(customer_state as varbinary(20)) as bin_state, count(*)
from #tbl
where customer_state like 'AC%'
group by customer_state order by customer_state
;
fiddle to demonstrate. If my guess is correct, then there is an important lesson to learn. Stop throwing code into a query to fix a problem without understanding the cause.
And one last note. Aggregation tends to produce rows in some order. That is an artifact of the execution plans. If the order of rows in your resultset matters (and it usually does), the query MUST have an ORDER BY clause. That applies to every query - not just those using aggregation.

sql: select query for values separated by commas in different orders [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a table which has a column with values which are separated by commas.
For example the Column has following values:
index Column
1 X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,T,W,O
2 Y,Z,G,H,I,J,K,L,M,T,E,W,O
3 X,Y,Z,F,G,H,I,L,M,T,W,O,A,B,C,D,E,J,K
4 A,Z,B,X,Y
5 X,Y,A,Z,B
I want to print data of the Column which has X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,T,W,O only so that can be index number 1 as well as 3 as they have the same values just in different order. Cant search for all values manually because if the requirement to search the query changes to say X,Y,A,Z,B only then it has to be index number 4 and 5.
How do I do that?. Thanks!
Just explicitly search for the values
SELECT *
FROM Table
WHERE Column IN ('X,Y', 'Y,X')
If you have leading or lagging spaces you can substitute spaces for a blank string to ensure exact matches can be found. Also, if your column varies from upper to lower case you can use UPPER to convert. Combining both of these should ensure you get a match
you can use a like('%X%') clause twice to filter for this.
your condition should be in this format;
{col} like ('%X%') and {col} like('%Y%')

How to use Sum() function with condition? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have an Access database. There is a table named cost with bottom value:
reson Cost Type
------------ ------ ------
A1 2500 1
A1 6500 1
A2 95000 2
A3 2500 1
A1 6500 1
A4 50000 2
Now I want a query that calculate sum of all cost filed where type = 2 and sum of cost filed where type = 1 and substract the first value from the second value.
For example, the above pic calculate final result:
Sum of Type 2 = 145000
Sum of Type 1 = 18000
-------------------------
Final Result = 127000
My Sql Code
select iif(type = 2, sum(cost), -sum(cost)) As col1 from cost group by type
First off, I'm sorry you have to deal with such obnoxious hostility when asking your question here. You asked your question perfectly fine, laying out your table structure, and your desired result. It's understandable that you are new to queries and need help creating them. Not every answer requires code, and not every person knows where to start.
Here is your answer:
Step 1
Make sure you have your table created with the data you provided
Step 2
Create a new query named qySumType1. Build it like this, so it sums everything of type=1. make sure to click the totals button.
Step 3
Create another query, name this one qySumType2. This query should sum everything of type=2.
Step 4
Now create another query called "Final". Add both of your previous queries to it. Now create an expression in the last column to calculate the difference between the 2 numbers. Just like this.
And there you have it. Now just run the Final query anytime you want to get the difference.
Hope this helps! I can't tell you how many times I've started learning something new and relied on a community to help me get started. Always just try your best and wait for a decent answer to your question. Good luck!
Change T1 to the name of your table.
SELECT Sum(T.Type1) AS Type1, Sum(T.Type2) AS Type2, Sum(T.Type2) - Sum(T.Type1) AS DIFF
FROM
(
SELECT Sum(T1.Cost) AS Type1, 0 AS Type2
FROM T1
WHERE (((T1.Type)=1))
UNION
SELECT 0 AS Type1, Sum(T1.Cost) AS Type2
FROM T1
WHERE (((T1.Type)=2))
) AS T;
Type1 | Type2 | DIFF
18000 | 145000 | 127000

Add Zeros to a product number in SQL [duplicate]

This question already has answers here:
Pad a string with leading zeros so it's 3 characters long in SQL Server 2008
(18 answers)
Closed 8 years ago.
I have two tables with product numbers. They both are limited to 12 characters (varchar(12)). One of them (product A) has a number structure like this:
Product No:
2345
568
89
And product B has the same exact numbers but with zeros to fill the 12 characters missing. It is something like this:
Product No:
000000002345
000000000568
000000000089
I just want to modify product A table to add the zeros at the beginning of the sequence. I had an idea with REPLACE() function but to add the zeros I might need another function. Thanks for reading and sorry for the time.
Try this, you can use this statement
RIGHT('000000000000'+ISNULL(ProductNo,''),12)
This should do it:
UPDATE tblA
SET ProductNo = REPLICATE('0', 12 - LEN(ProductNo)) + ProductNo
I just want to modify product A table to add the zeros at the beginning of the sequence.
Big hairy question for you: Are you absolutely certain that you want to store these values in the table with leading zeros, or just be able to display it as-needed with leading zeros?
Reason I ask is because the varchar(12) implies 13 bytes in memory, where an int only takes 4, which will make a big difference if this column participates in indexes and foreign key relationships with other tables.