Adding an additional Inner join with mutiple tables SQL - sql

I'm wondering how to inner join customer name-(CUSTNAM) from table rm001 to this query & have it added to my SSRS Report. Could use help adding this. Thanks
I've tried adding after the "from" saleslineitems as an "and" but it broke the SSRS report.
use n
select distinct a.[SOP Number]
--, [Item Number]
, a.[Customer Number], a.[Created Date from Sales Transaction], a.[Primary Shipto Address Code from Sales Line Item]
, a.[City from Sales Transaction],
,c.city
,case
when b.CITY <> c.city then 'Cities Do Not Match'
when c.city = '' then 'Cities do not Match'
when isnull(c.city,'1') = '1' then 'Cities Do Not Match'
else ''
end as [validate cities]
,b.USERDEF1 as GP_F
, c.f_number as EZ_F
,case
when b.USERDEF1 <> c.f_number then 'Fs do not Match'
when b.USERDEF1 = '' then 'No F in GP'
else ''
end as [validate Fs]
, c.f_expiration
,case
when c.f_expiration <= getdate() then ' F EXPIRED '
when c.f_expiration <= DATEADD(d,15,getDate()) then 'F expiring soon'
--when c.f_expiration >= dateAdd(d,61,getdate()) then 'valid F Expiration'
else ''
end as [valid f date]
--,( select top(1) c.f_number from NBS_BoundBook..contacts where c.f_number = b.userdef1 order by c.uid desc )
--, a.*
from SalesLineItems a
inner join rm00102 b on a.[customer number] = b.CUSTNMBR and a.[Primary Shipto Address Code from Sales Line Item] = b.ADRSCODE
left join NBS_BoundBook..contacts c on Replace(Replace(ltrim(rtrim(b.USERDEF1)),CHAR(10),''),CHAR(13),'') =
( select top(1) Replace(Replace(ltrim(rtrim(c.f_number)),CHAR(10),''),CHAR(13),'') from NBS_BoundBook..contacts
where Replace(Replace(ltrim(rtrim(c.f_number)),CHAR(10),''),CHAR(13),'') = Replace(Replace(ltrim(rtrim(b.USERDEF1)),CHAR(10),''),CHAR(13),'')
and c.city= b.CITY order by c.uid desc )
where [sop type] = 'Order'
and [Created Date from Sales Transaction] >= dateAdd(d,-3, getDate())
and [Item Tracking Option] in ( 'Serial Numbers' )
order by a.[Customer Number]

Something like this should work:
.....
FROM SalesLineItems a
INNER JOIN rm00102 b
ON a.[customer number] = b.CUSTNMBR
AND a.[Primary Shipto Address Code from Sales Line Item] = b.ADRSCODE
INNER JOIN rm001 cust
ON cust.[customer number] = a.[customer number]
LEFT JOIN NBS_BoundBook..contacts c
....

Related

How do I list the count of occurrences using the over() function, but only display the occurrences that are listed in the result 3 or more times?

