Character Format in SQL - sql

I am new to SQL code writing. How do I format EmployeeID as character(9)? It is currently shown as an int. I need it as character(9) since I will be joining that field up to a different table.
SELECT ,UserID
,EmployeeID
from DASH.tblUserHierarchy

SELECT UserID,
CAST(EmployeeID AS VARCHAR(9)) EmployeeID
FROM DASH.tblUserHierarchy
This should work

Related

ORACLE APEX SQL WORKSHOP: Received ORA-00936: missing expression error on this code

INSERT INTO TRANSACTIONS (TRANSACTIONID, CUSTOMERID, EMPLOYEEID, TRANSACTIONDATE, STOREID)
VALUES (SELECT MAX(TRANSACTIONID) + 1 FROM TRANSACTIONS, SELECT CUSTOMERID FROM CUSTOMER WHERE CUSTOMERNAME = 'Julia Forbes', SELECT EMPLOYEEID FROM EMPLOYEE WHERE EMPLOYEENAME = 'Heather Manning', '04/12/2022', SELECT STOREID FROM STORE WHERE STOREADDRESS LIKE '%Paso%')
Could you tell me what I may have done wrong here? I keep on receiving the error about the missing expression even though I tested this multiple times.
If you use subqueries like that, enclose them into brackets:
INSERT INTO TRANSACTIONS (TRANSACTIONID,
CUSTOMERID,
EMPLOYEEID,
TRANSACTIONDATE,
STOREID)
VALUES ((SELECT MAX (TRANSACTIONID) + 1 FROM TRANSACTIONS),
(SELECT CUSTOMERID
FROM CUSTOMER
WHERE CUSTOMERNAME = 'Julia Forbes'),
(SELECT EMPLOYEEID
FROM EMPLOYEE
WHERE EMPLOYEENAME = 'Heather Manning'),
'04/12/2022',
(SELECT STOREID
FROM STORE
WHERE STOREADDRESS LIKE '%Paso%'))
Note that this code is wrong anyway; selecting MAX + 1 for transactionid will most certainly fail in a multi-user environment because two (or more) users will fetch the same value, but only the first one who commits will succeed - all the others will get the error as - I presume - that column represents a primary key and you can't have duplicates there.
Then, for transactiondate: '04/12/2022' is a string; you shouldn't store date values into VARCHAR2 columns. Although, I presume that transactiondate's datatype is DATE (which is correct), and you should then NOT rely on Oracle's capabilities of implicit conversion between two datatypes as it might, or might not succeed. For example, your code would fail in my database because of different NLS settings.
Therefore, either insert a
date literal: date '2022-12-04', which is always in yyyy-mm-dd format - here's yet another ambiguity - what does your value represent (04/12) - is it 4th of December or 12th of April? Can't tell, could be both
value represented by the to_date function with appropriate format model, e.g. to_date('04.12.2022', 'dd.mm.yyyy')

Will a PIVOT meet my requirements?

Please see the DDL below:
CREATE TABLE Person (PersonNo int, Name varchar, Age int,address varchar(100))
Is it possible to SELECT the data in the following format using a single query:
PersonNo Name
PersonNo Age
PersonNo Address
I would need a column to identify the type of row e.g. Name. The more I think about this the more I don't think I can do it. I am currently trying to do it with a pivot.
One option would be to use UNION ALL (just remember to convert the int to varchar):
select personno, name as value, 'Name' as type
from person
union all
select personno, CONVERT(varchar(10), age), 'Age' as type
from person
union all
select personno, address, 'Address' as type
from person
SQL Fiddle Demo
Also please note -- you should define a length for the Name field. As is, it can only contain a single character.
You are looking for an UNPIVOT, not a PIVOT
SELECT
PersonNo
,ColumnName
,ColumnValue
FROM Person t1
UNPIVOT(ColumnValue FOR ColumnName in ([Name],[Age],[Address])) t2

how to transform vertical fields in a table to horizontal result by SQL

