how to convert numbers to character in mysql while using select query - mysql

I am trying to convert numbers to a character representation.
I have a column named salary and it stores a value, e.g. 400 for employee 1. I want to display the salary of employee 1 with a select query. But, if a salary is 200 then display the salary as *, and if salary is 400 display ** and if salary is 600 than display ***.
So each * = 200
Can any one guide me how to do this ?

If there are a limited number of options (less than maybe 10), you want a case statement - https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case.
If you want many many asterisks if someone's salary is 10,000, you could use a little logic around rpad - http://www.w3resource.com/mysql/string-functions/mysql-rpad-function.php.

This is a very trivial problem.
You have tagged it with both mysql and sql-server; these are different tools with different language variations. The answer below will work with mysql but may need some refactoring for sql-server.
Select name
, concat(salary,rpad('',floor(salary/200),'*'))
From your table
...

SQL Server:
create table #tab (
name nvarchar(100),
salary int
)
insert #tab values ('Mrs. Garrett', 100), ('Mr. Drummond', 200),
('Kimberly', 300), ('Willis', 400),
('Arnold', 500), ('Tooty', 600),
('Natalie', 700)
select name,
salary,
replicate('*', floor(salary/200))
from #tab
drop table #tab
Which produces:
name salary (No column name)
Mrs. Garrett 100
Mr. Drummond 200 *
Kimberly 300 *
Willis 400 **
Arnold 500 **
Tooty 600 ***
Natalie 700 ***
Alternatively, you could replace the replicate() with this:
case
when salary >= 600 then '***'
when salary >= 400 then '**'
when salary >= 200 then '*'
else ''
end

In MySQL you can use RPAD
SELECT RPAD('',FLOOR(salary/200), '*') AS stars
FROM table_name
And in SQL Server, you can use REPLICATE
;WITH C AS(
SELECT 200 AS salary
UNION ALL
SELECT 400 AS salary
UNION ALL
SELECT 600 AS salary
UNION ALL
SELECT 200 AS salary
UNION ALL
SELECT 200 AS salary
)
SELECT REPLICATE('*', salary/200) AS stars
,salary/200 AS salary
FROM C
Output
stars salary
* 1
** 2
*** 3
* 1
* 1

Related

Running average of employee salary

Is it possible to update the running average salary while inserting it into the table?
NAME SAL AVGSAL
ABC 10 10
ABD 20 15
ABF 60 30
In the above table while I insert NAME and SAL, the average salary should be calculated automatically including the current row, is it possible in single SQL ? ABC AVGSAL = 10/1 = 10 for ABD AVGSAL = (10+20)/2 = 15 for ABF AVGSAL = (60+20+10)/3 = 30.
Thanks
Have you tried this approach? You need to specify the value twice though:
insert into table1 select ?, (sum(t2.sal) + ?) / (count(*) + 1) from table1 t2;
For a normal insert you can refer to previous column. Sub-queries on the same table is not allowed.

Compare Highest Income Visitor from Two Columns

I have this table with certain columns.
**table_1**
device_uuid
visited_store_1
visited_store_2
income
parent
Im suppose to find which one of the stores has the highest top 10 income people.
I can think of finding the top 10 individually but how will I join it in a query to compare it and return a single store result?
with dat as (
select
'store1' name,
avg(income) avg_income,
sum(income) total_income
from table_1
where visited_store_1 = TRUE
order by income desc
limit 10
union all
select
'store2' name,
avg(income) avg_income,
sum(income) total_income
from table_1
where visited_store_2 = TRUE
order by income desc
limit 10
)
select name
from dat
order by avg_income desc
limit 1
I just don't know what metric to use for "Top 10 income people"; I used average for the final query, but the subqueries have both.
create table #temp (visitor int)
insert into #temp
select max(visitor) as visitor from shop1
union
select max(visitor) as visitor from shop2
select max(visitor) from #temp
select case when (max(a.visitor)>=max(b.visitor)) then max(a.visitor) else max(b.visitor) end from shop1 a,shop2 b

How to use SUM and COUNT in sql query

