Using multiple columns to determine SUM results - sql

I am having trouble getting my head around the following sum. I have a table of items, which shows the location, the item code and the size code. The unique feature of this table is there is a flag that determines whether the location will stock a particular item.
I have another table that shows the stock movements of the items. This table also shows location, item, size and either a positive or negative entry. The sum of the positive/negative entries give the current stock holding.
What i can't seem to do is say SUM the stock movement quantities where the item and size are marked with 'location can stock this item'
The first select statement brings back items that can be stocked by location
select
S.[Location Code],S.[Item No_],S.[size],
from [Stockkeeping Units] S
where [Range in Location] = 1
The results return a list as:
location Code| Item no | Size
1 | SHIRT1 | s
1 | SHIRT1 | m
1 | SHIRT2 | s
1 | SHIRT2 | m
2 | SHIRT1 | s
2 | SHIRT2 | m
The second select statement bring back the current stock for an item by location
select
L.[Location Code],L.[Item No_],L.[size],
sum(L.[Quantity]) as Quantity
from [Item Ledger Entry] L
location Code| Item no | Size | Quantity
1 | SHIRT1 | s | 5
1 | SHIRT1 | m | 3
1 | SHIRT2 | s | 5
1 | SHIRT2 | m | 7
2 | SHIRT1 | s | 3
2 | SHIRT2 | m | 0
It is when i try to join these tables to bring back the combination of the first 2 select statements, that it goes astray
select L.[Location Code],L.[Item No_], L.[Variant Code],
sum(L.[Quantity]) as Quantity
from [$Item Ledger Entry] L
join [Stockkeeping Unit] on [Item Ledger Entry].[Item No] = [Stockkeeping
Unit].[Item No_]
where [Stockkeeping Unit].[Range in Location] = 1
group by L.[Location Code],L.[Item No_],L.[Variant Code]
What i would like to see is:
location|item no|size|quantity where range in location is yes
The joined query is bringing back result the are ignoring the
[Stockkeeping Unit].[Range in Location] = 1 request
The joined query is also not returning the same SUM results as the second SELECT query

It looks like you meant this:
SELECT [Location Code], [Item No_], [size], SUM([Quantity]) AS Quantity
FROM [Item Ledger Entry] L
WHERE EXISTS (
SELECT *
FROM [Stockkeeping Units] S
WHERE S.[Range in Location]=1
AND S.[Location code]=L.[Location code]
AND S.[Item No]=L.[Item no]
AND S.[Size]=L.[Size]
)
GROUP BY L.[Location Code], L.[Item No_], L.[size];

Related

SQL Return corresponding values for duplicated rows in separate column

