Joining two SQL queries with different variations of data - sql

I have this query which returns some data:
select
id, name, username, email, password,
first_name, last_name, usertype,
block, sendemail, registerDate, lastvisitDate,
activation, params, uuid
from
jml2_users
where
uuid in ('51840915-e570-430d-9911-7247d076f6e7', '51912193-6694-4ca5-94c9-9f31d076f6e7',
'51927ada-6370-4433-8a06-30d2d076f6e7', '51c05ad7-d1d0-4eb6-bc6b-424bd076f6e7',
'd047adf1-a6af-891e-94a2d0b225dcd1b6', '2aba38f2-d7a7-0a7a-eff2be3440e3b763')
and the other query is this
SELECT
ct.TrainingID, ct.UserID, ct.TrainingType, ct.TrainingStatus,
ct.TrainingScore, ct.TrainingDate,
dbo.fn_StripCharacters(ctt.product_type,'^a-z0-9') as product_type,
ctt.product_type as oldName
FROM
clientTraining as ct
INNER JOIN
clientTraningTypes as ctt ON ct.TrainingType = ctt.TypeID
WHERE
1=1
AND UserID IN ('51840915-e570-430d-9911-7247d076f6e7', '51927ada-6370-4433-‌​8a06-30d2d076f6e7')
AND TrainingType IN (SELECT TypeID
FROM complaincetestlinks
WHERE parent_client_id = 1039
AND isactive = 1 AND isdeleted = 0)
Both queries return different results, with userid and uuid in both tables have same data, I mean we can do a join, but the problem is: I want the second query data which are rows should be converted to columns in the new query and the data should be copied to new query with a join to the second query based on userid and uuid
I am noob at SQL and first question comes to me how do I convert the first query row data to columns and populate it with data because the first query has 5 rows. So eventually I need 5*4 = 20 columns for the new query and the data to be passed and uploaded to the new query from the second query
Not sure what I need to do here, I am lost

Here is an example of how to pivot the supplied query on product_type. I've only done some of the columns. Hopefully you can follow the example to add more.
SELECT
TrainingID,
UserID,
TrainingType,
TrainingStatus,
MAX(CASE
WHEN product_type = 'MarketLinkedCDs' THEN TrainingDate ELSE NULL
END) TrainingDate_MarketLinkedCDs,
MAX(CASE
WHEN product_type = 'StructuredNotes' THEN TrainingDate ELSE NULL
END) TrainingDate_StructuredNotes,
MAX(CASE
WHEN product_type = 'BufferedRangeAccrualNotes' THEN TrainingDate ELSE NULL
END) TrainingDate_BufferedRangeAccrualNotes,
MAX(CASE
WHEN product_type = 'MarketLinkedCDs' THEN TrainingScore ELSE NULL
END) TrainingScore_MarketLinkedCDs,
MAX(CASE
WHEN product_type = 'StructuredNotes' THEN TrainingScore ELSE NULL
END) TrainingScore_StructuredNotes,
MAX(CASE
WHEN product_type = 'BufferedRangeAccrualNotes' THEN TrainingScore ELSE NULL
END) TrainingScore_BufferedRangeAccrualNotes
FROM
(
SELECT ct.TrainingID, ct.UserID, ct.TrainingType, ct.TrainingStatus,
ct.TrainingScore,
ct.TrainingDate, dbo.fn_StripCharacters(ctt.product_type,'^a-z0-9') as product_type,
ctt.product_type as oldName FROM clientTraining as ct INNER JOIN
clientTraningTypes as ctt ON ct.TrainingType = ctt.TypeID WHERE 1=1 and
UserID in ('51840915-e570-430d-9911-7247d076f6e7',
'51927ada-6370-4433-‌​8a06-30d2d076f6e7')
and TrainingType IN (select TypeID from complaincetestlinks where
parent_client_id = 1039 and isactive = 1 and isdeleted = 0)
) F
GROUP BY
TrainingID,
UserID,
TrainingType,
TrainingStatus,

Related

Is there a way to make this run without a case statement? [duplicate]