How do I list the amount of times each account number has occurred if I only want to see the ones that have occurred 3 times or more?
I'm using a window OVER() function to get the number of times the account number is listed.
SELECT a.ACCOUNTNUMBER AS [Account Number]
, CONCAT(n.FIRST, ' ', n.MIDDLE, ' ', n.LAST) AS [Member Name]
, l.id AS [Loan ID]
, COUNT(a.ACCOUNTNUMBER)
OVER(partition by a.ACCOUNTNUMBER) as [Number of
Tracking Record]
, n.EMAIL AS [Email]
, n.HOMEPHONE AS [Phone Number]
FROM dbo.account a
INNER JOIN dbo.LOAN l
ON a.ACCOUNTNUMBER = l.PARENTACCOUNT
INNER JOIN dbo.LOANTRACKING lt
ON l.PARENTACCOUNT = lt.PARENTACCOUNT
AND l.ID = lt.ID
INNER JOIN dbo.NAME n
ON a.ACCOUNTNUMBER = n.PARENTACCOUNT
WHERE lt.type = 46
AND l.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND lt.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND a.CLOSEDATE IS NULL
AND lt.EXPIREDATE IS NULL
GROUP BY a.ACCOUNTNUMBER, n.FIRST, n.MIDDLE, n.LAST, l.id, n.email,
n.HOMEPHONE
ORDER BY [Account Number]
Right now my result is giving me the number of times all of the accounts are listed in the "Number of Tracking Record" column. I want to see only the account numbers that have "3" occurrences or above.
My current result:
My Desired Result:
SELECT * -- edit to include only your relevant columnns
FROM
(
SELECT a.ACCOUNTNUMBER AS [Account Number]
, CONCAT(n.FIRST, ' ', n.MIDDLE, ' ', n.LAST) AS [Member Name]
, l.id AS [Loan ID]
, COUNT(a.ACCOUNTNUMBER)
OVER(partition by a.ACCOUNTNUMBER) as [Number of
Tracking Record]
, n.EMAIL AS [Email]
, n.HOMEPHONE AS [Phone Number]
FROM dbo.account a
INNER JOIN dbo.LOAN l
ON a.ACCOUNTNUMBER = l.PARENTACCOUNT
INNER JOIN dbo.LOANTRACKING lt
ON l.PARENTACCOUNT = lt.PARENTACCOUNT
AND l.ID = lt.ID
INNER JOIN dbo.NAME n
ON a.ACCOUNTNUMBER = n.PARENTACCOUNT
WHERE lt.type = 46
AND l.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND lt.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND a.CLOSEDATE IS NULL
AND lt.EXPIREDATE IS NULL
GROUP BY a.ACCOUNTNUMBER, n.FIRST, n.MIDDLE, n.LAST, l.id, n.email,
n.HOMEPHONE
) MyQuery
WHERE MyQuery.[Number of Tracking Record] >= 3
ORDER BY [Account Number]
I added an "outer" query around yours, using yours as a subquery, and filtered it for those with just the >=3 condition. And I moved the ORDER BY from your inside query to the outer query, as it's just used for ordering the results and not used in the computation itself.

Summing row before in a condition (SQL)

I have a spreadsheet where sales data is interspersed with other data in columns. The column headings for S always end with the sum between I(row before)+P(current row) - I(Current row). I would like the data to sum for each row only. I need to do this with SQL queries.
for example :
if the week is 201520, it will return 'X',
but if it isn't week 201520, then S(Column) = I(week 201547) + P(week 201548) - I(Week 201548)
Currently my queries is like this, but I don't get the logic in query for this case, can anybody help me?
select c.[SHIP TO CODE],Area,[Dealer/Account],
c.[PRODUCT CODE],c.Model,c.Category,c.WEEK,c.I,c.P,c.S
from(select distinct b.[SHIP TO CODE],rp.Model,rp.Category,b.[PRODUCT CODE],b.WEEK,b.QTY,
case when TYPE = 'I' then 'I' end as I,
case when TYPE = 'P' then 'P' end as P,
case when WEEK = '201550' then 'X' end as S from
(
select [SHIP TO CODE],[PRODUCT CODE],WEEK,qty,TYPE from Rekap
a
union
select [Ship-to party],Material,[Week-Ok],[1st G/I Qty],category from
SOT left join
SDate on [Tgl SAP] = [1st G/I Date]
)b
left join [Ref Prod]rp
on b.[PRODUCT CODE] = rp.ProductID
where WEEK is not null
)
c
left join [Ref Dealer]rd
on c.[SHIP TO CODE] = rd.[Ship To Code]
order by [Ship To Code],WEEK ASC
select * into #a from (
select
case when abcd.WEEK = '201520' then 'X' end as S,*
from(select abc.Area,abc.Channel,abc.[Dealer/Account],abc.[PRODUCT CODE],rp.Model,rp.Category,abc.week,abc.I,abc.P
from (select ab.[SHIP TO CODE],rd.Area,rd.Channel,rd.[Dealer/Account],ab.[PRODUCT CODE],
ab.WEEK,case when TYPE = 'I' then isnull(QTY,0) end as I,
case when TYPE = 'P' then isnull(qty,0) end as P
from(
select [SHIP TO CODE],[PRODUCT CODE],WEEK,qty,TYPE from Rekap
a
union all
select [Ship-to party],Material,[Week-Ok],[1st G/I Qty],category from
SOT left join
SDate on [Tgl SAP] = [Billing Date])
ab
left join [Ref Dealer]rd
on ab.[SHIP TO CODE] = rd.[Ship To Code]
)abc
left join
[Ref Prod]rp on rp.ProductID = abc.[PRODUCT CODE]
)abcd
--order by abcd.[Dealer/Account],abcd.WEEK
) a
select Area, Channel, [Dealer/Account], [Product Code], model, category, week,
CASE WHEN I IS NULL THEN 'P' WHEN P IS NULL THEN 'I' END type,
SUM(ISNULL(I,0)+ISNULL(p,0)) amount
into #b
from #a
where week is not null
group by area, channel,[dealer/account], [product code], model, category, week,
CASE WHEN I IS NULL THEN 'P' WHEN P IS NULL THEN 'I' END
order by week
--Grouping all, put into temp table
select Area, Channel, [Dealer/Account], [Product Code], model, category, week,
SUM(ISNULL(I,0)) I, SUM(ISNULL(p,0)) p
into #c
from #a
where week is not null
group by area, channel,[dealer/account], [product code], model, category, week
order by week
select *,(select MAX(week) from #c where a.week>#c.week
--IF NOT NEEDED
--and
--a.area=#c.area and a.channel=#c.channel and a.[dealer/account]=#c.[dealer/account] and a.[product code]=#c.[product code]
--and a.model=#c.model and a.category=#c.category
-- END OF
) lastweek
into #d
from #c a
select a.*, a.P-a.I+b.I s from #d a left join #d b on
a.area=b.area and a.channel=b.channel and a.[dealer/account]=b.[dealer/account] and a.[product code]=b.[product code]
and a.model=b.model and a.category=b.category and
a.lastweek=b.week
order by area, channel,[dealer/account], [product code], model, category, week