I have over 10K codes that I want to extract from the table to and show Euro and Sterling selling price in separate columns. My code duplicates each code and returns both currencies in 1 column making over 20K rows.
I am not advanced tech guy :-( I am trying to find a better ways of doing things. I browsed through few examples which were less complicated and suggested PIVOT or Dynamic Table functions but I could not understand how to implement it in my code hence I am reaching to you guys. I know you can probably do it with closed eyes.
SQL Code
SELECT
SI.Code AS [Item Code], SI.Name AS [Item Name],
PLSA.SupplierAccountNumber AS [Supplier Code], SC.Symbol AS [Currency],
SIS.ListPrice AS [€ Selling Price], PG.Code AS [PG Code]
, PG.Description AS [PG Name], SIP.Price AS [Standard Cost]
, CASE WHEN PB.PriceBandID = 129519 THEN '£ Standard'
WHEN PB.PriceBandID = 1001 THEN '€ Standard'
ELSE 'UNKNOWN' END AS [Selling Currency Std]
, SIS.SupplierStockCode AS [Supplier Stock Code],
SIStatus.StockItemStatusName [Stock Code Status], SI.AnalysisCode8 AS
[Core / Non-Core]
, SI.AnalysisCode7 AS [Product Chart], SI.AnalysisCode6 AS [Website Product]
FROM StockItem SI
INNER JOIN StockItemSupplier SIS ON SIS.ItemID = SI.ItemID
INNER JOIN PLSupplierAccount PLSA ON SIS.SupplierID =
PLSA.PLSupplierAccountID
INNER JOIN SYSCurrency SC ON PLSA.SYSCurrencyID = SC.SYSCurrencyID
INNER JOIN ProductGroup PG ON PG.ProductGroupID = SI.ProductGroupID
INNER JOIN StockItemPrice SIP ON SIP.ItemID = SI.ItemID
INNER JOIN PriceBand PB ON PB.PriceBandID = SIP.PriceBandID
INNER JOIN StockItemStatus SIStatus ON SIStatus.StockItemStatusID =
SI.StockItemStatusID
the result is
| Item Code |... |Selling Currency Std|
----------------------------
| M1 | | €1.00 |
| M1 | | £0.90 |
| M2 | | €5.00 |
| M2 | | £4.50 |
| M3 | | €9.99 |
What I want it to be:
| Item Code |... |Selling Currency Std €|Selling Currency Std £|
------------------------------------------------------------------
| M1 | | €1.00 | £0.90|
| M2 | | €5.00 | £4.50|
| M3 | | €9.99 | £8.99|
I would suggest you to use a something like excel's sumif, only sum the value if condition is true. If you have no duplicate for (Item, Currency) the sum will only add up 2 values, one always 0 and the other is the actual SalesPrice in the specific currency.
; with ItemPriceList as
(select
SI.Code as [Item Code]
, sum(iif(PB.PriceBandID = 1001, SIP.Price, 0)) as [Selling Currency Std €]
, sum(iif(PB.PriceBandID = 129519, SIP.Price, 0)) as [Selling Currency Std £]
from
StockItem SI
inner join StockItemPrice SIP on SIP.ItemID = SI.ItemID
inner join PriceBand PB on PB.PriceBandID = SIP.PriceBandID
group by
SI.Code
)
select
IPL.[Item Code]
, IPL.[Selling Currency Std €]
, IPL.[Selling Currency Std £]
from
ItemPriceList IPL
--inner join the additional data for analysis
Oh, and don't brother with the additional information, like [Supplier Code], [PG Code], etc. while you're collecting the Sales Price, they can be added later on, that's why I used a CTE.

Hello , currently learning and I am in need of some assistance. I need to write a query that will return a table with select columns [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Write a query that will return a table with the following columns:
User ID, Site ID, User Name, Total Sales, Total Refunds, Net Amount Collected
I need to write a query that will return a table which at the moment im trying to figure out thanks.
Tried select statement but failed.enter image description here
I agree with the others that simply handing this over will not help your learning much. There are a bunch of concepts that you need to learn here. Submitting this answer for your homework might be awkward (and result in a score of 0) if you can't explain it!
Common Table Expressions
Aggregate Functions
Outer Joins
with cte_sales as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Sales]
from Transactions t
where t.[Transaction Type] = 'Sale'
group by t.[User Id],
t.[Site Id]
),
cte_refunds as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Refunds]
from Transactions t
where t.[Transaction Type] = 'Refund'
group by t.[User Id],
t.[Site Id]
)
select
u.[User Id],
u.[Site Id],
u.[Name] as [User Name],
coalesce(s.[Total Sales],0) as [Total Sales],
abs(coalesce(r.[Total Refunds],0)) as [Total Refunds],
(coalesce(s.[Total Sales],0) + coalesce(r.[Total Refunds],0)) as [Net Amount Collected]
from Users u
left join cte_sales s on s.[User Id] = u.[User Id]
and s.[Site Id] = u.[Site Id]
left join cte_refunds r on r.[User Id] = u.[User Id]
and r.[Site Id] = u.[Site Id]
order by u.[User Id],
u.[Site Id];
Demo
| User Id | Site Id | User Name | Total Sales | Total Refunds | Net Amount Collected |
|---------|---------|-----------|-------------|---------------|----------------------|
| 1 | 1 | Arthur | 120 | 120 | 0 |
| 2 | 1 | Aaron | 90 | 30 | 60 |
| 2 | 2 | Brett | 90 | 0 | 90 |

SQL 2 Left outer joins with Sum and Group By