This question already has answers here:
TSQL Pivot without aggregate function
(9 answers)
Closed 1 year ago.
I'm relatively new to coding and SQL so please bear with me.
I'm currently working on a query and I have no idea how to get the infinite loop to stop without using a case statement. When I use the case statement I get each value on its own row rather than the values all together in the combination they're supposed to be in.
Case statement SQL
select
CASE
When Attribute_id = '5024923' Then attribute_value
END Page_Name,
CASE
When Attribute_id = '5024925' Then attribute_value
END Site_Name,
CASE
When Attribute_id = '5024924' Then attribute_value
END Last_Touch_Channel,
count(distinct MASTER_CONTACT_ID) known_contact_count,
count (distinct visitor_id) total_contact_Count,
ACTION_DATE
from Adobe_Analytics_Staging
where ATTRIBUTE_ID in ('5024925','5024924','5024923')
group by ATTRIBUTE_ID, ACTION_DATE, ATTRIBUTE_VALUE
Example:
Error with Case statement:
Column A
Column B
Column C
value1
NULL
NULL
NULL
value2
NULL
NULL
NULL
value3
When in the data it is value1, value2, value3 on the same row.
So I'm trying a new avenue. I suspect the loop is because I'm linking back to the table so many times but I have limited the amount of results to the best of my ability to reduce the amount of records being sent through. Each query works and works fast individually. It's collectively that it slows down a ton.
The reason for joining to the table so many times is because I have to distinguish different types of values within one column.
Note: Not sure if it's relevant but the different values in the table correlate to a specific id number within that that table. Attribute value and attribute ID are different columns
For example in Table A the column looks like this
Column
A
B
C
I have to make it look like this:
Column 1
Column 2
Column 3
A
B
C
select
a.ATTRIBUTE_VALUE,
b.ATTRIBUTE_VALUE,
c.ATTRIBUTE_VALUE,
count(distinct aas.MASTER_CONTACT_ID) known_contact_count,
count (distinct d.visitor_id) total_contact_Count,
aas.ACTION_DATE
from Adobe_Analytics_Staging aas
left join (select ATTRIBUTE_VALUE, VISITOR_ID from Adobe_Analytics_Staging
where Attribute_id = '5024923') a on a.VISITOR_ID = aas.VISITOR_ID
left join (select ATTRIBUTE_VALUE, VISITOR_ID from Adobe_Analytics_Staging
where Attribute_id = '5024925') b on b.VISITOR_ID = aas.VISITOR_ID
left join (select ATTRIBUTE_VALUE, VISITOR_ID from Adobe_Analytics_Staging
where Attribute_id = '5024924') c on c.VISITOR_ID = aas.VISITOR_ID
inner join (select visitor_id from Adobe_Analytics_Staging
where ATTRIBUTE_ID in ('5024923','5024925','5024924')) d
on d.VISITOR_ID = aas.VISITOR_ID
--where aas.VISITOR_ID = '3438634761938550664_6795123974460253552'
group by a.ATTRIBUTE_VALUE, b.ATTRIBUTE_VALUE, c.ATTRIBUTE_VALUE, aas.ACTION_DATE
SELECT
VISITOR_ID,
MAX(CASE WHEN Attribute_id = '5024923' Then attribute_value END) Page_Name,
MAX(CASE WHEN Attribute_id = '5024925' Then attribute_value END) Site_Name,
MAX(CASE WHEN Attribute_id = '5024924' Then attribute_value END) Last_Touch_Channel,
COUNT(distinct MASTER_CONTACT_ID) known_contact_count,
COUNT(distinct visitor_id) total_contact_Count,
ACTION_DATE
FROM ContactTargeting.dbo.Adobe_Analytics_Staging
GROUP BY VISITOR_ID, ACTION_DATE
See this fiddle with some demo data

How to get the value as per type from one column and display it as multiple column in hive?

The below query will populate only check no and ac no even if there is data in rest of the column. How to populate all column from the value?
query:
select distinct * from(
select
(CASE WHEN b.dtl_typ = 'CheckNumber' THEN b.col_val END) as `Check Number`,
a.acc_id as Account_Number,
(CASE WHEN b.dtl_typ = 'AddressLine1' THEN b.col_val END) as `Address Line 1`,
(CASE WHEN b.dtl_typ = 'AddressLine2' THEN b.col_val END) as `Address Line 2`,
(CASE WHEN b.dtl_typ = 'City' THEN b.col_val END) as City,
(CASE WHEN b.dtl_typ = 'State' THEN b.col_val END) as State,
(CASE WHEN b.dtl_typ = 'Zipcode' THEN b.col_val END) as ZipCode
from
(select *from(select acc_id as acc_id, row_number() over(partition by acc_id order by booking_ts desc) rw_nbr
from TABLE1 where P_CODE = 'CheckTrnsfr' ) d where rw_nbr = 1) a
LEFT OUTER JOIN
(select acc_id, dtl_val as col_val, dtl_typ
from TABLE2 where dtl_typ in('AddressLine1','AddressLine2','City','State','Zipcode','CheckNumber')) b on b.acc_id = a.acc_id)a where
`Check Number` is not null
output:
expected output:The above picture only populate check no and a/c no and rest of the column is null even if the data is present which should not be happen. All column should populate with the available data.It is possible if i use more then one left join with where clause one by one like: dtl_typ= 'AddressLine1' left join dtl_typ='AddressLine2 and so on, but that should be a performance issue. It will hit DB multiple times.
select acc_id, dtl_val as col_val, dtl_typ from TABLE2 where dtl_typ in('AddressLine1','AddressLine2','City','State','Zipcode')
output:

