How to combine two different SQL queries in one SQL statement? - sql

I have two tables which are:
Members
Member_id | Member_user_name | Member_account_id
and
Members_transaction
Member_id (sender) | Member_transaction_id | Member_account_id (recipient) | Amount | from_to
All columns have data but from_to is a new column added. I would like to add the username of sender or recipient into the column from_to.
I had use below SQL query to find out the sender's or recipient's username:
select member_user_name member_involved
from Members_transaction
left
join members
on members_transaction.member_account_id = members.member_account_id
I want to add the SQL query in this SQL query:
SELECT member_transaction_id
, mp.member_account_id
, m.member_user_name
, amount
, CASE
-- when the amount starts with "-" such as "-100" it means paid to recipient
WHEN amount LIKE '-%' THEN 'Paid to' + member_involved
-- else it is received from the sender
ELSE ' Received from '+ member_involved
END AS from_to
FROM members_transaction MP (nolock)
LEFT
JOIN members M (NOLOCK)
ON M.MEMBER_ID = MP.MEMBER_ID
AND M.IS_USE = 1
WHERE MP.IS_USE = 1
Since the condition is different (the ON), how can i combine the SQL query of finding sender or recipient into the below SQL query?

You can join twice with members, once for the sender name, once for the receiver name:
SELECT member_transaction_id
, mp.member_account_id
, m.member_user_name
, amount
, CASE
-- when the amount starts with "-" such as "-100" it means paid to recipient
WHEN amount LIKE '-%' THEN 'Paid to' + M2.member_user_name
-- else it is received from the sender
ELSE ' Received from '+ M.member_user_name
END AS from_to
FROM members_transaction MP (nolock)
LEFT JOIN members M (NOLOCK) ON M.MEMBER_ID = MP.MEMBER_ID AND M.IS_USE = 1
LEFT JOIN members M2 (NOLOCK) ON M2.member_account_id = MP.member_account_id AND M2.IS_USE = 1
WHERE MP.IS_USE = 1

Related

Using the results of a SQL query as parameters for a second one

Our SQL developer put together the following query to basically pull a list of any employee who has logged into our system today. This query works perfectly and will spit out a list of names. What I need to do is take the list of names it spits out and then use those in a new query to change a column on a different table for each of those names.
select distinct(t.CC_FullName) as Employee,
t.CC_Supervisor as Supervisor,
t.StaffCimID
from (
select s.*,
r.CC_FullName,
r.CC_Supervisor,
r.StaffCimID
from (
select AgentFirstName + ' ' + AgentLastName as AgentName,
Agent
from pia.dbo.Five9IntraDayExtract with(nolock)
group by AgentFirstName + ' ' + AgentLastName,
Agent
) s
inner join pia.dbo.StaffInformationNew r with(nolock)
ON CASE
WHEN s.Agent LIKE '%_manual' AND s.Agent = r.Five9Name_MTM THEN 1
WHEN s.Agent NOT LIKE '%_manual' AND s.Agent = r.Five9Name THEN 1
ELSE 0
END = 1
and r.EndDate is null
) t
where t.CC_FullName is not null
and t.StaffCimID is not null
order by t.CC_FullName, t.CC_Supervisor
so basically after that runs I get a list with three columns. I need to take the name column and basically do the following:
Update Attendance Set Seated = '1' where name = 'John Doe'
I need to do that for every result from the initial query. What's the best way to do that?
Add that to the top of your query...
Update Attendance
Set Seated = '1'
where name in
(select t.CC_FullName from (
select s.*,
r.CC_FullName,
r.CC_Supervisor,
r.StaffCimID
from (
select AgentFirstName + ' ' + AgentLastName as AgentName,
Agent
from pia.dbo.Five9IntraDayExtract with(nolock)
group by AgentFirstName + ' ' + AgentLastName,
Agent
) s
inner join pia.dbo.StaffInformationNew r with(nolock)
ON CASE
WHEN s.Agent LIKE '%_manual' AND s.Agent = r.Five9Name_MTM THEN 1
WHEN s.Agent NOT LIKE '%_manual' AND s.Agent = r.Five9Name THEN 1
ELSE 0
END = 1
and r.EndDate is null
) t
where t.CC_FullName is not null
and t.StaffCimID is not null)