Looking for some guidance on this. I am attempting to run a report in my complaint management system.. Complaints by Year, Location, Subcategory, Showing Totals for TotalCredits (child table) and TotalsCwts (childtable) as well as total ExternalRootCause (on master table).
This is my SQL, but the TotalCwts and TotalCredits are not being calculated correctly. It calculates 1 time for each child record rather than the total for each master record.
SELECT
dbo.Complaints.Location,
YEAR(dbo.Complaints.ComDate) AS Year,
dbo.Complaints.ComplaintSubcategory,
COUNT(Distinct(dbo.Complaints.ComId)) AS CustomerComplaints,
SUM(DISTINCT CASE WHEN (dbo.Complaints.RootCauseSource = 'External' ) THEN 1 ELSE 0 END) as ExternalRootCause,
SUM(dbo.ComplaintProducts.Cwts) AS TotalCwts,
Coalesce(SUM(dbo.CreditDeductions.CreditAmount),0) AS TotalCredits
FROM dbo.Complaints
JOIN dbo.CustomerComplaints
ON dbo.Complaints.ComId = dbo.CustomerComplaints.ComId
LEFT OUTER JOIN dbo.CreditDeductions
ON dbo.Complaints.ComId = dbo.CreditDeductions.ComId
LEFT OUTER JOIN dbo.ComplaintProducts
ON dbo.Complaints.ComId = dbo.ComplaintProducts.ComId
WHERE
dbo.Complaints.Location = Coalesce(#Location,Location)
GROUP BY
YEAR(dbo.Complaints.ComDate),
dbo.Complaints.Location,
dbo.Complaints.ComplaintSubcategory
ORDER BY
[YEAR] desc,
dbo.Complaints.Location,
dbo.Complaints.ComplaintSubcategory
Data Results
Location | Year | Subcategory | Complaints | External RC | Total Cwts | Total Credits
---------------------------------------------------------------------------------------
Boston | 2016 | Documentation | 1 | 0 | 8 | 8.00
Data Should Read
Location | Year | Subcategory | Complaints | External RC | Total Cwts | Total Credits
---------------------------------------------------------------------------------------
Boston | 2016 | Documentation | 1 | 0 | 4 | 2.00
Above data reflects 1 complaint having 4 Product Records with 1cwt each and 2 credit records with 1.00 each.
What do I need to change in my query or should I approach this query a different way?
The problem is that the 1 complaint has 2 Deductions and 4 products. When you join in this manner then it will return every combination of Deduction/Product for the complaint which gives 8 rows as you're seeing.
One solution, which should work here, is to not query the Dedustion and Product tables directly; query a query which returns one row per table per complaint. In other words, replace:
LEFT OUTER JOIN dbo.CreditDeductions ON dbo.Complaints.ComId = dbo.CreditDeductions.ComId
LEFT OUTER JOIN dbo.ComplaintProducts ON dbo.Complaints.ComId = dbo.ComplaintProducts.ComId
...with this - showing the Deductions table only, you can work out the Products:
LEFT OUTER JOIN (
select ComId, count(*) CountDeductions, sum(CreditAmount) CreditAmount
from dbo.CreditDeductions
group by ComId
) d on d.ComId = Complaints.ComId
You'll have to change the references to dbo.CreditDedustions to just d (or whatever you want to call it).
Once you've done them both then you'll one each per complaint, which will result with 1 row per complaint contaoining the counts and totals from the two sub-tables.

SQL Server 2014 Join Doubling Line Items

I can usually find answers to my questions if I search hard enough but I don't know how to word my question well enough to get the results I desire.
The issue I am having is that I am trying to Join my Order Charge Table to my other Query so that I can see if there was a Discount or a Shipping charge applied.
There are 3 scenarios that can happen per order in the Order Charge Table (Discount AND Shipping charge applied) OR (Discount applied) OR (Shipping applied)
NULL values are NOT allowed so if there is no discount or shipping for the order, it does not show up in this table.
My query without the order charges applied is:
SELECT
[Order].[OrderNumber],
CASE
WHEN [ShopifyOrder].[PaymentStatusCode] = '2' THEN 'Paid'
WHEN [ShopifyOrder].[PaymentStatusCode] = '4' THEN 'Refunded'
WHEN [ShopifyOrder].[PaymentStatusCode] = '5' THEN 'Voided'
WHEN [ShopifyOrder].[PaymentStatusCode] = '6' THEN 'Partially Refunded'
END AS 'PaymentStatus',
[Store].[StoreName] as 'MarketplaceNames',
[OrderItem].[SKU],
[LookupList].[MainSKU], [LookupList].[ProductName],
[LookupList].[Classification] as 'Classification',
[LookupList].[Cost],
([OrderItem].[Quantity] * [OrderItem].[UnitPrice]) AS 'Sales',
(([OrderItem].[Quantity] * [LookupList].[Quantity]) * [LookupList].[Cost]) AS 'Total Cost',
[OrderItem].[Quantity] * [LookupList].[Quantity] AS 'Total Qty'
FROM
[SHIPSERVER].[dbo].[Order]
JOIN
[SHIPSERVER].[dbo].[ShopifyOrder] ON [Order].[OrderID] = [ShopifyOrder].[OrderID]
JOIN
[SHIPSERVER].[dbo].[OrderItem] ON [OrderItem].[OrderID] = [Order].[OrderID]
JOIN
[SHIPSERVER].[dbo].[Store] ON [Order].[StoreID] = [Store].[StoreID]
LEFT JOIN
[SHIPSERVER].[dbo].[LookupList] ON [OrderItem].[SKU] = [LookupList].[SKU]
WHERE
([Store].[StoreName]= 'Shopify')
AND ([Order].[OrderDate] BETWEEN '2015-09-01 00:00:00.000' AND '2015-09-30 23:59:59.999')
AND ([Order].[IsManual] = '0')
I am going to give 1 order as an example in the Results
+-------------+---------------+------------------+---------------+---------------+----------------+-------+-------+------------+-----------+
| OrderNumber | PaymentStatus | MarketplaceNames | SKU | MainSKU | Classification | Cost | Sales | Total Cost | Total Qty |
| 7177 | Paid | Shopify | 300TLSH SL PL | 300TLSH SL PL | Sheet Set | 21.00 | 48.99 | 21 | 1 |
+-------------+---------------+------------------+---------------+---------------+----------------+-------+-------+------------+-----------+
Here is my query when I join the OrderCharge table:
SELECT
[Order].[OrderNumber],
CASE
WHEN [ShopifyOrder].[PaymentStatusCode] = '2' THEN 'Paid'
WHEN [ShopifyOrder].[PaymentStatusCode] = '4' THEN 'Refunded'
WHEN [ShopifyOrder].[PaymentStatusCode] = '5' THEN 'Voided'
WHEN [ShopifyOrder].[PaymentStatusCode] = '6' THEN 'Partially Refunded'
END AS 'PaymentStatus',
[Store].[StoreName] as 'MarketplaceNames',
[OrderItem].[SKU],
[LookupList].[MainSKU],
[OrderCharge].[Type], [OrderCharge].[Description], [OrderCharge].[Amount],
[LookupList].[Classification] as 'Classification', [LookupList].[Cost],
([OrderItem].[Quantity]* [OrderItem].[UnitPrice]) AS 'Sales',
(([OrderItem].[Quantity] * [LookupList].[Quantity]) * [LookupList].[Cost]) AS 'Total Cost',
[OrderItem].[Quantity] * [LookupList].[Quantity] AS 'Total Qty'
FROM
[SHIPSERVER].[dbo].[Order]
JOIN
[SHIPSERVER].[dbo].[ShopifyOrder] ON [Order].[OrderID] = [ShopifyOrder].[OrderID]
JOIN
[SHIPSERVER].[dbo].[OrderItem] ON [OrderItem].[OrderID] = [Order].[OrderID]
JOIN
[SHIPSERVER].[dbo].[Store] ON [Order].[StoreID] = [Store].[StoreID]
LEFT JOIN
[SHIPSERVER].[dbo].[LookupList] ON [OrderItem].[SKU] = [LookupList].[SKU]
JOIN
[SHIPSERVER].[dbo].[OrderCharge] ON [Order].[OrderID] = [OrderCharge].[OrderID]
WHERE
([Store].[StoreName]= 'Shopify')
AND ([Order].[OrderDate] BETWEEN '2015-09-01 00:00:00.000' AND '2015-09-30 23:59:59.999')
AND ([Order].[IsManual] = '0')
Again I am going to give the same order as an example in the Results
+-------------+---------------+------------------+---------------+---------------+----------+------------------------+--------+----------------+-------+-------+------------+-----------+
| OrderNumber | PaymentStatus | MarketplaceNames | SKU | MainSKU | Type | Description | Amount | Classification | Cost | Sales | Total Cost | Total Qty |
| 7177 | Paid | Shopify | 300TLSH SL PL | 300TLSH SL PL | DISCOUNT | 15chance | -7.35 | Sheet Set | 21.00 | 48.99 | 21 | 1 |
| 7177 | Paid | Shopify | 300TLSH SL PL | 300TLSH SL PL | SHIPPING | FREE Standard Shipping | 0.00 | Sheet Set | 21.00 | 48.99 | 21 | 1 |
+-------------+---------------+------------------+---------------+---------------+----------+------------------------+--------+----------------+-------+-------+------------+-----------+
If I were to export this into an excel file, the Cost, Sales, and Total Qty fields are now all doubled for this order, this becomes an even bigger issue if there are multiple line items in an order.
I thought a solution would be to make the Discount and Shipping Fields their own columns but all that did was put Discount and Shipping on the same line but all the line items were still doubled.
I have to be over looking something.
SELECT [Order].[OrderNumber]
,CASE WHEN [ShopifyOrder].[PaymentStatusCode] = '2' THEN 'Paid'
WHEN [ShopifyOrder].[PaymentStatusCode] = '4' THEN 'Refunded'
WHEN [ShopifyOrder].[PaymentStatusCode] = '5' THEN 'Voided'
WHEN [ShopifyOrder].[PaymentStatusCode] = '6' THEN 'Partially Refunded'
END AS 'PaymentStatus'
,[Store].[StoreName] as 'MarketplaceNames'
,[OrderItem].[SKU]
,[LookupList].[MainSKU]
,[ShippingCharge].[Description] as shippingDescription
,[ShippingCharge].[Amount] as shippingAmount
,[DiscountCharge].[Description] as discountDescription
,[DiscountCharge].[Amount] as discountAmount
,[LookupList].[Classification] as 'Classification'
,[LookupList].[Cost]
,([OrderItem].[Quantity]* [OrderItem].[UnitPrice]) AS 'Sales'
,(([OrderItem].[Quantity] * [LookupList].[Quantity]) * [LookupList].[Cost]) AS 'Total Cost'
,[OrderItem].[Quantity] * [LookupList].[Quantity] AS 'Total Qty'
FROM [SHIPSERVER].[dbo].[Order]
JOIN [SHIPSERVER].[dbo].[ShopifyOrder]
ON [Order].[OrderID]=[ShopifyOrder].[OrderID]
JOIN [SHIPSERVER].[dbo].[OrderItem]
ON [OrderItem].[OrderID]=[Order].[OrderID]
JOIN [SHIPSERVER].[dbo].[Store]
ON [Order].[StoreID]=[Store].[StoreID]
LEFT JOIN [SHIPSERVER].[dbo].[LookupList]
ON [OrderItem].[SKU]=[LookupList].[SKU]
LEFT JOIN [SHIPSERVER].[dbo].[OrderCharge] [ShippingCharge]
ON [Order].[OrderID]=[ShippingCharge].[OrderID] AND [ShippingCharge].[Type] = 'SHIPPING'
LEFT JOIN [SHIPSERVER].[dbo].[OrderCharge] [DiscountCharge]
ON [Order].[OrderID]=[DiscountCharge].[OrderID] AND [DiscountCharge].[Type] = 'DISCOUNT'
WHERE ([Store].[StoreName]= 'Shopify')
AND ([Order].[OrderDate] BETWEEN '2015-09-01 00:00:00.000' AND '2015-09-30 23:59:59.999')
AND ([Order].[IsManual] = '0')
The differences are :
,[ShippingCharge].[Description] as shippingDescription
,[ShippingCharge].[Amount] as shippingAmount
,[DiscountCharge].[Description] as discountDescription
,[DiscountCharge].[Amount] as discountAmount
and
LEFT JOIN [SHIPSERVER].[dbo].[OrderCharge] [ShippingCharge]
ON [Order].[OrderID]=[ShippingCharge].[OrderID] AND [ShippingCharge].[Type] = 'SHIPPING'
LEFT JOIN [SHIPSERVER].[dbo].[OrderCharge] [DiscountCharge]
ON [Order].[OrderID]=[DiscountCharge].[OrderID] AND [DiscountCharge].[Type] = 'DISCOUNT'
Basically, what I did is I left joined on OrderCharge twice, once for Discount and once for Shipping, with a different alias each time. This means that you're potentially linked to a discount row and potentially linked to a shipping row, and from there getting the data is incredibly easy.
As #thab pointed out in comments though, there are glaring issues with this. First of all, having more than one Shipping or Discount entries will duplicate rows, at which point you would have to use a sum on the [Amount] (and probably an XML concatenation on the description). This also means that the query must be altered whenever a new Type of ChargeOrder appears.
The idea solution would be using Pivot, but I haven't dabbled with that yet so I can't help you with that one. I do believe that Pivot tables run slower though (well, at least dynamic ones do), so as long as your problem doesn't change you should be fine.

Interesting and challenging self join problem SQL Server 2005

I have this table named OrdersToCall
Data types: All bigints, except for date which is a datetime
|-Order Num-|----Date--- |- Primary Ph -| Secondary Ph | Alternate Ph
|----101----| 02-07-2010 | 925-515-1234 | 916-515-1234 | 707-568-5778
|----102----| 02-07-2010 | 925-888-4141 | 925-888-4141 | 000-000-0000
|----103----| 02-07-2010 | 000-000-0000 | 000-000-0000 | 510-555-4575
|----104----| 02-07-2010 | 415-789-5454 | 415-707-5588 | 735-874-9566
|----105----| 02-07-2010 | 925-887-7979 | 925-887-7979 | 925-887-7979
and I have another table named PhoneNumCalled
|-AgentID-|----Date----|-Dialed Number|
|-145564--| 02-07-2010 | 925-515-1234 |
|-145564--| 02-07-2010 | 707-568-5778 |
|-145566--| 02-07-2010 | 925-888-4141 |
|-145567--| 02-07-2010 | 510-555-4575 |
|-145568--| 02-07-2010 | 415-789-5454 |
|-145568--| 02-07-2010 | 415-707-5588 |
|-145568--| 02-07-2010 | 735-874-9566 |
|-145570--| 02-07-2010 | 925-887-7979 |
|-145570--| 02-07-2010 | 925-887-7979 |
Now my challenge is: I want to count how many Order Num were called and create a table based off the results.
So for example if agent 1234 called all 3 numbers on 1 order that would still only count as 1 order for that agent. The ratio is 1:1. Once a phone number is called then it is counted as 1 order. No matter if all 3 were called, an agent only has to call 1 of phone numbers to get credit for the order.
In less than 3 months time I already have almost 1/2 a million records so try to be as space conscious as possible.
My solution (Which I wish to revise with your help):
I ended up creating a stored procedure which:
--Delete and recreate the CombinedData table created yesterday
Insert into the CombinedData table
Select Order Num, Date, Primary Ph as Phone
from OrdersToCall
Union
Select Order Num, Date, Secondary Ph as Phone
from OrdersToCall
Union
Select Order Num, Date, Alternate Ph as Phone
from OrdersToCall
Delete from the CombinedData table
where phone in ('000-000-0000', '999-999-9999')
Now not only does this create a new table, but since each phone number in each order is now its own row the table becomes HUGE and take up to 2 minutes to create.
Then from this table I derive the counts and store those in yet another table.
I think this is what you're looking for:
SELECT c.AgentId, COUNT(DISTINCT o.[Order Num]) AS [Orders per Agent]
FROM OrdersToCall o
JOIN PhoneNumCalled c ON c.[Dialed Number] = o.[Primary Ph]
OR c.[Dialed Number] = o.[Secondary Ph]
OR c.[Dialed Number] = o.[Alternate Ph]
GROUP BY c.AgentId
If you want to know how many calls were made on each date, you would have to join on the date also:
SELECT c.AgentId, c.Date, COUNT(DISTINCT o.[Order Num]) AS [Orders per Agent]
FROM OrdersToCall o
JOIN PhoneNumCalled c ON (c.[Dialed Number] = o.[Primary Ph]
OR c.[Dialed Number] = o.[Secondary Ph]
OR c.[Dialed Number] = o.[Alternate Ph])
AND o.Date = c.Date
GROUP BY c.AgentId, c.Date