I want to add the total marks of different three table in my database and find the number of students whose marks is less than 80. So I did it this way:
SELECT
(SELECT SUM((totalmarks / 30) * 5) AS marks1 FROM marks) +
(SELECT SUM((totalmarks / 25) * 5) AS marks2 FROM marks2) +
(SELECT SUM((totalmarks / 15) * 5) AS marks3 FROM marks3) AS result
HAVING COUNT((result / 300) * 50) < 80
I am able to get the sum of the marks, but when I put HAVING COUNT condition, it shows nothing. Can someone tell me how to get the number of student using COUNT?
It shows error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'HAVING COUNT((result/300)*50)>80' at line 11 .
Appreciate if someone can help me with this.
enter image description here
You need to group your results by student:
select studID, sum(result) * 5 as result
from (
select studID, totalmarks / 30 as result from marks1
union all
select studID, totalmarks / 25 as result from marks2
union all
select studID, totalmarks / 15 as result from marks3
) as base
group by studID
having ((result / 300) * 50) < 80
NB: it is a bit strange how you divide and multiply. For example, why not the equivalent:
having result < 480
If the logic is that in marks1 the highest possible score is 30, for marks2 25 and for marks3 15, and you want to give each of the three an equal weighting, then indeed you must divide each of the totalmarks as you do.
After the multiplication with five, this would mean the result can never be more than five.
So the having test is then quite superfluous: all results will be below 480.
So maybe you wanted to see who did not have the perfect score, for which the having clause should then be:
having result < 5
Using your current query, it needs a reference table/container to assess the HAVING condition.. so, here's my suggested solution:
SELECT result
FROM (
SELECT (
SELECT SUM(( totalmarks/30 )*5) AS marks1
FROM marks
) + (
SELECT SUM(( totalmarks/25 )*5) AS marks2
FROM marks2
) + (
SELECT SUM(( totalmarks/15 )*5) AS marks3
FROM marks3
) AS `result`
) AS `derived`
HAVING COUNT((result / 300) * 50) < 80

SUM DISTINCT based off a specific column?

I am attempting to sum the balance of each customer only once. Normally I would use a SUM DISTINCT expression, however, one column is throwing it off and the row is no longer "Distinct".
For example:
Customer Number - Customer Name - Exception Type - Balance
CIF13443 - Paul - 1 - 125
CIF13452 - Ryan - 2 - 85
CIF13443 - Paul - 3 - 125
CIF13765 - Linda - 1 - 90
In this case, if I use SUM DISTINCT, Paul's balance will be summed up twice simply because he has a different exception type, where in fact I only want SSRS to sum each customer once. One way would be to SUM the "Balance" of only DISTINCT customer numbers. Possibly by grouping the Customer Number? Is that possible on SSRS? I would rather not touch the SQL Dataset.
Thanks!
Any input is appreciated.
you can use union to dustinct the duplicate line:
Query 1(Using Union):
;WITH testdata(CustomerNumber,CustomerName,ExceptionType,Balance)AS(
SELECT 'CIF13443','Paul','1',125 UNION all
SELECT 'CIF13452','Ryan ','2',85 UNION all
SELECT 'CIF13443','Paul','3',125 UNION all
SELECT 'CIF13765','Linda','1',90
)
SELECT CustomerNumber,CustomerName,Balance FROM testdata UNION SELECT NULL,NULL,NULL WHERE 1!=1
/*
SELECT CustomerNumber,CustomerName,SUM(t.Balance) AS total_balance
FROM (
SELECT CustomerNumber,CustomerName,Balance FROM testdata UNION SELECT NULL,NULL,NULL
) AS t WHERE CustomerNumber IS NOT null
GROUP BY CustomerNumber,CustomerName
*/
CustomerNumber CustomerName Balance
-------------- ------------ -----------
CIF13443 Paul 125
CIF13452 Ryan 85
CIF13765 Linda 90
Using windows function pick one line for the duplicate lines:
;WITH testdata(CustomerNumber,CustomerName,ExceptionType,Balance)AS(
SELECT 'CIF13443','Paul','1',125 UNION all
SELECT 'CIF13452','Ryan ','2',85 UNION all
SELECT 'CIF13443','Paul','3',125 UNION all
SELECT 'CIF13765','Linda','1',90
)
SELECT CustomerNumber,CustomerName,SUM(t.Balance) AS total_balance
FROM (
SELECT CustomerNumber,CustomerName,Balance,ROW_NUMBER()OVER(PARTITION BY CustomerNumber,CustomerName,Balance ORDER BY testdata.ExceptionType) seq FROM testdata
) AS t WHERE t.seq=1
GROUP BY CustomerNumber,CustomerName

Cases in SQL Query?

I have a Query In MySQL
Give all managers of First Bank Corporation a 10 percent salary raise unless the salary become greater than $100000; in such cases, give only a 3 percent raise.
In my Database I have following Table on which i have to work on
Employee(emp_name, street, city)
Works(emp_name, company_name, salary)
Company(company_name, city)
Manages(emp_name, manager_name)`
I have done half part of the query, now I have no idea how to do its other part
Update Works
set Salary= salary + salary * 0.10
where company_name = 'First Bank Corporation' AND
emp_name IN (Select manager_name from Manages) AND
salary > 100000;
UPDATE ...
SET salary = CASE
WHEN salary * 1.10 > 100000
THEN salary * 1.03
ELSE salary * 1.10
END
WHERE ...
-or-
UPDATE ...
SET salary = salary * CASE
WHEN salary * 1.10 > 100000
THEN 1.03
ELSE 1.10
END
WHERE ...