I have a table like this:
create table t1 {
person_id int,
item_name varchar(30),
item_value varchar(100)
};
Suppose person_id+item_name is the composite key, now I have some data (5 records) in table t1 as below:
person_id ====item_name ====== item_value
1 'NAME' 'john'
1 'GENDER' 'M'
1 'DOB' '1970/02/01'
1 'M_PHONE' '1234567890'
1 'ADDRESS' 'Some Addresses unknown'
Now I want to use SQL (or combing store procedure/function or whatever) to query the above result (1 result set) become:
NAME==GENDER==DOB========M_PHONE=======ADDRESS===============
1 M 1970/02/01 1234567890 Some Addresses unknown
How should I do ?
Thank you for your help.
Regardless of the database you are using, the concept of what you are trying to achieve is called "Pivot Table".
Here's an example for mysql:
http://en.wikibooks.org/wiki/MySQL/Pivot_table
Some databases have builtin features for that, see the links below.
SQLServer:
http://msdn.microsoft.com/de-de/library/ms177410.aspx
Oracle:
http://www.dba-oracle.com/t_pivot_examples.htm
You can always create a pivot by hand. Just select all the aggregations in a result set and then select from that result set. Note, in your case, you can put all the names into one column using concat (i think that's group_concat in mysql), since you cannot know how many names are related to a person_id.
Finally, I found the solution in PostgreSQL:
select * from crosstab ('select person_id, item_name, item_value from t1 where person_id = 1 ')
as virtual_table ( person_id integer, name varchar, gender varchar, dob varchar, m_phone varchar, address varchar)
Also need to install the crosstab function on Postgres. See more: http://www.postgresql.org/docs/8.3/static/tablefunc.html

Retrieve distinct SQL query results for one column and not the other column

I have a table that has the following format for the data. All I want is just one code and phone number. It does not matter which phone number I get, all I need it one phone number.
Code phoneNumber
1000009 (123)752-0108
1000257 (456)718-1229
1000257 (789)750-1057
1000259 (000)000-0001 1000259 (111)453-0522
1000259 (222)460-8947 1000270 (333)528-6468 1000276 (444)384-5571
The results I need would look like:
Code phoneNumber
1000009 (123)752-0108
1000257 (456)718-1229
1000259 (000)000-0001
1000270 (333)528-6468
1000276 (444)384-5571
Any help with the SQL query would be appreciated. Thank you
If any of the phoneNumbers for a given code is sufficient, you can use a GROUP BY with any of the aggregating functions to accomplish just that
This example uses the MAX aggregating function.
SELECT Code
, PhoneNumber = MAX(phoneNumber)
FROM Table
GROUP BY
Code
WITH cteRowNum AS (
SLEECT Code, phoneNumber,
ROW_NUMBER() OVER(PARTITION BY Code ORDER BY phoneNumber) AS RowNum
FROM YourTable
)
SELECT Code, phoneNumber
FROM cteRowNum
WHERE RowNum = 1;

Higher Query result with the DISTINCT Keyword?

Say I have a table with 100,000 User IDs (UserID is an int).
When I run a query like
SELECT COUNT(Distinct User ID) from tableUserID
the result I get is HIGHER than the result from the following statement:
SELECT COUNT(User ID) from tableUserID
I thought Distinct implied unique, which would mean a lower result. What would cause this discrepancy and how would I identify those user IDs that don't show up in the 2nd query?
Thanks
**
UPDATE - 11:14 am est
**
Hi All
I sincerely apologize as I should've taken the trouble to reproduce this in my local environment. But I just wanted to see if there was a general consensus about this. Here are the full details:
The query is a result of an inner join between 2 tables.
One has this information:
TABLE ACTIVITY (NO PRIMARY KEY)
UserID int (not Nullable)
JoinDate datetime
Status tinyint
LeaveDate datetime
SentAutoMessage tinyint
SectionDetails varchar
And here is the second table:
TABLE USER_INFO (CLUSTERED PRIMARY KEY)
UserID int (not Nullable)
UserName varchar
UserActive int
CreatedOn datetime
DisabledOn datetime
The tables are joined on UserID and the UserID being selected in the original 2 queries is the one from the TABLE ACTIVITY.
Hope this clarifies the question.
This is not technically an answer, but since I took time to analyze this, I might as well post it (although I have the risk of being down voted).
There was no way I could reproduce the described behavior.
This is the scenario:
declare #table table ([user id] int)
insert into #table values
(1),(1),(1),(1),(1),(1),(1),(2),(2),(2),(2),(2),(2),(null),(null)
And here are some queries and their results:
SELECT COUNT(User ID) FROM #table --error: this does not run
SELECT COUNT(dsitinct User ID) FROM #table --error: this does not run
SELECT COUNT([User ID]) FROM #table --result: 13 (nulls not counted)
SELECT COUNT(distinct [User ID]) FROM #table --result: 2 (nulls not counted)
And something interesting:
SELECT user --result: 'dbo' in my sandbox DB
SELECT count(user) from #table --result: 15 (nulls are counted because user value
is not null)
SELECT count(distinct user) from #table --result: 1 (user is the same
value always)
I find it very odd that you are able to run the queries exactly how you described. You'd have to let us know the table structure and the data to get further help.
how would I identify those user IDs that don't show up in the 2nd query
Try this query
SELECT UserID from tableUserID Where UserID not in (SELECT Distinct User ID from tableUserID)
I think there will be no row.
Edit:
User is a reserved keyword. Do you mean UserID in your requests ?
Ray : Yes
I tried to reproduce the problem in my environment and my conclusion is that given the conditions you described, the result from the first query can not be higher than the second one. Even if there would be NULL's, that just won't happen.
Did you run the query #Jean-Charles sugested?
I'm very intrigued with this, please let us know what turns out to be the problem.