Case Statement with 2 columns - sql

If Dr's name is SoinSo, then make column "Clinic Number Column" say "SO" instead of "06"
This is just a select statement not an actual change to the database.
Not sure how to code this in SQL to get this specific output.
This is the current output:
Dr Name Column | Clinic Number Column
---------------+---------------------
Doe 06
SoinSo 06
James 06
This is the desired Output:
Dr Name Column | Clinic Number Column
---------------+---------------------
Doe 06
SoinSo SO
James 06
I've tried this, but couldn't find any documentation online about doing a CASE statement for 2 columns:
When stf.DrName='SoInSo' then pc.ClinicNumberColumn='SO'

You can get the desired output from following (not tested):
SELECT
stf.DrName
,CASE WHEN stf.DrName='SoInSo' THEN 'SO' ELSE pc.ClinicNumberColumn END AS "CLINIC"
FROM
TABLE

Related

How can I add data from table to other in SQL?

I have 2 departments and created a new one, I want to update employee department but if that employees id equals one of id's listed in other table.
Employees
empid empname deptname
------------------------
01 john dept1
02 bill dept2
03 alex dept1
.
.
.
80 tomas dept1
New_depts_employees_id
empid
-----
02
05
45
18
20
34
78
80
55
32
If employee's id is inside the second table his depname will become 'dept3'
How can I write code make this process in SQL language (I using MS Access).
Do you want sql? You can use update and exists as follows:
Update employees
Set dept_name = 'dept3'
Where exists (select 1 from New_depts_employees_id n where n.emp_id = employees.emp_id)
Open new query constructor.
Add both tables to it.
Drag Employees.empid and drop it onto New_depts_employees_id.empid - a link occures. Not needed if the link is created automatically.
Change query type to UPDATE.
Set "Column to update" to Employees.deptname.
Set "Value to set" to 'dept3'.
Click "Execute".
You may save this query and convert static 'dept3' value to query parameter for future use from external application. Or you may open query constructor in SQL Mode and copy query text from it for external use.

identifying a calculated column and reading value from it

