Below is transaction item table.
Now I wanted to retrieve total amount of the transaction, total amount with discount, total discount and Sales Tax for which I wrote the below query:
select t1.av_transaction_id,
round(SUM((t1.gross_line_amount - t1.pos_discount_amount)), 2) AS total_amount_with_discount,
round(SUM((t1.gross_line_amount)), 2) AS total_amount,
round(SUM((t1.pos_discount_amount)), 2) AS total_discount,
round(SUM((t2.gross_line_amount)), 2) AS total_sales_tax
from transaction_detail as t1
inner join transaction_detail as t2 on t1.av_transaction_id=t2.av_transaction_id
and t1.transaction_date=t2.transaction_date
where (t1.sku_id is not null or t1.line_action_display_descr='sold')
and t2.line_object_description='S6 Sales Tax'
and t1.av_transaction_id='581280193'
group by t1.av_transaction_id
But I get the following output:
av_transaction_id:581280193 || total_amount_with_discount:5.01 || total_amount:6.67 || total_discount:1.66 || total_Sales_tax:0.66
As you may see in the screenshot the Sales Tax should be 0.22 but somehow the query returns 0.66.
Can someone pleas help me in optimizing this query and let me know why does it return an incorrect value ?
There are three records for this transaction where the sku_id is not null or the display description is 'sold'. All three of those will match with the Sales Tax record for the join... and then you take the SUM(). So .22 + .22 + .22 = .66
To fix this, I'd use conditional aggregation rather than a self-join:
select t1.av_transaction_id,
round(SUM(CASE WHEN t1.sku_id is not null or t1.line_action_display_descr='sold' THEN t1.gross_line_amount - t1.pos_discount_amount ELSE 0 END)), 2) AS total_amount_with_discount,
round(SUM(CASE WHEN t1.sku_id is not null or t1.line_action_display_descr='sold' THEN t1.gross_line_amount ELSE 0 END), 2) AS total_amount,
round(SUM(CASE WHEN t1.sku_id is not null or t1.line_action_display_descr='sold' THEN t1.pos_discount_amount ELSE 0 END), 2) AS total_discount,
round(SUM(CASE WHEN t1.line_object_description='S6 Sales Tax' THEN t1.gross_line_amount ELSE 0 END), 2) AS total_sales_tax
from transaction_detail as t1
where t1.av_transaction_id='581280193'
group by t1.av_transaction_id
Though this repeats the same condition, so you might be able to wrap that up further to only resolve the condition once.
This worked for me, thanks to previous respondents:
select t1.av_transaction_id,
round(SUM((t1.gross_line_amount - t1.pos_discount_amount)), 2) AS total_amount_with_discount,
round(SUM((t1.gross_line_amount)), 2) AS total_amount,
round(SUM((t1.pos_discount_amount)), 2) AS total_discount,
round(SUM((t2.gross_line_amount))/count(t1.gross_line_amount), 2) AS total_sales_tax
from transaction_detail as t1 inner join
transaction_detail as t2 on t1.av_transaction_id=t2.av_transaction_id
and t1.transaction_date=t2.transaction_date
where (t1.sku_id is not null or t1.line_action_display_descr='sold')
and t2.line_object_description='S6 Sales Tax'
and t1.av_transaction_id='581280193'
group by t1.av_transaction_id
I think that all you need to do is to not sum the sales tax, so your query would look like this:
select t1.av_transaction_id,
round(SUM((t1.gross_line_amount - t1.pos_discount_amount)), 2) AS total_amount_with_discount,
round(SUM((t1.gross_line_amount)), 2) AS total_amount,
round(SUM((t1.pos_discount_amount)), 2) AS total_discount,
round(t2.gross_line_amount, 2) AS total_sales_tax
from transaction_detail as t1
inner join transaction_detail as t2 on t1.av_transaction_id=t2.av_transaction_id
and t1.transaction_date=t2.transaction_date
where (t1.sku_id is not null or t1.line_action_display_descr='sold')
and t2.line_object_description='S6 Sales Tax'
and t1.av_transaction_id='581280193'
group by t1.av_transaction_id
I mocked up your table with this script:
CREATE TABLE SO_TEST
(
intTransID INT
, objDesc VARCHAR(MAX)
, displayDesc VARCHAR(MAX)
, lintAmt FLOAT
, discAmount FLOAT
)
INSERT INTO SO_TEST (intTransID, objDesc, displayDesc, lintAmt, discAmount)
VALUES
(1,'emp merch','sold',2.29,.57)
, (1,'emp merch','sold',1.89,.47)
, (1,'emp merch tax','sold',2.49,.62)
, (1,'sales tax','charged',.22,0.0)
, (1,'blah','blah',1.0,2.0)
, (2,'emp merch','sold',3.29,1.57)
, (2,'emp merch','sold',2.89,1.47)
, (2,'emp merch tax','sold',3.49,1.62)
, (2,'sales tax','charged',1.22,0.0)
, (2,'blah','blah',1.0,2.0)
And came up with this query that displays what I believe you want to have it display:
SELECT t1.intTransID
, ROUND(SUM(t1.lintAmt - t1.discAmount),2) tot_amt_disc
, ROUND(SUM(t1.lintAmt), 2) tot_amt
, ROUND(SUM(t1.discAmount),2) disc_amt
, ROUND(t2.lintAmt,2) sales_tax
FROM SO_TEST t1
JOIN SO_TEST t2 ON 1=1
AND t1.intTransID = t2.intTransID
WHERE t1.displayDesc IN ('sold','charged')
AND t1.objDesc <> 'sales tax'
AND t2.objDesc = 'sales tax'
GROUP BY t1.intTransID, t2.lintAmt
The results of the query are as follows:
This works for multiple transactions as asked.
Related
What I'm looking to do is quantify the total value of purchases and the number of months in which a purchase was made within three different timeframes by account. I only want to look at accounts who made a purchase between 1-1-2020 and 4-1-2021.
I'm wondering if there is a more streamlined way to pull in the fields I'm creating using CASE WHEN below (maybe through a series of queries to create the calculations and the left joining?). This query is taking extremely long to pull back, so I'd like to enhance this code where I can. All of my code and desired output is listed below. Thank you!
Creating a temporary table to pull account numbers:
DROP TABLE IF EXISTS #accounts
SELECT DISTINCT s.account_no, c.code, c.code_desc
INTO #accounts
FROM sales AS s
LEFT JOIN customer AS c ON s.account_no = c.account_no
WHERE s.tran_date BETWEEN '2020-01-01' AND '2021-04-01'
GROUP BY s.account_no, c.code, c.code_desc;
Confirming row counts:
SELECT COUNT (*)
FROM #accounts
ORDER BY account_no;
Creating Sales and Sales period count columns for three timeframes:
SELECT
s.account_no, c.code, c.code_desc
SUM(CASE
WHEN s.tran_date BETWEEN '2020-01-01' AND '2021-04-01'
THEN VALUE_USD
END) AS Total_Spend_Pre,
SUM(CASE
WHEN s.tran_date BETWEEN '2021-04-01' AND '2022-03-31'
THEN VALUE_USD
END) Total_Spend_During,
SUM(CASE
WHEN s.tran_date > '2022-04-01'
THEN VALUE_USD
END) Total_Spend_Post,
COUNT(DISTINCT CASE WHEN s.tran_date BETWEEN '2020-01-01' AND '2021-04-01' THEN CONCAT(s.bk_month, s.bk_year) END) Pre_Periods,
COUNT(DISTINCT CASE WHEN s.tran_date BETWEEN '2021-04-01' AND '2022-03-31' THEN CONCAT(s.bk_month, s.bk_year) END) During_Periods,
COUNT(DISTINCT CASE WHEN s.tran_date > '2022-04-01' THEN CONCAT(s.bk_month, s.bk_year) END) Post_Periods
FROM
sales AS s
LEFT JOIN
customer AS c ON s.account_no = c.account_no
WHERE
c.account_no IN (SELECT DISTINCT account_no
FROM #accounts)
GROUP BY
s.account_no, c.code, c.code_desc;
Desired output:
account_no
code
code_desc
Total_Spend_Pre
Total_Spend_During
Total_Spend_Post
Pre_Periods
During_Periods
Post_Periods
25
1234
OTHER
1000
2005
500
2
14
5
11
5678
PC
500
100
2220
5
11
2
You may use your date ranges to join with dataset, and 'Tag' your result like below, this will result in 3 rows, for each group. If you need them in a single row, have PIVOTE over it
;With DateRanges AS (
SELECT CAST('2020-01-01' AS DATE) StartDate, CAST('2021-04-01' AS DATE) EndDate, 'Pre' Tag UNION
SELECT '2021-04-01', '2022-03-31', 'During' UNION
SELECT '2022-04-01', Null, 'Post'
)
SELECT s.account_no, c.code, c.code_desc, d.Tag,
SUM(VALUE_USD) AS Total_Spend,
COUNT(DISTINCT CONCAT(s.bk_month, s.bk_year)) RecordCount
FROM sales as s
LEFT JOIN customer as c
INNER JOIN DateRanges D ON s.tran_date BETWEEN D.StartDate AND ISNULL(D.EndDate,s.tran_date)
ON s.account_no = c.account_no
WHERE c.account_no IN (SELECT DISTINCT account_no FROM #accounts)
GROUP BY s.account_no, c.code, c.code_desc;
with [cte_accountActivityPeriods] as (
select [PeriodOrdinal] = 1, [PeriodName] = 'Total Spend Pre', [PeriodStart] = convert(date,'2020-01-01',23) , [PeriodFinish] = convert(date,'2021-03-31',23) union
select [PeriodOrdinal] = 2, [PeriodName] = 'Total Spend During', [PeriodStart] = convert(date,'2021-04-01',23) , [PeriodFinish] = convert(date,'2022-03-31',23) union
select [PeriodOrdinal] = 3, [PeriodName] = 'Total Spend Post', [PeriodStart] = convert(date,'2022-04-01',23) , [PeriodFinish] = convert(date,'9999-12-31',23)
)
, [cte_allsalesForActivityPeriod]
SELECT s.account_no, bk_month, bk_year, [PeriodOrdinal], s.tran_date, s.value_usd
FROM sales as s
cross join [cte_accountActivityPeriods]
on s.[tran_date] between [cte_ActivityPeriods].[PeriodStart] and [cte_ActivityPeriods].[PeriodFinish]
)
, [cte_uniqueAccounts] as ( /*Unique and qualifying Accounts*/
select distinct account_no from [cte_allsalesForActivityPeriod]
inner join #accounts accs on accs.[account_no] = [cte_allsalesForActivityPeriod].[account_no]
)
, [cte_AllSalesAggregatedByPeriod] as (
select account_no, [PeriodOrdinal], bk_month, bk_year, [PeriodTotalSpend] = sum([value_usd])
from [cte_allsalesForActivityPeriod]
group by s.account_no, [PeriodOrdinal], bk_month, bk_year
)
, [cte_PeriodAnalysis] as (
select account_no, [PeriodOrdinal], [ActivePeriods] = count(distinct concat(bk_month, bk_year))
from [cte_AllSalesAggregatedByPeriod]
group by s.account_no, [PeriodOrdinal]
)
, [cte_pivot_clumsily] as (
/* Aggregations already done - so simple pivot */
select [cte_uniqueAccounts].[account_no]
, [Total_Spend_Pre] = case when [SaleVal].[PeriodOrdinal] in (1) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Total_Spend_During] = case when [SaleVal].[PeriodOrdinal] in (2) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Total_Spend_Post] = case when [SaleVal].[PeriodOrdinal] in (3) then [SaleVal].[PeriodTotalSpend] else 0 end
, [Pre_Periods] = case when [SalePrd].[PeriodOrdinal] in (1) then [SalePrd].[ActivePeriods] else 0 end
, [During_Periods] = case when [SalePrd].[PeriodOrdinal] in (2) then [SalePrd].[ActivePeriods] else 0 end
, [Post_Periods] = case when [SalePrd].[PeriodOrdinal] in (3) then [SalePrd].[ActivePeriods] else 0 end
from [cte_uniqueAccounts]
left join [cte_AllSalesAggregatedByPeriod] [SaleVal] on [SaleVal].[account_no] = [cte_uniqueAccounts].[account_no]
left join [cte_PeriodAnalysis] [SalePrd] on [SalePrd].[account_no] = [cte_uniqueAccounts].[account_no]
)
select c.code, c.code_desc, [cte_pivot_clumsily].*
from [cte_pivot_clumsily]
LEFT JOIN customer as c
ON [cte_pivot_clumsily].account_no = c.account_no
I have a view of materials data which contains what was purchased and reversals of some of the purchases. I need a query that removes records that have reversals of purchase transactions. NOTE: The view does not have a primary key.
In the example I need to remove the first two rows as the second row offsets the first row because it reverses the purchase, but I need to keep the third row. Any ideas?
Here is the SQL for the view:
SELECT LEFT(mi.Plnt, 3) AS SBUID ,
oth.EQUIP AS PROJECTID ,
ms.Req_No AS GI ,
ms.Req_Item AS GI_LINE ,
CONVERT(VARCHAR(11), [Doc_Date], 100) + ' 12:00 AM' AS DOC_DATE ,
mi.[SLoc] AS SLOC ,
[Material] AS MATERIAL ,
mi.[Description] AS MATERIAL_DESCRIPTION ,
[Qty] AS QUANTITY ,
mi.[UoM] AS UOM ,
CASE WHEN mi.Mvt IN ( '101', '103', '105', '123', '261' ) THEN
mi.Amount
ELSE mi.Amount * -1
END AS Cost ,
mi.Amount AS EXT_ORG_COST ,
mi.PO AS [PO] ,
mi.Batch ,
mi.Vendor AS VENDOR ,
mi.VendorName AS VENDOR_NAME ,
at.AC_Group AS AC_TYPE ,
[Mvt] AS MVT
FROM [dbo].[MatIssued] mi
INNER JOIN dbo.OrderTableHistory oth ON oth.SUB_ORDER = mi.SubOrder
INNER JOIN dbo.Aircraft_Information2 ai ON ai.Equip = oth.EQUIP
INNER JOIN dbo.RFC_AcftTypeList at ON at.ID = ai.AC_TypeID
LEFT OUTER JOIN dbo.MatStatus ms ON ms.MPN = mi.Material
AND ms.SubOrder = mi.SubOrder
WHERE mi.Plnt IN ( '9131', '9132' )
AND mi.Mvt IN ( '101', '102', '103', '104', '105', '106', '122', '123' ,
'261' ,'262' )
AND mi.Doc_Date >= DATEADD(YEAR, -1, GETDATE())
ORDER BY mi.PO ,
mi.Batch ,
PROJECTID ,
mi.Mvt;
Some assumptions, based on your screenshot:
Reversals have same DOC_DATE as purchases
Reversals have same Batch as purchases
If the above assumptions are correct, try something like this:
DELETE FROM t
FROM MyTable t
WHERE EXISTS (
SELECT 1
FROM MyTable t2
WHERE
-- Join to outer table
t2.SLOC = t.SLOC
AND t2.MATERIAL = t.MATERIAL
AND t2.QUANTITY = t.QUANTITY
AND t2.PO = t.PO
AND t2.Batch = t.Batch
AND t2.VENDOR = t.VENDOR
GROUP BY SLOC, MATERIAL, QUANTITY, PO, Batch, VENDOR
HAVING COUNT(*) = 2 -- There are 2 matching rows
AND -MIN(QUANTITY) = MAX(QUANTITY) -- Minimum quantity negates Maximum quantity
AND MIN(COST) + MAX(COST) = 0 -- Costs cancel each other out
AND MIN(CASE WHEN Cost > 0 THEN DOC_DATE END) <= MIN(CASE WHEN Cost < 0 THEN DOC_DATE END) -- Purchase DOC_DATE less than or equal to reversal DOC_DATE
AND MIN(MVT) = MAX(MVT) + 1 -- Correlate purchase and reversal movement
AND (t.DOC_DATE = MIN(DOC_DATE) OR t.DOC_DATE = MAX(DOC_DATE)) -- Join to outer table
)
I am trying to add a 'Total' row after each Unique CustomerName. I have tried ROLLUP and it does not seem to work properly because of the amount of fields i am trying to group by. An example of what i am looking for would pseudo be
(
FlavorName('Total'), 2016Sales (Sum of total sales), 2017Sales (Sum of total sales), 2016TotalPounds (Sum of total pounds), 2017TotalPounds (Sum of total pounds))
Please find my current code below.
WITH cte AS (SELECT CustName AS CustomerName, ItemKey AS CICode, Description AS FlavorName, CASE WHEN InvoiceDate BETWEEN '2016-01-01' AND
'2016-12-31' THEN SUM(LineNet) ELSE 0 END AS [2016TotalSales], CASE WHEN InvoiceDate BETWEEN '2017-01-01' AND getdate() THEN SUM(LineNet)
ELSE 0 END AS [2017TotalSales], CASE WHEN InvoiceDate BETWEEN '2016-01-01' AND '2016-12-31' THEN ROUND(SUM(QtyOrd), 2)
ELSE 0 END AS [2016TotalPounds], CASE WHEN InvoiceDate BETWEEN '2017-01-01' AND getdate() THEN ROUND(SUM(QtyOrd), 2)
ELSE 0 END AS [2017TotalPounds], BasePrice, SUBSTRING(CAST(InvoiceDate AS nvarchar(50)), 8, 5) AS year, UOM
FROM dbo.ABC
GROUP BY CustName, ItemKey, Description, BasePrice, InvoiceDate, UOM)
SELECT TOP (100) PERCENT CustomerName, CASE WHEN CICode IS NULL THEN 'ALL' ELSE CICode END AS CICode, CASE WHEN BasePrice IS NULL
THEN 'TOTALS' ELSE FlavorName END AS FlavorName, SUM([2016TotalSales]) AS [2016Sales], SUM([2017TotalSales]) AS [2017Sales], SUM([2016TotalPounds])
AS [2016TotalPounds], ROUND(SUM([2017TotalPounds]), 2) AS [2017TotalPounds], UOM, ISNULL(ROUND((SUM([2017TotalPounds]) - SUM([2016TotalPounds]))
/ NULLIF (SUM([2016TotalPounds]), 0) * 100, 2), 100) AS [%Change], BasePrice
FROM cte AS cte_1
GROUP BY CustomerName, CICode, FlavorName, BasePrice, UOM
HAVING (SUM([2016TotalSales]) + SUM([2017TotalSales]) > 0)
Try GROUPING SETS:
GROUP BY GROUPING SETS ( (CustomerName, CICode, FlavorName, BasePrice, UOM), (CustomerName) )
You may have to play with ORDER BY to get the results in the particular order that you want.
I have 2 seperate select statements, using aggregate functions in each. I would like to be able to take the results and combine them.
table_a
id int
entered_date datetime (holds utc stamp)
balance money
group_id int
table_b
id int
entered_date date
balance money
transaction_type int
query 1:
select convert(date,entered_date), sum(balance) as earned
from table_a
where group_id in (1, 2, 3, 4)
group by convert(date,entered_Date)
query 2:
select convert(date,entered_date), sum(balance) as spent
where transaction_type = 2
group by convert(date,entered_Date)
results:
query 1:
2012-05-13, 5000
2012-05-14, 12000
...
query 2:
2012-05-13, 9000
2012-05-14, 55856
...
I would like to return one row for each record without using temp tables. The result set should have a date, then earned vs. spent. I have a report running using union to get the totals and that is fine, but i need to generate a result set with 1 record and a earned vs against line. Any help with this is appreciated.
Try:
;With AllDates AS
(
select convert(date,entered_date) As EnteredDate
from table_a
where group_id in (1, 2, 3, 4)
group by convert(date,entered_Date)
UNION
select convert(date,entered_date)
from table_b
where transaction_type = 2
group by convert(date,entered_Date)
)
, AllEarned AS (
select convert(date,entered_date) AS EnteredDate, sum(balance) as Earned
from table_a
where group_id in (1, 2, 3, 4)
group by convert(date,entered_Date)
)
, AllSpent AS (
select convert(date,entered_date) AS EnteredDate, sum(balance) as Spent
from table_b
where transaction_type = 2
group by convert(date,entered_Date)
)
SELECT
d.EnteredDate, e.Earned, s.Spent
FROM AllDates d
LEFT OUTER JOIN AllEarned e ON d.EnteredDate=e.EnteredDate
LEFT OUTER JOIN AllSpent s ON d.EnteredDate=s.EnteredDate
ORDER BY 1,2,3
You can combine these using logic, assuming that both are from the same table
(the second query is missing the from statement):
select convert(date,entered_date),
sum(case when group_id in (1, 2, 3, 4) then balance end) as earned,
sum(case when transaction_type = 2 then balance end) as spend
from table_a
group by convert(date,entered_Date)
SELECT
CASE WHEN a.a_date IS NULL THEN b.a_date ELSE a.a_date END as a_data,
a.earned,
b.spent
FROM
(select
convert(date,entered_date) as a_date,
sum(balance) as earned
from table_a
where group_id in (1, 2, 3, 4)
group by entered_Date) A
FULL OUTER JOIN
(select
convert(date,entered_date) as a_date,
sum(balance) as spent
from table_a
where transaction_type = 2
group by entered_Date) B
ON A.a_date=b.a_date
Or using FULL OUTER JOIN if there are data that don't meet both conditions. And using CASE WHEN a.a_date IS NULL THEN b.a_date ELSE a.a_date END as a_data
Assuming earned amounts are from table_a and spent amounts are from table_b,
; WITH a AS (
select entered_date=convert(date,entered_date), balance as earned, 0 AS spent
from table_a
where group_id in (1, 2, 3, 4)
UNION ALL
select entered_date=convert(date,entered_date), 0 AS earned, balance as spent
from table_b
where transaction_type = 2
)
SELECT entered_date
, earned=SUM(earned)
, spent=SUM(spent)
FROM a
GROUP BY entered_date
Hi i have a query which i need to show the number of transactions a user made,per day with the EUR equivalent of each transaction.
The query below does do that (find the eur equivalent by getting an average rate) but because the currencies are different i get the results by currency instead and not by total. what the query returns is:
Numb Transactions,Date, userid,transaction_type,total value (per currency),eur_equiv
1 12/12, 2, test 5 10
2 12/12,2, test 2 2
whereas i want it to return
Numb Transactions,Date, userid,transaction_type,total value (per currency),eur_equiv
1 12/12, 2, test 7 12
the query is shown below
SELECT COUNT(DISTINCT(ot.ID)) AS 'TRANSACTION COUNTER'
,CONVERT(VARCHAR(10) ,ot.CREATED_ON ,103) AS [DD/MM/YYYY]
,lad.ci
,ot.TRA_TYPE
,c.C_CODE
,CASE
WHEN op.CURRENCY_ID='CURRENCY-002' THEN SUM(CAST(op.IT_AMOUNT AS MONEY))
/(
SELECT AVG(CAST(cr.B_RATE AS MONEY)) AS AVG_RATE
FROM C_RATE cr
WHERE cr.CURRENCY_ID = 'CURRENCY-002'
)
WHEN op.CURRENCY_ID='-CURRENCY-005' THEN SUM(CAST(op.IT_AMOUNT AS MONEY))
/(
SELECT AVG(CAST(cr.B_RATE AS MONEY)) AS AVG_RATE
FROM C_RATE cr
WHERE cr.CURRENCY_ID = 'CURRENCY-005'
)
WHEN op.CURRENCY_ID='CURRENCY-006' THEN SUM(CAST(op.IT_AMOUNT AS MONEY))
/(
SELECT AVG(CAST(cr.B_RATE AS MONEY)) AS AVG_RATE
FROM C_RATE cr
WHERE cr.CURRENCY_ID = 'CURRENCY-006'
)
ELSE '0'
END AS EUR_EQUIVAL
FROM TRANSACTION ot
INNER JOIN PAYMENT op
ON op.ID = ot.ID
INNER JOIN CURRENCY c
ON op.CURRENCY_ID = c.ID
INNER JOIN ACCOUNT a
ON a.ID = ot.ACCOUNT_ID
INNER JOIN ACCOUNT_DETAIL lad
ON lad.A_NUMBER = a.A_NUMBER
INNER JOIN CUST cus
ON lad.CI = cus.CI
WHERE ot.TRA_TYPE_ID IN ('INBANK-TYPE'
,'IN-AC-TYPE'
,'DOM-TRANS-TYPE')
AND ot.STATUS_ID = 'COMPLETED'
AND cus.BRANCH IN ('123'
,'456'
,'789'
,'789')
GROUP BY
lad.CI
,CONVERT(VARCHAR(10) ,ot.CREATED_ON ,103)
,c.C_CODE
,op.CURRENCY_ID
,ot.TRAN_TYPE_ID
HAVING SUM(CAST(op.IT_AMOUNT AS MONEY))>'250000.00'
ORDER BY
CONVERT(VARCHAR(10) ,ot.CREATED_ON ,103) ASC
SELECT MIN([Numb Transactions]
, Date
, UserID
, Transaction_type
, SUM([Total Value]
, SUM([Eur Equiv]
FROM (
... -- Your current select (without order by)
) q
GROUP BY
Date
, UserId
, Transaction_type
The problem resides most likely in a double row in your joins. What I do, is Select * first, and see what columns generate double rows. You might need to adjust a JOIN relationship for the double rows to disappear.
Without any resultsets, it's very hard to reproduce the error you are getting.
Check for the following things:
Select * returns only double rows on the data i will merge with an aggregate function. If the answer here is "NO", you will need to alter a JOIN relationship with a Subselect. I am thinking of that Account and Account detail table.
certain joins can create duplicate rows if the join cannot be unique enough. Maybe you will have to join on multiple things here, for example JOIN table1 ON table1.ID = table2.EXT_ID and table1.Contact = table2.Contact
Couple of things:
1) Consider using a function for:
SELECT AVG(CAST(cr.B_RATE AS MONEY)) AS AVG_RATE
FROM C_RATE cr
WHERE cr.CURRENCY_ID = 'CURRENCY-002' with the currencyID as a parameter
2) Would grouping sets work here?
3) was the sum on the case or on the individual whens?
sum(CASE ..) vs sum(cast(op.IT_Amount as money)