How to sum a count of bookings to display total bookings for location and total value for location

I am writing a report that needs to show the number of bookings taken for a location with the total value of those bookings.
How do I sum the bookings column and show only one row for the location, that includes the columns set out in the example of expected data?
Select Statement Below:
SELECT
Locations.Description as LocationsDesc,
Locations.LocationGUID,
Venues.VenueName,
Venues.VenueGUID,
count (Bookings.BookingID) as Bookings,
Departments.DepartmentName,
Departments.DepartmentGUID,
sum(SalesTransactionDetails.NetDetailValue) as NetDetailValue,
sum(SalesTransactionDetails.DetailValue) as DetailValue,
SUM(CASE When Salestransactionlines.itemtype = 1 Then SalesTransactionDetails.NetDetailValue Else 0 End ) as RentalFee,
SUM(CASE When Salestransactionlines.itemtype = 2 Then SalesTransactionDetails.NetDetailValue Else 0 End ) as ExtraFee,
SalesTransactions.SalesTransactionGUID
FROM BookingLinesDetails
INNER JOIN Bookings ON BookingLinesDetails.BookingGUID=Bookings.BookingGUID
INNER JOIN Locations ON BookingLinesDetails.LocationGUID=Locations.LocationGUID
INNER JOIN Venues on Venues.Venueguid = Locations.Venueguid
INNER JOIN SalesTransactionDetails ON BookingLinesDetails.BookingLinesDetailGUID=SalesTransactionDetails.BookingLinesDetailGUID
INNER JOIN SalesTransactionLines ON SalesTransactionDetails.SalesTransactionLineGUID=SalesTransactionLines.SalesTransactionLineGUID
INNER JOIN SalesTransactions ON SalesTransactionLines.SalesTransactionGUID=SalesTransactions.SalesTransactionGUID
INNER JOIN Departments on Departments.DepartmentGUID = Locations.DepartmentGUID
WHERE
BookingLinesDetails.StartDateTime >= dbo.InzDateOnly(#pFromDate) and
BookingLinesDetails.StartDateTime < DateAdd(day,1,dbo.inzDateOnly(#pToDate)) and
Departments.DepartmentGUID in (Select GUID from dbo.InzSplitGUID(#DepartmentID)) and
(#IncludeAllLocationGroupsInVenues <> 0 or (#IncludeAllLocationGroupsInVenues = 0 )) and
Venues.VenueGUID in (Select GUID from dbo.InzSplitGUID(#VenueID)) and
salesTransactions.Status = 1 and -- remove cancelled
salestransactions.receiptonly = 0
GROUP BY
Locations.Description,
Locations.LocationGUID,
Venues.VenueName,
Venues.VenueGUID,
Departments.DepartmentName,
Departments.DepartmentGUID,
SalesTransactions.SalesTransactionGUID
The output is currently:
Desired output is:
LocationsDesc LocationGUID VenueGUID Bookings DepartmentName NetDetailValue DetailValue ExtraFee
Location - Deck Room 348A43F12 7DAD77BE 33 Aquatics Centre 2059.46 2162.5 0
I have attempted several versions of Count and sum. I believe I need to make the query a derived table and then select from that, but am not sure how to go about it, even if that is the answer.
Thank you in advance.

Iteration between 2 tables SQL Query

Im very new using SQL as you can see and i got a doubt about the iteration using 2 tables.
Here is the thing:
I have two tables "UsersEmails" and "Sent_Emails".
In the "UsersEmail" i have all the emails (user accounts) and in the "Sent_Emails" i have the emails sent during one period of time for example "TODAY".
So, i'd like to KNOW which email account on my "UsersEmail" table where sent TODAY and which ones werent.
I got an idea by iterating every email in my table "UsersEmail" and checking it on the table "Email_Sent" but i dont know how to do it.
I hope you guys could help me with this.
My best regards.
You gave little information about your tables however supposedly you can write this:
sent today:
select * from UsersEmail e
where exists (select 1 from Sent_Emails where userEmailID=e.ID and
TRUNC(emailDate)=TRUNC(sysdate))
not sent today:
select * from UsersEmail e
where not exists (select 1 from Sent_Emails where userEmailID=e.ID and
TRUNC(emailDate)=TRUNC(sysdate))
you actually want to track the mails sent and cannot be sent?
if i were you, i'd add a column to my table "Sent_Emails" datetime, and set send date when i mail is sent by a user,
and in that case ,
--MAILS SENT: SELECT * FROM SEND_MAILS WITH (NOLOCK) INNER JOIN USEREMAILS WITH (NOLOCK) ON SEND_MAILS.USERMAILID =
USEREMAILS.USERMAILID WHERE SEND_MAILS.SENDDATE IS NOT NULL
--MAILS NOT - SENT: SELECT * FROM SEND_MAILS WITH (NOLOCK) INNER JOIN USEREMAILS WITH (NOLOCK) ON SEND_MAILS.USERMAILID =
USEREMAILS.USERMAILID WHERE SEND_MAILS.SENDDATE IS NULL
And with this info, you can report mails-sent on daily base.
like
SELECT * FROM SEND_MAILS WITH (NOLOCK) INNER JOIN USEREMAILS WITH
(NOLOCK) ON SEND_MAILS.USERMAILID = USEREMAILS.USERMAILID WHERE
SEND_MAILS.SENDDATE = '2016-05-24'
Emails Sent today
SELECT * FROM UserEmail as E
INNER JOIN sentEmails AS s ON s.userEmailID = e.UserEmailId
WHERE s.date = YOUR_TARGET_DATE
Emails not sent today
SELECT * FROM UserEmail as E
INNER JOIN sentEmails AS s ON s.userEmailID = e.UserEmailId
WHERE s.date <> YOUR_TARGET_DATE
I like to repeat the problem to myself in English and then write the SQL. You want to compare the last email sent for a given userEmailID to the start of today. The subquery below gives you the last email sent for a given userEmailID. The case statement will be 1 for sent today and 0 for never sent or last email sent earlier than today.
SELECT E.*,
CASE WHEN MaxSentEmail > trunc_date(getdate()) THEN 1 ELSE 0 END AS SentToday
FROM UserEmail as E
LEFT JOIN (SELECT se.userEmailID,
max(se.sentEmails) AS MaxSentEmail
FROM sentEmails se
GROUP BY se.userEmailID) as se
on E.UserEmailID = se.userEmailID
ORDER BY E.UserEmailID

SQL Joining tables with 'constants'

I have a table of orders,
Invoice Location Customer Code SalesPersonEmail
------------------------------------------------------
300001 001 CUS001 ?
300002 006 CUS002 ?
And a table of email groups,
Role Email
-----------------------------------------------------
Filtered_Group Management#gmail.com;john#gmail.com
When Location = 001, SalesPersonEmail must be the Email field from Filtered_Group
SalesPersonEmail for all other locations must be "Orders#gmail.com;" + the Email for Role No_Filter_Group.
I'm currently using the following to achieve this,
SELECT i.Invoice, i.Location, i.[Customer Code],
CASE WHEN i.Location = 001
THEN f.Email
ELSE N'Orders#gmail.com;' + nf.Email as SalesPersonEmail
END
FROM Invoice i, RoleCodes f, RoleCodes nf
WHERE f.Role = N'Filtered_Group' AND nf.Role = N'No_Filter_Group'
My problem is the Role No_Filter_Group may not exist in the Role table at times, which causes the above query to return nothing.
How do I join these tables properly so if No_Filter_Group does not exist in the table, rows that have a SalesPersonEmail of Filtered_Group are still returned from the query?
Thanks
A relatively simple way is to use LEFT JOIN and put the special number 001 for your location and special role names Filtered_Group and No_Filter_Group in the join condition.
In this SQL Fiddle you can comment/uncomment one line in the schema definition to see how it works when RoleCodes has a row with No_Filter_Group and when it doesn't.
In any case, the query would return all rows from Invoice table.
SELECT
Invoice.Invoice
,Invoice.Location
,Invoice.[Customer Code]
,CASE WHEN Invoice.Location = '001'
THEN RoleCodes.Email
ELSE 'Orders#gmail.com;' + ISNULL(RoleCodes.Email, '')
END AS SalesPersonEmail
FROM
Invoice
LEFT JOIN RoleCodes ON
(Invoice.Location = '001'
AND RoleCodes.Role = 'Filtered_Group')
OR
(Invoice.Location <> '001'
AND RoleCodes.Role = 'No_Filter_Group')
Try something like this.
Note: This is just a example am not sure about the tables and column of your schema. Replace with the respective tables and columns
SELECT CASE
WHEN location = '001' THEN (SELECT TOP 1 email
FROM email_table
WHERE [role] = 'Filtered_Group')
ELSE 'Orders#gmail.com;'
END
FROM orders
If email_table table will have only one row for [role] = 'Filtered_Group' then you can remove the TOP 1 from the sub-query
Left join or an easier, albeit less efficient method would be to do a subquery in the select statement itself.
SELECT i.Invoice, i.Location, i.[Customer Code],
CASE WHEN i.Location = 001
THEN (SELECT TOP 1 f.Email FROM RoleCodes f WHERE f.Role = N'Filtered_Group')
ELSE N'Orders#gmail.com;' + ISNULL( (SELECT nf.Email as SalesPersonEmail FROM RoleCodes nf WHERE nf.Role = N'No_Filter_Group'), '')
END
FROM Invoice i
Normally you would want to join these in on each other but I'm not certain how you would do that with the schema provided.
Nested select will be run for each row, instead, you could try this :-
Select i.Invoice
,i.Location
,i.CustomerCode
,Isnull(r.Email,'Orders#gmail.com') As SalesPersonEmail
From Invoice As i With (Nolock)
Left Join
(
Select rc.Email
,'001' As Location
From RoleCodes As rc With (Nolock)
Where rc.Role = 'Filtered_Group'
) As r On i.Location = r.Location
use the following Query:
select t.Invoice,t.Location,t.[Customer Code],
case t.Location
when '001' then
t2.Email
else
'Orders#gmail.com'
end
as
Salespersonemail
from orders t
join email_groups t2 on t2.Role='Filtered_Group'

SELECT DISTINCT STATEMENT

For some reason, my query is returning dup rows. I am trying to create a SELECT DISTINCT query. Can someone please tell me what is wrong with my query?
SELECT DISTINCT
PT_AGCY_DTL.MLM_AGCY_NBR AS AgencyID
, AGENCY.ORG_NM AS Agency
, AGCY_ADDR.CTY_NM as AgencyCity
, AGCY_ADDR.ST_PRVN_CDE_CID as AgencyST
, AG_AGCY_CNTCT.AGCY_CNTCT_ID as ContactID
, AG_AGCY_CNTCT.CNTCT_DT AS ContactDt
, AG_AGCY_CNTCT.AGCY_RESULTS_TXT AS AgencyResults
, AG_AGCY_CNTCT.GEN_OVERVIEW_TXT AS GeneralOverview
, AG_AGCY_CNTCT.NB_RNWL_BUS_DISCUSSION_TXT AS NewAndRenewalBusinessDiscussions
, AG_AGCY_CNTCT.NB_RNWL_BUS_DISCUSSION_TXT AS NewAndRenewalBusinessDiscussions
, AG_AGCY_CNTCT.MKT_INTELLIGENCE_TXT AS MarketIntelligence
, AG_AGCY_CNTCT.AGCY_PERSONNEL_CHG_TXT AS AgencyPersonnelChanges
, AG_AGCY_CNTCT.MM_ISSUE_TXT AS MyMonitorIssues
, AG_AGCY_CNTCT.UW_CLM_ISSUE_TXT AS UnderwritingClaimIssues
, AG_AGCY_CNTCT.FOLLOW_UP_ITEM_TXT AS FollowUpActionItems
, AG_AGCY_CNTCT.NXT_CNTCT_DT AS NextScheduledVisitDate
, CONTACT_TYPE.CODE_NM AS ContactType
, CONVERT(VARCHAR, AG_AGCY_CNTCT.CNTCT_DT,101) + ' - ' + CONTACT_TYPE.CODE_NM AS ContactDtType
, AG_AGCY_CNTCT.CNTCT_DESC AS ContactDetails
, CASE
WHEN PRODUCER.LST_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(PRODUCER.FRST_NM)) + ' ' + LTRIM(RTRIM(PRODUCER.LST_NM)) END AS Producers
, CASE
WHEN MLM_EMPL.LST_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(MLM_EMPL.FRST_NM)) + ' ' + LTRIM(RTRIM(MLM_EMPL.LST_NM)) END AS Employees
, CASE
WHEN PROD_CAT.CODE_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(PROD_CAT.CODE_NM)) END AS ProductCategory
FROM
AG_AGCY_CNTCT
INNER JOIN PT_AGCY_DTL
ON AG_AGCY_CNTCT.AGCY_PID = PT_AGCY_DTL.PARTY_ID
INNER JOIN PT_PARTY AS AGENCY
ON AGENCY.PARTY_ID = AG_AGCY_CNTCT.AGCY_PID
LEFT OUTER JOIN PT_PARTY_ADDR AS AGCY_ADDR
ON AGCY_ADDR.PARTY_ID = AG_AGCY_CNTCT.AGCY_PID
INNER JOIN CD_CODE AS CONTACT_TYPE
ON CONTACT_TYPE.CODE_ID = AG_AGCY_CNTCT.CNTCT_TYP_CID
LEFT OUTER JOIN AG_AGCY_CNTCT_PRDCR_RLTNSHP
ON AG_AGCY_CNTCT_PRDCR_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN PT_PARTY AS PRODUCER
ON PRODUCER.PARTY_ID = AG_AGCY_CNTCT_PRDCR_RLTNSHP.PRDCR_PID
LEFT OUTER JOIN AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP
ON AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN PT_PARTY AS MLM_EMPL
ON MLM_EMPL.PARTY_ID = AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP.MLM_EMPL_PID
LEFT OUTER JOIN AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP
ON AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN CD_CODE AS PROD_CAT
ON PROD_CAT.CODE_ID = AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP.PROD_CAT_TYP_CID
AND AGCY_ADDR.ADDR_TYP_CID = '30' -- business address
AND AGCY_ADDR.REC_STS_TYP_CID = 'A' -- active
WHERE
PT_AGCY_DTL.MLM_AGCY_NBR ='4759' --#AgencyID (this is the FILTER)
ORDER BY ContactDt DESC, ContactID DESC
You don't specify, but I suspect you are under the impression that the following rows are duplicate:
t1.col1 | t1.col2 | t2.col1
--------------------------------
1 | 1 | 1
1 | 1 | 2
This is not the case. As was mentioned in the comments, DISTINCT is applied to all columns you are selecting. You can see there are two different combinations of values, hence two rows will be returned. Some people will use an aggregate function and a group by to get around this. Example:
SELECT t1.col1, t1.col2, MAX(t2.col1)
FROM table1 t1
INNER JOIN table2 t2
on t1.whatever = t2.whatever
GROUP BY t1.col1, t1.col2
This would only return the second row. If you are doing this be sure that you understand that you are excluding information in order to force the appearance of a distinct set of records.