Comma-separated List of Results

I have a fairly basic query that essentially returns a SUM total for invoice line net, for each customer, where there was a certain discount given.
As part of this, I want to return the invoice numbers that each discount applied to, as a comma separated list.
This is essential as it's being fed into another piece of software that only accepts the data in this format.
I could format in Excel as this is where the data will end up, however I'd rather do it in the query directly.
I'm getting my head muddled trying to use the FOR XML PATH function to do this.
Below is the current query, which returns one row per Discount Group, Customer, Discount % given with the sum totals
Field for invoice number is invoice_header.ih_number
SELECT variant_discount_group.vdg_node_path AS 'Discount Group' ,
customer_detail.cd_statement_name AS 'Customer Name' ,
invoice_line_item.ili_discount_percent AS 'Discount' ,
SUM(( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_qty) AS 'Qty' ,
SUM(( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_net) AS 'Total Net'
FROM invoice_header
JOIN invoice_line_item ON invoice_line_item.ili_ih_id = invoice_header.ih_id
JOIN variant_detail ON variant_detail.vad_id = invoice_line_item.ili_vad_id
JOIN variant_setting ON variant_setting.vas_vad_id = variant_detail.vad_id
JOIN customer_detail ON customer_detail.cd_id = invoice_header.ih_cd_id
LEFT JOIN variant_discount_group ON variant_discount_group.vdg_id = variant_setting.vas_vdg_id
WHERE invoice_header.ih_datetime BETWEEN #DateFrom
AND #DateTo
AND ISNULL(variant_discount_group.vdg_node_path, '') LIKE #VDGroup
+ '%'
AND invoice_line_item.ili_discount_percent BETWEEN #DiscFrom
AND #DiscTo
GROUP BY variant_discount_group.vdg_node_path ,
customer_detail.cd_statement_name ,
invoice_line_item.ili_discount_percent
ORDER BY variant_discount_group.vdg_node_path ,
customer_detail.cd_statement_name ,
invoice_line_item.ili_discount_percent
try this
WITH cte
AS ( SELECT variant_discount_group.vdg_node_path AS [Discount Group] ,
customer_detail.cd_statement_name AS [Customer Name] ,
invoice_line_item.ili_discount_percent AS [Discount] ,
( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_qty AS [Qty] ,
( CASE WHEN invoice_header.ih_credit = 1 THEN -1
ELSE 1
END ) * invoice_line_item.ili_net AS [Total Net] ,
invoice_header.ih_number AS [invoice]
FROM invoice_header
JOIN invoice_line_item ON invoice_line_item.ili_ih_id = invoice_header.ih_id
JOIN variant_detail ON variant_detail.vad_id = invoice_line_item.ili_vad_id
JOIN variant_setting ON variant_setting.vas_vad_id = variant_detail.vad_id
JOIN customer_detail ON customer_detail.cd_id = invoice_header.ih_cd_id
LEFT JOIN variant_discount_group ON variant_discount_group.vdg_id = variant_setting.vas_vdg_id
WHERE invoice_header.ih_datetime BETWEEN #DateFrom
AND #DateTo
AND ISNULL(variant_discount_group.vdg_node_path, '') LIKE #VDGroup
+ '%'
AND invoice_line_item.ili_discount_percent BETWEEN #DiscFrom
AND
#DiscTo
)
SELECT a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount] ,
SUM(a.[Qty]) AS Qty ,
SUM(a.[Total Net]) AS [Total Net] ,
SUBSTRING(( SELECT ', ' + CONVERT(VARCHAR, b.[invoice])
FROM (SELECT DISTINCT
[invoice],
[Discount Group],
[Customer Name],
[Discount]
FROM cte) AS b
WHERE a.[Discount Group] = b.[Discount Group]
AND a.[Customer Name] = b.[Customer Name]
AND a.[Discount] = b.[Discount]
FOR
XML PATH('')
), 2, 1000) AS [List of invoices]
FROM cte AS a
GROUP BY a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount]
ORDER BY a.[Discount Group] ,
a.[Customer Name] ,
a.[Discount]
I don't know about performance issues but you could create a function returning a VARCHAR. Call that function in your select statement and as parameter give your reference for your invoicenumbers.
in the Function you would have a cursor for all rows of Invoicenumbers and iterate over it and concatenate into the return value.
This is probably quick and dirty and ressource intensive.

SSRS Reporting with Date ranges are optional

I am currently try to build report with filter that has Date range (DateTO and DateFrom). The problem is the report need to have ability for date range as optional. THe following is my current SQL. Please advise how i can modify
SELECT
PG.Name AS [Project Group],
PSG.Name AS [Project Sub Group],
P.ReferenceNumber,
P.ReferenceNumber + ' / ' + P.ProjectTitle AS [Project Description],
CASE WHEN W.Removed = 1
THEN 'Yes'
ELSE 'No'
END AS [Removed],
W.Description,
W.CommunicationStartDate,
PR.Name as [Person Responsible],
CASE WHEN W.CommunicationStartDate IS NULL
THEN 'Not Specified'
ELSE CONVERT(NVARCHAR, W.CommunicationStartDate, 103)
END AS [Deadline],
ES.Name AS [Status],
CASE WHEN W.Estimate IS NOT NULL
THEN W.Estimate
ELSE 0
END AS [Estimate]
FROM dbo.ProjectWorkplan W
INNER JOIN dbo.Project P
INNER JOIN dbo.ProjectSubGroup PSG
INNER JOIN dbo.ProjectGroup PG ON PSG.ProjectGroupId = PG.ProjectGroupId
ON P.ProjectSubGroupId = PSG.ProjectSubGroupId
ON W.ProjectId = P.ProjectId
INNER JOIN dbo.PersonResponsible PR ON W.PersonResponsibleId = PR.PersonResponsibleId
INNER JOIN dbo.ElementStatus ES ON W.ElementStatusId = ES.ElementStatusId
WHERE P.DateCompleted IS NULL AND W.Removed = 0
AND W.CommunicationStartDate BETWEEN #DateFrom AND #DateTo
AND ES.NAME in (#ActionRequired, #FollowUp, #OnHold, #UrgentAction, #Waiting,#Complete)
ORDER BY PG.Name, PSG.Name, P.ReferenceNumber, W.Removed, W.CommunicationStartDate
You can check the date parameters for NULL and use them if only both of them are valid:
AND (#DateFrom IS NULL OR #DateTo IS NULL OR W.CommunicationStartDate BETWEEN #DateFrom AND #DateTo)

CASE Statement in query

I am trying to return a bunch of values in a table without causing "duplicate" outputs. I thought a CASE statement or derived table may help? Any input would be great.
Within the column Product_code there are the following values
(AFF,E,H,PD,PDM,PDRL,PDRM etc)
Here is my SQL:
SELECT DISTINCT
[Member Id] = c.master_customer_id,
[Full Name] = c.label_name,
[First Name] = c.first_name,
[Last Name] = c.last_name,
[Email] = ISNULL(c.primary_email_address,''),
[Annual Meeting] = MAX(ca.product_code)
CASE WHEN od.product_code IN (AFF,E,H,PD,PDM,PDRL,PDRM) then ??
--[Membership Type] = od.product_code
FROM order_detail od
INNER JOIN customer c
on c.master_customer_id = od.ship_master_customer_id
and c.sub_customer_id = od.ship_sub_customer_id
and od.subsystem = 'MBR'
INNER JOIN cus_activity ca
on ca.master_customer_id = c.master_customer_id
and ca.sub_customer_id = c.sub_customer_id
and ca.subsystem = 'MTG'
and ca.activity_subcode IN ('2012AM', '2011AM')
and ca.product_code IN ('2012AM','2011AM')
INNER JOIN cus_address caddr
on caddr.master_customer_id = c.master_customer_id
and caddr.sub_customer_id = c.sub_customer_id
INNER JOIN cus_address_detail caddrd
on caddrd.cus_address_id = caddr.cus_address_id
where c.customer_class_code NOT IN ('STAFF', 'TEST_MBR')
and c.customer_status_code = 'ACTIVE'
and c.primary_email_address IS NOT NULL
and ca.master_customer_id IN (select order_detail.ship_master_customer_id
from order_detail where order_detail.subsystem = 'MBR')
and caddrd.priority_seq = 0
and caddrd.address_status_code = 'GOOD'
and od.product_code in
( 'AFF','E','H', 'PD','PDM','PDRL','PDRM','PDRU','R',
'RM','RRL','RRM','RRU','S','SM','SRL','SRM','SRU','SU','SUM','SURL','SURM','SURU' )
and od.cycle_end_date >= '01/01/2011' and od.cycle_end_date <= '12/31/2012'
GROUP BY c.master_customer_id,c.label_name,
c.FIRST_NAME,c.LAST_NAME,c.primary_email_address,od.product_code,caddr.country_descr
order by c.master_customer_id
You are looking for a Cross-Tab result (also known as a Pivot table) based on a given customer. You want all possible membership status levels as a person could be multiple levels (per your example).
With the group by on the customer ID, everything will roll-up to the member. So, if there are multiple product codes, I have applied SUM() based on each individual "product_code" you wanted to consider.
Next, to help optimize your query, I would ensure your Order_Detail has an index on
( SubSystem, Product_Code, Cycle_End_Date, ship_master_customer_id )
I've slightly rewritten to better allow myself to follow what you were getting and the criteria related to each table. Hopefully it makes sense to what you started with.
SELECT
c.master_customer_id as [Member Id],
c.label_name as [Full Name],
c.first_name as [First Name],
c.last_name as [Last Name],
ISNULL(c.primary_email_address,'') as [Email],
MAX(ca.product_code) as [Annual Meeting],
SUM( CASE WHEN od.product_code = 'AFF' then 1 else 0 end ) as Membership_AFF,
SUM( CASE WHEN od.product_code = 'E' then 1 else 0 end ) as Membership_E,
SUM( CASE WHEN od.product_code = 'H' then 1 else 0 end ) as Membership_H,
SUM( CASE WHEN od.product_code = 'PD' then 1 else 0 end ) as Membership_PD,
SUM( CASE WHEN od.product_code = 'PDM' then 1 else 0 end ) as Membership_PDM,
SUM( CASE WHEN od.product_code = 'PDRL' then 1 else 0 end ) as Membership_PDRL,
SUM( CASE WHEN od.product_code = 'PDRM' then 1 else 0 end ) as Membership_PDRM
FROM
order_detail od
INNER JOIN customer c
on od.ship_master_customer_id = c.master_customer_id
and od.ship_sub_customer_id = c.sub_customer_id
and c.customer_class_code NOT IN ('STAFF', 'TEST_MBR')
and c.customer_status_code = 'ACTIVE'
and c.primary_email_address IS NOT NULL
INNER JOIN cus_activity ca
on od.ship_master_customer_id = ca.master_customer_id
and od.ship_sub_customer_id = ca.sub_customer_id
and ca.subsystem = 'MTG'
and ca.activity_subcode IN ('2012AM', '2011AM')
and ca.product_code IN ('2012AM','2011AM')
INNER JOIN cus_address caddr
on od.ship_master_customer_id = caddr.master_customer_id
and od.ship_sub_customer_id = caddr.sub_customer_id
INNER JOIN cus_address_detail caddrd
on caddr.cus_address_id = caddrd.cus_address_id
and caddrd.priority_seq = 0
and caddrd.address_status_code = 'GOOD'
WHERE
od.subsystem = 'MBR'
and od.product_code in ( 'AFF','E','H','PD','PDM','PDRL','PDRM','PDRU',
'R','RM','RRL','RRM','RRU','S','SM','SRL',
'SRM','SRU','SU','SUM','SURL','SURM','SURU' )
and od.cycle_end_date >= '01/01/2011'
and od.cycle_end_date <= '12/31/2012'
GROUP BY
od.ship_master_customer_id,
c.label_name,
c.FIRST_NAME,
c.LAST_NAME,
c.primary_email_address,
caddr.country_descr
order by
od.ship_master_customer_id