sccm query cross apply outerapply doesnt give output - sql

iam running SQL query which has cross apply and outer apply , i need state names as complaint , non complaint and pending system restart, but data iam getting is for all assignment id , please find query
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, sn.StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
WHERE cia.AssignmentID = 2238
-- and sn.statename like '%Compliant%' or sn.statename like '%Pending system restart%'
and sn.statename like '%Compliant%' and sn.statename like '%restart%'
ORDER BY cia.AssignmentID, sc.StateCount DESC, sn.StateName
output iam getting is as follows
i need only statename as complaint , non complaint and pending restart for assignment id 2238 only but iam getting data for all assignment id
can you please help
output of query

This is because of your left join that's doesn't have any assignmentID
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
I suggest to use following query.
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, (SELECT StateName FROM v_StateNames WHERE TopicType = sc.StateType AND StateID = sc.StateID and statename like '%Compliant%' and statename like '%restart%') as StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
WHERE cia.AssignmentID = 2238
ORDER BY cia.AssignmentID, sc.StateCount DESC

Related

Use CTE in SQL to flag DUPLICATES and reference in sub-query

So I have the following CTE:
with dupeinv AS (
select * from (
select
tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (partition by tci.t_idoc ORDER BY tci.t_idoc, tci.t_idat DESC) as rn
from [ln106].[dbo].tcisli305100 tci
) as t
where t.rn = 1
)
There are duplicates in the above table ([ln106].[dbo].tcisli305100) , hence the CTE to get single values. I want to format just these values in the below query (prefixed with ---)
select 'JCI' as BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER
, cl.t_pono AS SALES_ORDER_LINE_NUMBER
, CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID
,CASE WHEN cl.t_dqua = 0 or cl.t_dqua is null THEN cl.t_amti ELSE
cl.t_amti / cl.t_dqua END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL
, cl.t_line AS AR_INVOICE_LINE_NUMBER
, cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY
--- , concat(dupeinv.t_idoc,'|',format(dupeinv.t_idat,'MMddyyyy') ---
,ci.t_ccur AS AR_INVOICE_CURRENCY
, ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di on cl.t_doc = di_t_doc
LEFT JOIN (SELECT t_orno,t_pono FROM [ln106].[dbo].ttdsls401100 WHERE t_oltp <> 1 group by t_orno,t_pono) as l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci on cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'
Query doesn't like me referencing it in the main query. Can anyone help, or suggest a better idea?
Your final query should look something like this:
WITH dupeinv AS
(SELECT *
FROM
(SELECT tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (PARTITION BY tci.t_idoc
ORDER BY tci.t_idoc,
tci.t_idat DESC) AS rn
FROM [ln106].[dbo].tcisli305100 tci) AS t
WHERE t.rn = 1 )
SELECT 'JCI' AS BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER ,
cl.t_pono AS SALES_ORDER_LINE_NUMBER ,
CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID ,
CASE
WHEN cl.t_dqua = 0
OR cl.t_dqua IS NULL THEN cl.t_amti
ELSE cl.t_amti / cl.t_dqua
END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL ,
cl.t_line AS AR_INVOICE_LINE_NUMBER ,
cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY ,
concat(dupeinv.t_idoc,
'|',
format(dupeinv.t_idat, 'MMddyyyy')) ,
ci.t_ccur AS AR_INVOICE_CURRENCY ,
ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di ON cl.t_doc = di_t_doc
LEFT JOIN
(SELECT t_orno,
t_pono
FROM [ln106].[dbo].ttdsls401100
WHERE t_oltp <> 1
GROUP BY t_orno,
t_pono) AS l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS
AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci ON cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'

How to get biggest value from 2 or more fields in a subquery

I have a table with customers that I join with a fact table with sales, based on invoices.
What I need from my report is to get in first part the biggest value of sales based on the incoming order type (1,2,3,C,D) for a customer for last year. And in the second part to get the same but for current year. What I get as result from my current query is all incoming order types with the customer revenue made for each of them. I tried with outer apply as subquery to get only the top 1 value ordered by revenue descending, but in the result I get the same - For all order types the customer revenue. Please help! I hope my explanation isn't understood only by me (happens a lot..)
use dwh01;
WITH OrderTypeUsedLY AS
(
SELECT
c.CustomerKey
,c.BranchId
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_LY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_LY]
,y.IncomingOrderTypeId as IncomingOrderType_LY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE())-1 --- Last Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId
),
--*********************************************************************************************************************************--
OrderTypeCY as(
SELECT
c.CustomerKey
,c.BranchId
,c.SalesRepKey
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_CY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_CY]
,y.IncomingOrderTypeId as IncomingOrderType_CY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE()) --- Current Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId, c.SalesRepKey
)
--*********************************************************************************************************************************--
SELECT
otly.BranchId,
rep.SalesRepId,
rep.SalesRepName,
otly.CustomerId,
otly.CustomerName,
otly.Sale_Revenue_LY,
otly.Sale_GrossMarginTotal_LY,
IncomingOrderType_LY,
otcy.Sale_Revenue_CY,
otcy.Sale_GrossMarginTotal_CY,
IncomingOrderType_CY
from OrderTypeUsedLY otly
left join OrderTypeCY otcy
on otly.CustomerKey = otcy.CustomerKey
join live.DimCustomer cus on cus.CustomerKey = otcy.CustomerKey
join live.DimSalesRep rep on rep.SalesRepKey = otcy.SalesRepKey
order by otcy.Sale_Revenue_CY desc, otly.Sale_Revenue_LY desc
,rep.SalesRepId
And here is the outer apply I tried:
outer apply (
SELECT top 1
iot.IncomingOrderTypeId,
Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
where iot.IncomingOrderTypeKey = y.IncomingOrderTypeKey
order by Sale_Revenue desc) x
In the first select ( with OrderTypeUsed_LY ) I get this:
And I get the same in the second select, but with the values for current year.
The purpose of the report is to see the difference in the incoming order type most used (most profit made with it) for a customer last year and to see if he continues to use it this year, or uses another incoming order type this year.
Again I'm sorry for the bad explanation, I'm trying my best (I understand myself very well)
Here is the expected result:
Expected Result
I marked in red the last year part and in green the current year part.
If you change the subquery to:
SELECT
iot.IncomingOrderTypeKey,
MAX(Sale_Revenue)
FROM [dwh01].[live].DimIncomingOrderType iot
GROUP BY iot.IncomingOrderTypeKey
then you can JOIN (not APPLY) directly on IncomingOrderTypeKey AND Sale_Revenue.
Try this:
USE dwh01;
DECLARE #CustomerKey varchar(6) = '157053'
, #ReportCurrencyId varchar(2) = 'LC'
, #CurrentYear int = YEAR(GETDATE())
, #TargetYear int = YEAR(GETDATE())-1
;
WITH FactsTable AS
(
SELECT
s.CustomerKey
, i.IncomingOrderTypeid
, [Sale_Revenue] = ISNULL(s.[Sale_Revenue] , 0)
, [Sale_GrossMarginTotal] = ISNULL(s.[Sale_GrossMarginTotal], 0)
, d.[Year]
FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType i on i.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where
s.CustomerKey = #CustomerKey
and s.ReportCurrencyId = #ReportCurrencyId
)
, OrderTypeTable
(
SELECT
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, c.SalesRepKey
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
FROM live.DimCustomer c
left join FactsTable y on y.CustomerKey = c.CustomerKey
group by
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, y.IncomingOrderTypeId
, c.SalesRepKey
)
SELECT
O.BranchId
, R.SalesRepId
, R.SalesRepName
, O.CustomerId
, O.CustomerName
, O.Sale_Revenue_LY
, O.Sale_GrossMarginTotal_LY
, O.IncomingOrderType_LY
, O.Sale_Revenue_CY
, O..Sale_GrossMarginTotal_CY
, O.IncomingOrderType_CY
from OrderTypeTable O
join live.DimSalesRep R on R.SalesRepKey = O.SalesRepKey
order by
O.Sale_Revenue_CY desc
, O.Sale_Revenue_LY desc
, R.SalesRepId
The solution is with using row_number() function in the inner query of the first CTE:
(
select *, row_number() over (partition by x0.CustomerKey order by x0.Sale_Revenue desc) as rn
from
(
select fs.CustomerKey, iot.IncomingOrderTypeKey,
sum(fs.Sale_Revenue) as Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
join live.FactSales fs
on iot.IncomingOrderTypeKey = fs.IncomingOrderTypeKey
join live.DimDate d
on d.DateId = fs.PostingDateKey
where d.[year] = #CurrentYear
GROUP BY fs.CustomerKey, iot.IncomingOrderTypeKey
) as x0
) as x1 on x1.CustomerKey = s.CustomerKey
The row_number() function gets only the first row from the result for each customer, and that is with the biggest sale revenue ( order by sale_revenue desc).

