Need SQL JOIN statement assistance - sql

I am creating a report that needs to list both Primary Person Id and Alternate Person ID. But it also needs to show both Primary Person IDs contact information and Alternates. Report I've created right now only lists out Primary Person ID's contact information, but shows the Alternates ID number. Can someone assist me in fixing my sql so both Primary and Alternates contact information is listed and not just the Primary's. The sql I have is below.
SELECT "ORG_ACCOUNT".ACCOUNT_NUMBER AS "Account Number",
"ORG_PERSON".ADDRESS_2 AS "Address",
"ORG_ACCOUNT".DODAAC AS "Dodaac",
"ORG_DODAAC".DRA AS "Dra",
"ORG_PERSON".EMAIL AS "Email",
"ORG_PERSON".FIRST_NAME AS "First Name",
"ORG_PERSON".LAST_NAME AS "Last Name",
"ORG_PERSON".LAST_TRAIN_DATE AS "Last Train Date",
"ORG_PERSON".MIDDLE_NAME AS "Middle Name",
"ORG_ALT_ACCOUNT_CUST".PERSON_ID AS "Alt Person Id",
"ORG_ORG".ORG_NAME AS "Org Name",
"ORG_ACCOUNT".PERSON_ID AS "Person Id",
"ORG_PERSON".PHONE_COM AS "Phone Com",
"ORG_PERSON".PHONE_DSN AS "Phone Dsn",
"ORG_PERSON".RANK AS "Rank"
FROM "ORG"."ORG_ACCOUNT" "ORG_ACCOUNT",
"ORG"."ORG_DODAAC" "ORG_DODAAC",
"ORG"."ORG_ORG" "ORG_ORG",
"ORG"."ORG_PERSON" "ORG_PERSON"
"ORG"."ORG_ALT_ACCOUNT_CUST" "ORG_ALT_ACCOUNT_CUST"
WHERE ( ( "ORG_PERSON".PERSON_ID(+) = ORG_ALT_ACCOUNT_CUST".PERSON_ID )
AND ( "ORG_ORG".ORG_ID = "ORG_ACCOUNT".ORG_ID )
AND ( "ORG_PERSON".PERSON_ID = "ORG_ACCOUNT".PERSON_ID )
AND ( "ORG_ALT_ACCOUNT_CUST".PERSON_ID = "ORG_ACCOUNT".PERSON_ID )
AND ( "ORG_DODAAC".DODAAC = "ORG_ACCOUNT".DODAAC ) )
AND ( UPPER("ORG_ACCOUNT".DODAAC) LIKE UPPER(:DODAAC)
AND "ORG_DODAAC".DRA IN ( :P_DRA_ENTRIES)
AND UPPER("ORG_ACCOUNT".DODAAC_COMMODITY) = UPPER('A') )
ORDER BY "ORG_DODAAC".DRA ASC, "ORG_ACCOUNT".ACCOUNT_NUMBER ASC, "ORG_PERSON".LAST_NAME ASC

When you want to join a table twice, like you do here with ORG_PERSON, you need to list it twice in the FROM clause (with different aliases).
SELECT ORG_ACCOUNT.ACCOUNT_NUMBER AS "Account Number",
ORG_PERSON.ADDRESS_2 AS "Address",
ORG_ACCOUNT.DODAAC AS "Dodaac",
ORG_DODAAC.DRA AS "Dra",
ORG_PERSON.EMAIL AS "Email",
ORG_PERSON.FIRST_NAME AS "First Name",
ORG_PERSON.LAST_NAME AS "Last Name",
ORG_PERSON.LAST_TRAIN_DATE AS "Last Train Date",
ORG_PERSON.MIDDLE_NAME AS "Middle Name",
ORG_ALT_ACCOUNT_CUST.PERSON_ID AS "Alt Person Id",
ORG_ORG.ORG_NAME AS "Org Name",
ORG_ACCOUNT.PERSON_ID AS "Person Id",
ORG_PERSON.PHONE_COM AS "Phone Com",
ORG_PERSON.PHONE_DSN AS "Phone Dsn",
ORG_PERSON.RANK AS "Rank",
alt_person.address_2 as "Alt Address",
alt_person.email as "Alt Email",
alt_person.first_name as "Alt First Name",
alt_person.last_name as "Alt Last Name",
alt_person.phone_com as "Alt Phone"
FROM "ORG".ORG_ACCOUNT ORG_ACCOUNT,
"ORG".ORG_DODAAC ORG_DODAAC,
"ORG".ORG_ORG ORG_ORG,
"ORG".ORG_PERSON ORG_PERSON
"ORG".ORG_ALT_ACCOUNT_CUST ORG_ALT_ACCOUNT_CUST,
"ORG".ORG_PERSON alt_person
WHERE ( ( alt_person.PERSON_ID(+) = ORG_ALT_ACCOUNT_CUST.PERSON_ID )
AND ( ORG_ORG.ORG_ID = ORG_ACCOUNT.ORG_ID )
AND ( ORG_PERSON.PERSON_ID = ORG_ACCOUNT.PERSON_ID )
AND ( ORG_ALT_ACCOUNT_CUST.PERSON_ID = ORG_ACCOUNT.PERSON_ID )
AND ( ORG_DODAAC.DODAAC = ORG_ACCOUNT.DODAAC ) )
AND ( UPPER(ORG_ACCOUNT.DODAAC) LIKE UPPER(:DODAAC)
AND ORG_DODAAC.DRA IN ( :P_DRA_ENTRIES)
AND UPPER(ORG_ACCOUNT.DODAAC_COMMODITY) = UPPER('A') )
ORDER BY ORG_DODAAC.DRA ASC, ORG_ACCOUNT.ACCOUNT_NUMBER ASC, ORG_PERSON.LAST_NAME ASC
Some style notes: I removed the double quotes from your table names and aliases because they're annoying and unnecessary. But I left your query in the old proprietary Oracle join syntax instead of ANSI joins, since I know a lot of workplaces still use it as an internal coding standard. I left my changes in lowercase so they'd be easy to see.

Related

Is there anyway in power bi to assign value to distinct count against value

I want to ask that i have a column of claims in which a claim no have different occurances but i want to assign value of 1 when claim no is distinct and it occurred first time then i assign 0 when it is repeated , so is there any method for creating calculated column for this problem
You can use Power Query to achieve your goal: Below I created some datasets, and achieved a result:
Let's say you have such data set:
Then here is all steps involved in Power Query to achieve your goal. Just Paste the code into Advanced Editor in which you can find in Home tab and Query Group:
If you clicked the Advanced Editor, You can see the full code, like this:
The Full M-Code:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjMwNDFS0lEyVIrVAfNMzYA8IxgPTc4UWQ6s0hBFpSmKnAmKnBGKKcboZsYCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Claim No" = _t, Occurances = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Claim No", Int64.Type}, {"Occurances", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Claim No"}, {{"Order", each _, type table [Claim No=nullable number, Occurances=nullable number]}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each Table.AddIndexColumn([Order],"SNo",1)),
Custom1 = Table.Combine(#"Added Custom"[Custom]),
#"Added Custom1" = Table.AddColumn(Custom1, "Distinct_Number", each if [SNo] = 1 then 1 else 0),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom1",{"SNo"}),
#"Changed Type1" = Table.TransformColumnTypes(#"Removed Columns",{{"Distinct_Number", Int64.Type}})
in
#"Changed Type1"
If we test it, It returns:

PL-SQL: ORA-00904 - Invalid Identifier - Column in Select and Pivot Clause

Have code that works to create output below, and cannot for the life of me debug the pivot to take "Tax Status" to each have their own column. I remove the "ORDER" and "GROUP" clauses and try this as a pivot, but it still yields "ORA-00904: "Tax Status": invalid identifier". Depending on what I've done it gets made at the initial select at times, others it gets angry about the pivot and if Im using single or double quotes.
Pivot Struggling With:
pivot
(
min('Total Value')
for ("Tax Status")
in ('Exempt from Taxation' as "Exempt", 'Taxable' as "Taxable", 'Tax Agreement - Operator of a Public Utility' as "Tax Agreement",
'"Assessed Person" Tax Agreement' as "Tax Agreement", 'Grant in Place of Tax' as "Grant", 'Council Tax Cancellation or Refund' as "Council Cancel/Refund")
)
Working Query that Produces Output Below:
SELECT "Team", "Tax Status", sum("Total Value") "Total Value"
FROM
(
select (A.account_roll_number) "Roll Number", ALU.DESCRIPTION "Assessor", A.account_total_property_value as "Total Value",
TaxLU.DESCRIPTION "Tax Status",
CASE
when A.assessor_id in ('ATHENDRATA', 'BRTHOMPSON', 'FTACIUNE', 'HPHILLIPS', 'JDCHU', 'JRYOUNG1', 'MHARTMANN', 'NCCHAN', 'RLEE5', 'SBERZINS') then 'Industrial'
when A.assessor_id in ('ASMTDWA','ASMTEB', 'ASMTWS', 'BBROCKLEBANK', 'CCHICHAK', 'CYMAU', 'GJONES4', 'IYPAU', 'JTGREER', 'KHOUSTON', 'LGMORRISON', 'MMCKENZIE1', 'MWALZ', 'SKUANG', 'STBAZIN', 'TKNGUYEN1', 'ASHIELDS') then 'Single Residential'
when A.assessor_id in ('BTANG', 'CMACMILLAN1', 'DGENCARELLI', 'EWU1', 'JWEHLER', 'LMDUNBAR', 'LWONG4', 'MGULOWSKA', 'RLEE1', 'SHAMMOUD', 'SLTURNER', 'YWANG') then 'Multi Residential'
when A.assessor_id in ('CMULENGA', 'EPOPOVICS', 'GFULLER', 'IMCDERMOTT', 'JERMUBE', 'JNSTEVENSON', 'JPLEPINE', 'KBUCKRY', 'KDALMHJELL', 'NPHAM1', 'PGKERSEY', 'SMSAMPLE') then 'Special Purpose and Land'
when A.assessor_id in ('ASMTHN', 'DCARSON', 'DLIDGREN', 'DMCCORD', 'EBORISENKO', 'HYAU1', 'MCTRIMBLE', 'RJTHARAKAN', 'TBJOHNSON1', 'VWONG1', 'WGIBBS', 'YYE', 'AVPETERS') then 'Office'
when A.assessor_id in ('AKEAST', 'BLTHOMPSON', 'BNELSON1', 'JCRUJI', 'JWONG1', 'KGARDINER', 'KMHAUT', 'NTNGUYEN', 'RTLUCHAK', 'SGILL3', 'THEGER1', 'TJLUDLOW', 'ZRGEIB') then 'Retail'
else 'Other'
END as "Team"
from REP_DBA.AB000_ACCOUNT A
join REP_DBA.LU_ASMT_ASSIGN_ASSESSOR ALU
on A.assessor_id = ALU.code
-- Decode the Tax Status from the LU Table
join rep_dba.LU_ASMT_ACCT_TAX_STATUS TaxLU
on TaxLU.CODE = A.account_tax_status
where A.rollyear = :rollyear
and A.account_type = 'P'
and A.account_status = 'AP'
and A.account_total_property_value is not null
ORDER BY account_total_property_value DESC
)
GROUP BY "Team", "Tax Status"
ORDER BY "Team"
Output before Pivot
You must use double quotes for the column in PIVOT as follows:
Select * from
(
SELECT "Team", "Tax Status", sum("Total Value") "Total Value"
FROM
(
select (A.account_roll_number) "Roll Number", ALU.DESCRIPTION "Assessor", A.account_total_property_value as "Total Value",
TaxLU.DESCRIPTION "Tax Status",
CASE
when A.assessor_id in ('ATHENDRATA', 'BRTHOMPSON', 'FTACIUNE', 'HPHILLIPS', 'JDCHU', 'JRYOUNG1', 'MHARTMANN', 'NCCHAN', 'RLEE5', 'SBERZINS') then 'Industrial'
when A.assessor_id in ('ASMTDWA','ASMTEB', 'ASMTWS', 'BBROCKLEBANK', 'CCHICHAK', 'CYMAU', 'GJONES4', 'IYPAU', 'JTGREER', 'KHOUSTON', 'LGMORRISON', 'MMCKENZIE1', 'MWALZ', 'SKUANG', 'STBAZIN', 'TKNGUYEN1', 'ASHIELDS') then 'Single Residential'
when A.assessor_id in ('BTANG', 'CMACMILLAN1', 'DGENCARELLI', 'EWU1', 'JWEHLER', 'LMDUNBAR', 'LWONG4', 'MGULOWSKA', 'RLEE1', 'SHAMMOUD', 'SLTURNER', 'YWANG') then 'Multi Residential'
when A.assessor_id in ('CMULENGA', 'EPOPOVICS', 'GFULLER', 'IMCDERMOTT', 'JERMUBE', 'JNSTEVENSON', 'JPLEPINE', 'KBUCKRY', 'KDALMHJELL', 'NPHAM1', 'PGKERSEY', 'SMSAMPLE') then 'Special Purpose and Land'
when A.assessor_id in ('ASMTHN', 'DCARSON', 'DLIDGREN', 'DMCCORD', 'EBORISENKO', 'HYAU1', 'MCTRIMBLE', 'RJTHARAKAN', 'TBJOHNSON1', 'VWONG1', 'WGIBBS', 'YYE', 'AVPETERS') then 'Office'
when A.assessor_id in ('AKEAST', 'BLTHOMPSON', 'BNELSON1', 'JCRUJI', 'JWONG1', 'KGARDINER', 'KMHAUT', 'NTNGUYEN', 'RTLUCHAK', 'SGILL3', 'THEGER1', 'TJLUDLOW', 'ZRGEIB') then 'Retail'
else 'Other'
END as "Team"
from REP_DBA.AB000_ACCOUNT A
join REP_DBA.LU_ASMT_ASSIGN_ASSESSOR ALU
on A.assessor_id = ALU.code
-- Decode the Tax Status from the LU Table
join rep_dba.LU_ASMT_ACCT_TAX_STATUS TaxLU
on TaxLU.CODE = A.account_tax_status
where A.rollyear = :rollyear
and A.account_type = 'P'
and A.account_status = 'AP'
and A.account_total_property_value is not null
-- ORDER BY account_total_property_value DESC -- not needed
)
GROUP BY "Team", "Tax Status"
)
pivot
(
min("Total Value") -- here
for ("Tax Status")
in ('Exempt from Taxation' as "Exempt", 'Taxable' as "Taxable",
'Tax Agreement - Operator of a Public Utility' as "Tax Agreement", -- duplicate
'"Assessed Person" Tax Agreement' as "Tax Agreement 1", -- changed alias, added 1
'Grant in Place of Tax' as "Grant", 'Council Tax Cancellation or Refund' as "Council Cancel/Refund")
)
Cheers!!

IIF Function in Access SQL

I am trying to write an IIF statement to return on certain Job Titles in my Query.
However, when I went to run my code, this column did not even get returned in the table that I created. I looked online and it seems that this is the correct syntax. Am I missing something that is causing it not to return this column?
IIF ([w.Job_Title] = "Sales Pro" OR [w.Job_Title] = "Services Pro" OR [w.Job_Title] = "Universal Pro" OR [w.Job_Title] = "Fulfillment Pro", "JobTitle", NULL),
I originally had a WHERE statement at the end of my query, but this seemed to cause my other data to not be accurate, so I thought this IIF way would be better.
Below is the Full query:
SELECT cal.FiscalYear,
cal.FiscalQuarter,
cal.FiscalMonth,
cal.FiscalWeekNumber,
Format(w.Day, "Dddd") AS DayOfWeek,
cal.Day AS CalendarDay,
w.Day,
c.SegStart,
c.SPLITNAME AS SkillName,
w.Site,
w.Campaign,
w.Manager,
w.Supervisor,
IIF ([w.Job_Title] = "Sales Pro"
OR [w.Job_Title] = "Services Pro"
OR [w.Job_Title] = "Universal Pro"
OR [w.Job_Title] = "Fulfillment Pro", "JobTitle", NULL),
w.EmployeeNumber AS SalesID,
w.ACDID,
c.CallID,
w.Employee,
c.Caller_Name AS cms_EmployeeName,
c.Answerer_Name AS cms_ProEmployeeName,
c.Answered,
c.AcwTime,
c.Agt_Released AS AgentReleased,
c.AnsHoldTime,
c.AnsLogin,
c.Calling_Pty AS CallingParty,
c.Conference,
c.ConsultTime,
c.Dialed_Num AS DialedNumber,
c.DispIVector,
c.DispSplit,
c.DispVDN,
c.Duration,
c.Disposition,
c.Held,
c.HoldABN AS AbanOnHold,
c.OrigLogin,
c.QueueTime,
c.RingTime,
c.TalkTime,
c.Transferred,
c.VDN2,
c.VDN3,
c.VDN4,
c.VDN5
FROM (t_wfm AS w
INNER JOIN t_cms AS c ON (c.CALLING_PTY = w.ACDID)
AND (Format(c.SEGSTART, "Short date") = Format(w.[Day], "Short date")))
INNER JOIN tbl_Calendar AS cal ON cal.Day = w.Day;
You haven't provided a column alias.
The column is most probably there, but with a title like Expr1 or something.
I think what you want is retrieving the actual title, not the constant "JobTitle":
IIF ([w.Job_Title] = "Sales Pro"
OR [w.Job_Title] = "Services Pro"
OR [w.Job_Title] = "Universal Pro"
OR [w.Job_Title] = "Fulfillment Pro", [w.Job_Title], NULL) AS JobTitle,
Edit
If you want to only return the rows containing these titles, the check goes into the WHERE clause. The IIf() is not needed then.
WHERE ([w.Job_Title] = "Sales Pro"
OR [w.Job_Title] = "Services Pro"
OR [w.Job_Title] = "Universal Pro"
OR [w.Job_Title] = "Fulfillment Pro")

PostgreSQL - How can I return results from multiple field IDs?

I would like to rewrite this query so I can return results from four field IDs: industry, location, phone number, SFDC contact ID.
At the bottom, you will see I commented out the other columns I would like to surface. Due to the way this is currently written, I can only show one at a time, and have to uncomment/comment accordingly. An important consideration is to write this so it shows all records available for industry, or location, or phone number, or SFDC contact ID (as opposed to only show records where data is available across the board through an implied "and").
As a bonus, the phone number value does include the type. Any way to remove that? For example: "123-456-7890|work" ...I would just want this to be "123-456-7890" but worst case, I can always remove this in Excel.
I appreciate any help with this.
select cmsuser.userid as "User ID",
cmsuser.username as "Username",
cmsuser.firstname as "First Name",
cmsuser.lastname as "Last Name",
cmsuser.email as "Email",
cmsuser.userenabled as "Enabled?",
to_char(date(to_timestamp(cmsuser.creationdate/1000)),'YYYY-MM-DD') as "Creation Date",
to_char(date(to_timestamp(cmsuser.modificationdate/1000)),'YYYY-MM-DD') as "Modification Date",
to_char(date(to_timestamp(cmsuser.lastloggedin/1000)),'YYYY-MM-DD') as "Last Logged In",
to_char(date(to_timestamp(cmsuser.lastprofileupdate/1000)),'YYYY-MM-DD') as "Last Profile Update",
---****** Industry ******
cmsuserprofile.value as "Industry"
from cmsuser, cmsuserprofile
where cmsuser.userid = cmsuserprofile.userid and cmsuserprofile.fieldid = '5011' and cmsuser.userenabled = '1';
---****** Location ******
---cmsuserprofile.value as "Location"
---from cmsuser, cmsuserprofile
---where cmsuser.userid = cmsuserprofile.userid and cmsuserprofile.fieldid = '6' and cmsuser.userenabled = '1';
---****** Phone Number ******
---cmsuserprofile.value as "Phone Number"
---from cmsuser, cmsuserprofile
---where cmsuser.userid = cmsuserprofile.userid and cmsuserprofile.fieldid = '1' and cmsuser.userenabled = '1';
---****** SFDC Contact ID ******
---cmsuserprofile.value as "SFDC Contact ID"
---from cmsuser, cmsuserprofile
---where cmsuser.userid = cmsuserprofile.userid and fieldid = '5004' and cmsuser.userenabled = '1';
select
u.userid as "User ID",
u.username as "Username",
u.firstname as "First Name",
u.lastname as "Last Name",
u.email as "Email",
u.userenabled as "Enabled?",
to_char(date(to_timestamp(u.creationdate/1000)),'YYYY-MM-DD') as "Creation Date",
to_char(date(to_timestamp(u.modificationdate/1000)),'YYYY-MM-DD') as "Modification Date",
to_char(date(to_timestamp(u.lastloggedin/1000)),'YYYY-MM-DD') as "Last Logged In",
to_char(date(to_timestamp(u.lastprofileupdate/1000)),'YYYY-MM-DD') as "Last Profile Update",
(select p.value from cmsuserprofile p where u.userid = p.userid and p.fieldid = '5011') as "Industry",
(select p.value from cmsuserprofile p where u.userid = p.userid and p.fieldid = '6') as "Location",
(select p.value from cmsuserprofile p where u.userid = p.userid and p.fieldid = '1') as "Phone Number",
(select p.value from cmsuserprofile p where u.userid = p.userid and p.fieldid = '5004') as "SFDC Contact ID"
from cmsuser u where u.userenabled = '1';

How can I query max date? (PostgreSQL)

Using PostgreSQL, I would like to be able to only see Document IDs with the latest modification time stamp. I am having difficulty getting this working and was wondering if anyone had any pointers?
Here is my current code:
SELECT cmsdw_document.document_id as "Document ID",
cmsdw_activity_meta.activity_name as "Activity Name",
cmsdw_document.title as "Title",
cmsdw_document.creation_ts as "Creation Timestamp",
cmsdw_document.modification_ts as "Modification Timestamp",
cmsdw_user.firstname as "First Name",
cmsdw_user.lastname as "Last Name",
cmsdw_container.name as "Name",
cmsdw_document_stats_fact.content_id as "Content ID",
cmsdw_document_stats_fact.views as "Views",
cmsdw_document_stats_fact.likes as "Likes",
cmsdw_document_stats_fact.bookmarks as "Bookmarks",
cmsdw_document_stats_fact.comments as "Comments",
cmsdw_document_stats_fact.shares as "Shares",
cmsdw_document_stats_fact.unique_viewers as "Unique Viewers"
FROM
public.cmsdw_document,
public.cmsdw_document_stats_fact,
public.cmsdw_container,
public.cmsdw_object,
public.cmsdw_user,
public.cmsdw_activity_fact,
public.cmsdw_activity_meta
WHERE
cmsdw_activity_fact.activity_type = cmsdw_activity_meta.activity_type AND
cmsdw_document_stats_fact.content_id = cmsdw_object.object_id AND
cmsdw_document.document_id = cmsdw_object.object_id AND
cmsdw_container.container_id = cmsdw_document.container_id AND
cmsdw_object.dw_object_id = cmsdw_activity_fact.direct_dw_object_id AND
cmsdw_object.object_type = cmsdw_activity_fact.direct_object_type AND
cmsdw_activity_fact.user_id = cmsdw_user.user_id AND
cmsdw_container.name = 'Getting Started' AND
cmsdw_object.object_type = 102 AND
cmsdw_activity_fact.activity_type = 20;
You should fix your query to have proper join syntax -- simple rule: never use commas in the from clause.
For your query, you can replace the select with with:
select distinct on (cmsdw_document.document_id) . . .
The ". . ." is the rest of your query. Then add:
order by cmsdw_document.document_id, cmsdw_document.modification_ts desc
This should give you the latest document, using a Postgres extension.