I have a simple table containing data of a batch of students and
their score for different years (the data may not be realistic, but it's
just an example).
Name Dept HOD Year1 Year2 Year3 Year4
Sam Science Christie 76.23 34.65 45.67 23.45
Mike Science Christie 57.987 26.98 43.98 78.34
Bonny Maths Christie 64.87 67.23 34.09 12.87
Ben English Simon 43.98 54.76 55.87 76.87
Now the requirement is, considering 2015 as point of reference, if the
user enters 2018 and wants data for Sam in Science department under
Christie's management, then the value from column Year3 (i.e.2018-2015)
is expected for all those conditions.
For example -
[case
when Name='Sam' and Dept='Science' and HOD='Christie' then Year*
when Name='Bonny' and Dept='Maths' and HOD='Christie' then Year*
when Name='Ben' and Dept='English' and HOD='Simon' then Year*
end]
I have already tried the sql -
select Value from (
select concat('Year', abs(2018-2015)) as Value from Class where
Name='Sam' and Dept='Science' and HOD='Christie')
So, when I am hardocoding Year3 in the above query instead of the formula,
it's working fine. When I separately firing computed Value, its is giving
output.
select concat('Year', abs(2018-2015) as Value from Class
But when I am integrating the two , my query is only giving Year3 as a
string. Whereas I want to pick the value for that column.
May be I am doing something wrong, I am not sure, but any suggestion is
welcome to solve this problem.
I came across a post advising use of coalesce() for dynamically calling a
column. so i tried that too -
select coalesce(Value, T.period,0) as Value from (
select concat('Year',(abs(2018-2015)))as period, Name, Dept, HOD from
Class where Name='Sam' and Dept='Science' and HOD='Christie') as T
where T.Name='Sam' and T.Dept='Science' and T.HOD='Christie'
But I am receiving error -
Error while compiling statement: FAILED: SemanticException [Error 10004]:
line 1:16 Invalid table alias or column reference 'Value': (possible
column names are: period, Name, Dept, HOD)
Is this what you want?
select (case when #year = 2016 then year1
when #year = 2017 then year2
when #year = 2018 then year3
when #year = 2019 then year4
end) as value
from class c
where hod = 'Christie'

SQL: Dynamically Transposing Column as Row in Chartio

I would love to have your help transposing this table's column into a row. I am trying to have the Project Names (column 1) each becoming their own column header with the MUVs value entered as the column value.
I have read through 20+ threads on this topic, but they are using different SQL packages and code that I am unable to use.
The ideal solution would modify this query to create the desired query output:
Current Query:
SELECT
cust_gae_account.project_name as "Project Name",
cust_be_project_usage.unique_visitor_count as "MUVs",
cust_be_project_usage.billing_period_start as "Month"
FROM
cust_be_project_usage
INNER JOIN
cust_gae_account
ON cust_gae_account.account_id = cust_be_project_usage.project_id
WHERE
cust_be_project_usage.admin_account_id = {ACCOUNT_ID}
Current Query Output:
Project Name | MUVs | Month
-----------------------------------------------------
ProjectAAAAAZ | 68000 | Jun 01, 2016
DynamicName | 3200 | Jun 01, 2016
ProjectAAAAAZ | 21000 | May 01, 2016
DynamicName | 4500 | May 01, 2016
CustomProject | 117000 | Jun 01, 2016
CustomProject | 118400 | May 01, 2016
Desired Query Output:
Project Name | CustomProject | ProjectAAAAAZ | DynamicName
-------------------------------------------------------------------
Jun 01, 2016 | 117000 | 68000 | 3200
May 01, 2016 | 118400 | 21000 | 4500
Notes:
We are using PostgreSQL via Chartio, we can only use base SQL
We cannot use custom functions sadly
Names and number of projects is dynamic, varies from 1 to 20
MUVs are always numeric, there are no duplicates
You can use crosstab https://www.postgresql.org/docs/9.1/static/tablefunc.html , but it will only work with a static list of columns. So you need a dynamic query. You need to define that query, and execute it.
EXECUTE ('SELECT * FROM crosstab(
\'SELECT
cust_be_project_usage.billing_period_start as "Month",
cust_gae_account.project_name as "Project Name",
cust_be_project_usage.unique_visitor_count as "MUVs"
FROM
cust_be_project_usage
INNER JOIN
cust_gae_account
ON cust_gae_account.account_id = cust_be_project_usage.project_id
WHERE
cust_be_project_usage.admin_account_id = {ACCOUNT_ID}\',
\'SELECT
cust_gae_account.project_name as "Project Name"
FROM
cust_be_project_usage
INNER JOIN
cust_gae_account
ON cust_gae_account.account_id = cust_be_project_usage.project_id
WHERE
cust_be_project_usage.admin_account_id = {ACCOUNT_ID}\')
AS ( "Project Name" date, ' ||
(SELECT
string_agg(cust_gae_account.project_name, ' int,')
FROM
cust_be_project_usage
INNER JOIN
cust_gae_account
ON cust_gae_account.account_id = cust_be_project_usage.project_id
WHERE
cust_be_project_usage.admin_account_id = {ACCOUNT_ID}) || ' int'
|| ' )')
I am not able to test it though. It SHOULD work, but my suspicions are that it might not, in these situations:
Concatenating to a scalar formed by a query (might need to use a variable for that one)
I might have mixed up a column somewhere
Not sure how you pass the {ACCOUNT_ID} parameter so you might need to change that too

oracle - sql query select max from each base

I'm trying to solve this query where i need to find the the top balance at each base. Balance is in one table and bases are in another table.
This is the existing query i have that returns all the results but i need to find a way to limit it to 1 top result per baseID.
SELECT o.names.name t.accounts.bidd.baseID, MAX(t.accounts.balance)
FROM order o, table(c.accounts) t
WHERE t.accounts.acctype = 'verified'
GROUP BY o.names.name, t.accounts.bidd.baseID;
accounts is a nested table.
this is the output
Name accounts.BIDD.baseID MAX(T.accounts.BALANCE)
--------------- ------------------------- ---------------------------
Jerard 010 1251.21
john 012 3122.2
susan 012 3022.2
fin 012 3022.2
dan 010 1751.21
What i want the result to display is calculate the highest balance for each baseID and only display one record for that baseID.
So the output would look only display john for baseID 012 because he has the highest.
Any pointers in the right direction would be fantastic.
I think the problem is cause of the "Name" column. since you have three names mapped to one base id(12), it is considering all three records as unique ones and grouping them individually and not together.
Try to ignore the "Name" column in select query and in the "Group-by" clause.
SELECT t.accounts.bidd.baseID, MAX(t.accounts.balance)
FROM order o, table(c.accounts) t
WHERE t.accounts.acctype = 'verified'
GROUP BY t.accounts.bidd.baseID;

Merge rows with same username in SSIS

I have data origination from Active Directory in a flat file that i need to export to SQL server using SSIS. My challenge is that I want to do all the operations in SSIS and have the data that is exported into the database as the final output. My flat file has several rows bearing the same username that need to be combined into one row, and then concatenating the data in one column as in my illustration below:
Username Office LocationID Dept
-------- ---------- ---------- -----
1. btan HQ 01 Acct
2. cvill South 04 HR
3. cvill North 02 HR
4. btan East 03 Acct
5. cvill West 05 HR
6. lkays HQ 01 Legal
My output should be as follows and it should all be done using SSIS:
Username LocationID Dept
-------- ---------- -----
1. btan 01, 03 Acct
2. cvill 04, 02, 05 HR
6. lkays 01 Legal
Any help will be very much appreciate.
I support the prior suggestions that this is a bad data model, and I also support the SQL (non SSIS) solution. However if you must follow this path despite our warnings, take a look at the SSIS Pivot operator. You'll need to concatenate the resulting columns into one column.
Something like this will get you a comma delimited list of the IDs
SELECT Username, STUFF(IDList, 1,2,'') AS LocationID, Dept
FROM TableName T OUTER APPLY
(
SELECT ', ' + LocationID [text()]
FROM TableName
WHERE UserName = T.UserName
FOR XML PATH('')
) T2(IDList)