Display Only More Than One Unique Customer/Address Per Truck Number

Been working on a project in which a report will generated from the SQL Query. I wish to display all Shipments (based on unique automatic truck ID) which contain any combination of:
Unique Customers (based on Customer Number, more than one Customer
Number per shipment)
Unique Addresses (based on defined Address Field, more than one unique
Address per shipment)
The output should look like this when the code runs correct:
Truck Customer First Address (other addresses) City State ZIP Country
12345 C12345 567 Hummingbird Lane Detroit MI 48610 US
12345 C12345 908 Elm Street Detroit MI 48611 US
12345 C78901 219 Maple Street Lansing MI 49012 US
Here is a sample of the code I been trying to tease out this information:
WITH cte
AS (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, ads.Country
FROM
dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shipmentID = shpo.shpID
WHERE shpo.shpID = shp.shipmentID
AND ven.venCode IS NOT NULL
)
, maxadd
AS (SELECT
aa.venCode
, MAX(Multadd) AS Multadd
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY cte.shipmentID, cte.CustomerCode ORDER BY cte.shipmentID) Multadd
, cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
FROM
cte
) AS aa
GROUP BY
aa.CustomerCode
HAVING COUNT (*)>1
)
, maxshp
AS (SELECT
cc.shipmentID
, MAX(cc.Multadd) AS MultVencode
FROM (
SELECT
bb.shipmentID
, bb.CustomerCode
, ROW_NUMBER() OVER (PARTITION BY shipmentID ORDER BY CustomerCode) Multadd
FROM (SELECT DISTINCT cte.shipmentID, cte.CustomerCode FROM cte) AS bb
) AS cc
GROUP BY
cc.shipmentID
HAVING COUNT(*) > 1
)
SELECT
cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
, maxadd.Multadd AS AddOnShipID
, maxshp.MultVencode AS VenOnShipID
FROM
cte
JOIN maxadd ON maxadd.CustomerCode = cte.CustomerCode
JOIN maxshp ON maxshp.shipmentID = cte.shipmentID
WHERE
(
maxadd.Multadd <> 2
AND maxshp.MultVencode <> 1
)
ORDER BY
cte.shipmentID
, cte.CustomerCode;
This "quasi" works. I have been racking my brain as to why this still is not working. Wondering if a second set of eyes may find something I am overlooking.
SELECT * FROM (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, CASE WHEN(ads.Country LIKE 'US') THEN N'USA' ELSE 'CANADA' END AS Country
, COUNT (shp.shipmentID) OVER (PARTITION BY shipmentID ORDER BY shp.shpID) AS cntshpID
FROM dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shpID = shpo.shipmentID
WHERE shpo.shpID = shp.shipmentID
GROUP BY shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.aZip
, ads.Country) AS bb
WHERE bb.cntshpID > 1
ORDER BY shpID ASC
CTE was not the way to go, it overcomplicated something simple.