counting number of times a particular level and then aggregating it the number of times in new variable

Counting number of times a particular level (in transaction data) and then aggregating it the number of times in new variable (under one row per customer)
I have 2 levels to solicitation method, phone and email. I have created 2 new columns which count the number of times phone or email happened per id. Right now I have transaction data and cant figure out how to go about it. the data is on left, what I want is on right. I am okay with both kinds of output on right side.
So far I tried this. returns error
create table d.email as
select ID, email_count
from d.emai
where email_count = (select count (*)
from d.email
group by ID
having SolicitMethod = 'Email' );
quit;
I am not sure what you really want to do, but you can fix the syntax error by making the subquery a correlated subquery:
create table d.email as
select ID, email_count
from d.emai e
where email_count = (select count(*)
from d.email e2
where e2.SolicitMethod = 'Email' and e2.id = e.id
);
I assume the reference in the first from should be d.emai.
The first output can be obtain with this query:
It groups rows by id, and then count how many rows are on each SolicitMethod
SELECT id
, SUM(CASE
WHEN SolicitMethod = 'Email' THEN 1
ELSE 0
END) count_email
, SUM(CASE
WHEN SolicitMethod = 'phone' THEN 1
ELSE 0
END) count_phone
FROM d.email
GROUP BY id
This second output query depends of your dbms and availability of analytics function:
it count on each rows the count of sollicitMethod of each group of id
SELECT id
, SUM(CASE
WHEN SolicitMethod = 'Email' THEN 1
ELSE 0
END)
OVER (partition BY id) count_email
, SUM(CASE
WHEN SolicitMethod = 'phone' THEN 1
ELSE 0
END)
OVER (partition BY id) count_phone
FROM d.email

SQL Server : do not Select all if true

I have these columns
Id Status
----------
1 pass
1 fail
2 pass
3 pass
How do I select all that only have a status of pass but if the Id has at least one fail it will not be selected as well.
If same id can have multiple passes
SELECT id
from table
WHERE status = 'pass'
and id NOT IN (SELECT id FROM table WHERE status = 'fail')
You need to use GROUP BY & HAVING clause
SELECT Id
FROM yourtable
GROUP BY Id
HAVING Sum(case when status ='pass' then 1 else 0 end) = count(status)
HAVING clause can be changed to
HAVING Count(case when status ='pass' then 1 end) = count(status)
I just hate chatty case statement, so
SELECT Id
FROM table1
GROUP BY Id
HAVING COUNT(DISTINCT [Status]) = 1 AND MIN([Status]) = 'pass'
or
SELECT Id
FROM table1
GROUP BY Id
HAVING COUNT(NULLIF([Status], 'fail')) = 1 AND COUNT(NULLIF([Status], 'pass')) = 0
The second query only works when status has two values 'pass' and 'fail'.

Pivoting and merging data from a sql query

This is My Query:
SELECT ad.Name, av.Value AS Attribute1, ctv.Value AS Attribute2
FROM AttributeDefinitions AS ad WITH (nolock)
INNER JOIN AttributeValues AS av WITH (nolock)
ON ad.AttributeDefinitionID = av.AttributeDefinitionID
INNER JOIN AttributeCategories
ON ad.AttributeCategoryID = AttributeCategories.AttributeCategoryID
LEFT OUTER JOIN CodeTableValues AS ctv WITH (nolock)
ON av.CodeTableValueID = ctv.CodeTableValueID
WHERE (AttributeCategories.Name = 'Camp') AND (av.AttributeValueGroupID = 9840)
My Result Looks Like This:
Name Attribute1 Attribute2
Childs Age: 10
Attended Camp Before?: Yes
Childs T-Shirt Size: large NULL
Allergies Description none NULL
Phone # 212-555-1212 NULL
Pickup Mary Jordan NULL
Name= Name of Attribute Column
Attribute1 = Data is from a free Form
Attribute2 = Data is from a Drop down Menu
What I would like to do is Rotate the data so that the information from column “Name” becomes the column header and I need to combine the values from attribute 1 & 2
This is what my Result Should Look Like:
*Childs Age Attended Camp Before? Childs T-Shirt Size Allergies Description Phone# Pickup*
10 yes large none 212-555-1212 Mary Jordan
In Oracle DB I am using CASE statement to convert rows into columns.
Take a look on this example:
select event_date
,sum(case when service_type = 'OCSAC_DEG' then service_count end) ocsac_deg
,sum(case when service_type = 'SMS_ONL' then service_count end) sms_onl
,sum(case when service_type = 'SMS_DEG' then service_count end) sms_deg
,sum(case when service_type = 'DATA_ONL' then service_count end) data_onl
,sum(case when service_type = 'DATA_DEG' then service_count end) data_deg
from STATS
where to_char(event_date, 'yyyymm') = to_char(add_months(sysdate,-1), 'yyyymm')
group by event_date
order by event_date desc