This SQL query is taking too long

This SQL query is taking too long
SELECT
s.State
, ServiceCenter
, s.LocationId
, LMG.dbo.ProperCase(LastName + ', ' + FirstName + ' (' + convert(varchar,s.ClientId) + ')') as Client
, ISNULL(ul.ContractorName, ServiceCenter) as ContractorName
, InvoiceId as InvoiceNumber
, s.ItemDescription
, s.Quantity
--, s.Revenue
--, SUM(s.Quantity) as Quantity
, SUM(s.Quantity * s.UnitPrice) as Revenue
--, SUM(s.Quantity * s.Revenue) as Total
, SUM(Quantity * lxref.Amount) as ContractorPayment
, (SELECT InvoiceAmount FROM AG1.MAMOZI.dbo.tInvoices i WHERE s.InvoiceId = i.invoiceId AND DeletedStatus IS NULL) as InvoiceAmount
, (SELECT SUM(Payment) FROM AG1.MAMOZI.dbo.tPayments p WHERE s.InvoiceId = p.invoiceId AND DeletedStatus IS NULL) as PaymentAmount
, (SELECT PaymentType FROM #PaymentTypeGuardian pt WHERE pt.ClientId = s.ClientId AND pt.InvoiceId = s.InvoiceId) as PaymentType
, ISNULL((SELECT SUM(AccountBalance) FROM [PLUSREPORT].Warehouse_LMG1.dbo.RptAccountBalance a WHERE a.CompanyId = 3 AND a.ClientId = CAST(s.ClientId as varchar(max))), 0) as AccountBalance
FROM #ServicePaymentGuardian s
INNER JOIN AG1.MAMOZI.dbo.tClient c on s.ClientId = c.ClientId
INNER JOIN DATABASESAVE.MAMO.org.LocationExtended le on s.LocationID = le.OrgDatabaseid
INNER JOIN DATABASESAVE.MAMO.jur.Location ul on le.LocationId = ul.LocationId AND ul.LocationTypeid = 2
INNER JOIN DATABASESAVE.MAMO.base.Jurisdiction uj on ul.JurisdictionId = uj.JurisdictionId AND uj.CompanyId = 3
INNER JOIN DATABASESAVE.MAMO.jur.LocationServicePaymentXref lxref on ul.LocationId = lxref.LocationId and s.ServicePaymentId = lxref.ServicePaymentId
GROUP BY
s.State
, ServiceCenter
, s.LocationId
, s.ClientId
, c.LastName
, c.FirstName
, s.InvoiceId
, s.Quantity
, s.ItemDescription
, s.ServicePaymentId
, ul.ContractorName
Order by State, ServiceCenter, InvoiceNumber, LastName, FirstName, ItemDescription
see execution plan - maybe you need to add indexes
run query without sub-queries and see how long it will take then
try to split query to smaller parts (and run it separately) to find out which part slows query down

SQL Server: select the largest order total from multiple customers with multiple orders, and there are multiple items on each order

I am really stuck on a problem and could use a little help. Here is the problem statement:
"Write the query that will show all the customers, the total of all orders, a count of orders made, the average total of each order, average number of items per order (with decimal points), the largest order total and the smallest order total for each customer. Show every customer even if a customer didn't make an order."
These are the tables:
the lovely tables
I've gotten this far, and I'm hung up on the max order total. I was thinking of a subquery for the highest and lowest order totals but I can't make it work.
SELECT
TC.intCustomerID
,TC.strLastName + ',' + ' ' + TC.strFirstName AS strCustomerName
,ISNULL(SUM( TCOI.intQuantity * TI.monPrice), 0) AS monOrderTotals
,COUNT(DISTINCT TCO.intOrderIndex) AS intNumberOfOrders
,ISNULL(SUM(TCOI.intQuantity * TI.monPrice) / COUNT(DISTINCT TCO.intOrderIndex), 0) AS monAverageOrderTotals
,(SELECT MAX(TCOI.intQuantity * TI.monPrice)
FROM TItems AS TI, TCustomerOrderItems AS TCOI
WHERE TI.intItemID = TCOI.intItemID
-- Cross-query join with two columns
-- AND TC.intCustomerID = TCOI.intCustomerID
-- AND TCO.intOrderIndex = TCOI.intOrderIndex
----GROUP BY
-- TCOI.intCustomerID
--,TCOI.intOrderIndex
) AS monMostExpensiveOrder
FROM
TCustomers AS TC
LEFT OUTER JOIN
TCustomerOrders AS TCO ON (TC.intCustomerID = TCO.intCustomerID)
LEFT OUTER JOIN
TCustomerOrderItems AS TCOI ON (TCO.intOrderIndex = TCOI.intOrderIndex)
LEFT OUTER JOIN
TItems AS TI ON (TCOI.intItemID = TI.intItemID)
GROUP BY
TC.intCustomerID
,TC.strLastName
,TC.strFirstName
Any insight would be greatly appreciated.
For me, using a common table expression goes a long way towards making code easier to read and write when you are working with derived tables (selecting from subqueries).
I think this should cover what you are trying to do, but I was not sure which way you wanted to count average items per order (by number of distinct items or the quantity of items):
with cte as (
select
tc.intCustomerId
, tc.strFirstName
, tc.strLastName
, tcoi.intOrderIndex
, TotalPrice = isnull(sum(tcoi.intQuantity * ti.monPrice), 0 )
, ItemCount = count(*)
, TotalItemQuantity = sum(tcoi.intQuantity)
from TCustomers tc
left join tCustomerOrderItems as tcoi
on tc.intCustomerId = tcoi.intCustomerId
left join tItems as ti
on ti.intItemID = tcoi.intItemID
)
select
intCustomerId
, Name = isnull(strLastName+', ') + isnull(strFirstName,'')
, countOrders = count(intOrderIndex)
, sumTotalPrice = sum(TotalPrice)
, minTotalPrice = min(TotalPrice)
, maxTotalPrice = max(TotalPrice)
, avgTotalPrice = avg(TotalPrice)
, avgItemCount = (sum(ItemCount)+.0)/nullif(count(intOrderIndex),0)
, avgItemQuant = (sum(TotalItemQuantity)+.0)/nullif(count(intOrderIndex),0)
from cte
group by
intCustomerId
, strFirstName
, strLastName
To take out the cte part, you would just move the query into the from.
select
intCustomerId
, Name = isnull(strLastName+', ') + isnull(strFirstName,'')
, countOrders = count(intOrderIndex)
, sumTotalPrice = sum(TotalPrice)
, minTotalPrice = min(TotalPrice)
, maxTotalPrice = max(TotalPrice)
, avgTotalPrice = avg(TotalPrice)
, avgItemCount = (sum(ItemCount)+.0)/nullif(count(intOrderIndex),0)
, avgItemQuant = (sum(TotalItemQuantity)+.0)/nullif(count(intOrderIndex),0)
from (
select
tc.intCustomerId
, tc.strFirstName
, tc.strLastName
, tcoi.intOrderIndex
, TotalPrice = isnull(sum(tcoi.intQuantity * ti.monPrice), 0 )
, ItemCount = count(*)
, TotalItemQuantity = sum(tcoi.intQuantity)
from TCustomers tc
left join tCustomerOrderItems as tcoi
on tc.intCustomerId = tcoi.intCustomerId
left join tItems as ti
on ti.intItemID = tcoi.intItemID
) as cte
group by
intCustomerId
, strFirstName
, strLastName
You will first need to calculate totals per order and per customer.
I will say that the schema is deficient in not storing order totals, since item price is likely to change, and TCustomerOrders likely includes historical orders. Prefixing tables and column names is also not recommended.
WITH CustomerOrders AS
(
SELECT
oi.intCustomerID as CustomerID,
oi.intOrderIndex as OrderID,
SUM(oi.intQuantity * i.monPrice) as SalesAmount,
COUNT(DISTINCT oi.intItemID) as DistinctItemCount,
SUM(oi.intQuantity) as ItemCount
FROM TCustomerOrderItems as oi
INNER JOIN TItems as i on oi.intItemID = i.intItemID
GROUP BY oi.intCustomerID, oi.intOrderIndex
),
CustomerSales AS
(
SELECT
co.CustomerID,
SUM(co.SalesAmount) as TotalSalesAmount,
COUNT(*) as OrderCount,
AVG(co.SalesAmount) as AvgOrderSalesAmount,
-- If item count should be distinct SKU's, use DistinctItemCount
-- Cast to numeric or another non-integer type to get fractional averages
AVG(CAST(co.ItemCount as numeric(14,4)) as AvgItemCount,
MIN(co.SalesAmount) as SmallestOrderSalesAmount,
MAX(co.SalesAmount) as LargestOrderSalesAmount
FROM CustomerOrders co
GROUP BY co.CustomerID
)
SELECT
c.intCustomerID as CustomerID,
c.strFirstName as CustomerFirstName,
c.strLastName as CustomerLastName,
COALESCE(cs.TotalSalesAmount, 0) as TotalSalesAmount,
COALESCE(cs.OrderCount, 0) as OrderCount,
COALESCE(cs.AvgOrderSalesAmount, 0) as AvgOrderSalesAmount,
COALESCE(cs.AvgItemCount, 0) as AvgItemCount,
COALESCE(cs.SmallestOrderSalesAmount, 0) as SmallestOrderSalesAmount,
COALESCE(cs.LargestOrderSalesAmount, 0) as LargestOrderSalesAmount
FROM TCustomers c
LEFT OUTER JOIN CustomerSales cs on c.intCustomerID = cs.CustomerID;