date issue due to datediff function in between - sql

I have following query:
SELECT
datediff(d, 0, sauda_date),
Scrip_Code,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) AS BuyQty,
SUM(CASE WHEN Buy_sell = 1 THEN Market_Rate ELSE 0 END) AS BuyRate,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) AS BuyAmount,
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) AS SellQty,
SUM(CASE WHEN Buy_sell = 2 THEN Market_Rate ELSE 0 END) AS SellRate,
(CASE WHEN SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) >
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) THEN 'BF'
ELSE 'BT' END ) as TradeType,
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END) AS SellAmount,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) -
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) as NETQTY,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) -
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END)as NetAmt,
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END) -
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) as PNLAmt
FROM tradeFile
where Inst_Type = 'FUTIDX'
OR Inst_Type='FUTSTK'
and Sauda_Date = convert(datetime,'1 Mar 2013')
group by Scrip_Code, ExpiryDate, datediff(d,0,sauda_date)
Result:
This query is for taking sum of Buy_Qty,Sell_Qty datewise.[With ref to this quest:not able to get individual date in query result
But as we can see datediff(d,0,sauda_date) column (i.e. first column) is giving me some result, but i wanted to add sauda_date also in this result as a date.
what changes i should make in this query.
I tried it by adding directly sauda_date in query but it gives me error.
Please guid me.

If you use a GROUP BY in your query then (in case of T-SQL) in the field's part of a query you can use only fields from GROUP BY or aggregate functions (SUM, COUNT,....). So you can't add just sauda_date. You should add it with aggregate function. For example MIN(sauda_date). OR you can add it to GROUP BY part.

Not sure with your result requirement..
simply adding sauda_date in select list should not give error if you includ it in group by list, i have tried belwo and its working.
Select datediff(d,0,f.Date),
sum(f.price),
f.OrderID,
f.Date
from test f
group by f.Date,OrderID,datediff(d,0,f.Date)
Else
you can use self join to get only sauda date joining main result on your key column

Related

Sum case statement

The below SQL is returning 'Cannot perform an aggregate function on an expression containing an aggregate or a subquery.', can anyone help?
SELECT
sum(case when Frequency = 'Monthly' then ISNULL(SUM(Amount),0.0) else 0 end) +
sum(case when Frequency = '4 Weekly' then ISNULL(SUM(Amount),0.0) / 2 else 0 end) +
sum(case when Frequency = 'Fortnightly' then ISNULL(SUM(Amount),0.0) / 3 else 0 end) +
sum(case when Frequency = 'Weekly' then ISNULL(SUM(Amount),0.0) / 5 else 0 end)
FROM TableWHERE Id = 1
If you want conditional aggregation, you only want one sum():
SELECT sum(case when Frequency = 'Monthly' then Amount else 0 end) +
sum(case when Frequency = '4 Weekly' then Amount / 2 else 0 end) +
sum(case when Frequency = 'Fortnightly' then Amount / 3 else 0 end) +
sum(case when Frequency = 'Weekly' then Amount,0.0) / 5 else 0 end)
FROM Table
WHERE Id = 1;
I think you want to do something like
sum(case when Frequency = 'Monthly' then ISNULL(Amount,0.0) else 0 end)
SELECT
sum(case when Frequency = 'Monthly' then ISNULL(Amount,0.0) else 0 end) +
sum(case when Frequency = '4 Weekly' then ISNULL(Amount,0.0) / 2 else 0 end) +
sum(case when Frequency = 'Fortnightly' then ISNULL(Amount,0.0) / 3 else 0 end) +
sum(case when Frequency = 'Weekly' then ISNULL(Amount,0.0) / 5 else 0 end)
FROM Table
WHERE Id = 1

SQL How to do substraction based on my below case?

How to I set a column called NEW_BAL, result are from strResponseTextNull minus of the MIGS_STATUS_Approved:
SELECT
Convert(char(8), WebPayH_dtmRequest, 112)as MIGSPaymentRequestDate,
SUM(case when WebPayH_strResponseText IS NULL then 1 else 0 end) as strResponseTextNull,
SUM(case when WebPayH_strApproved like 'Y' then 1 else 0 end) as MIGS_STATUS_Approved,
SUM(case when WebPayH_strResponseText like 'Transaction+was+blocked+by+the+Payment+Server+because+it+did+not+pass+all+risk+checks.' then 1 else 0 end) as RiskCheckNotPass,
SUM(case when WebPayH_strResponseText like 'The+card+holder+was+not+authorised.+This+is+used+in+3-D+Secure+Authentication.' then 1 else 0 end) as ThreeDNotEnabled,
SUM(case when WebPayH_strResponseText like 'Expired+Card' then 1 else 0 end) as ExpiredCard,
SUM(case when WebPayH_strResponseText like 'Declined' then 1 else 0 end) as DeclinedByBank,
SUM(case when WebPayH_strResponseText like 'Insufficient+Funds' then 1 else 0 end) as InsufficientFunds,
SUM(case when WebPayH_strResponseText like 'Timed+Out' then 1 else 0 end) as TimerOut,
**-- SELECT strResponseTextNull - SUM MIGS_STATUS_Approved AS NEW_BAL**
count(WebPayH_strResponseCode) AS TotalMIGSPaymentRequest
FROM
[VISTAIT].[dbo].[tblWebPaymentHistory]
WHERE
WebPayH_dtmRequest >= '2015-05-07'
GROUP BY
Convert(char(8), WebPayH_dtmRequest, 112)
ORDER BY
Convert(char(8), WebPayH_dtmRequest, 112)
Try this
SELECT
Convert(char(8), WebPayH_dtmRequest, 112)as MIGSPaymentRequestDate,
SUM(case when WebPayH_strResponseText IS NULL then 1 else 0 end) as strResponseTextNull,
SUM(case when WebPayH_strApproved like 'Y' then 1 else 0 end) as MIGS_STATUS_Approved,
SUM(case when WebPayH_strResponseText like 'Transaction+was+blocked+by+the+Payment+Server+because+it+did+not+pass+all+risk+checks.' then 1 else 0 end) as RiskCheckNotPass,
SUM(case when WebPayH_strResponseText like 'The+card+holder+was+not+authorised.+This+is+used+in+3-D+Secure+Authentication.' then 1 else 0 end) as ThreeDNotEnabled,
SUM(case when WebPayH_strResponseText like 'Expired+Card' then 1 else 0 end) as ExpiredCard,
SUM(case when WebPayH_strResponseText like 'Declined' then 1 else 0 end) as DeclinedByBank,
SUM(case when WebPayH_strResponseText like 'Insufficient+Funds' then 1 else 0 end) as InsufficientFunds,
SUM(case when WebPayH_strResponseText like 'Timed+Out' then 1 else 0 end) as TimerOut,
SUM(case when WebPayH_strResponseText IS NULL then 1 else 0 end)-SUM(case when WebPayH_strApproved like 'Y' then 1 else 0 end) as NEW_BAL,
count(WebPayH_strResponseCode) AS TotalMIGSPaymentRequest
FROM
[VISTAIT].[dbo].[tblWebPaymentHistory]
WHERE
WebPayH_dtmRequest >= '2015-05-07'
GROUP BY
Convert(char(8), WebPayH_dtmRequest, 112)
ORDER BY
Convert(char(8), WebPayH_dtmRequest, 112)

Calculation in CASE WHEN statement

I have this extract form a query im writing.
What I want to do is sum only the successful payments
something along the lines of
, SUM(CASE WHEN (LOWER(result) = 'successful') THEN (SUM(amount) as amt_paid) ELSE 0 END) AS Successful_Payed
Here is the query extract.
Select
resultdate
, SUM(amount) as amt_paid
, SUM(CASE WHEN (LOWER(result) = 'successful') THEN 1 ELSE 0 END) AS Successful
, SUM(CASE WHEN (LOWER(result) = 'unsuccessful') THEN 1 ELSE 0 END) AS Unsuccessful
, SUM(CASE WHEN (LOWER(result) = 'tracking') THEN 1 ELSE 0 END) AS Tracking
, SUM(CASE WHEN (LOWER(result) = 'dispute') THEN 1 ELSE 0 END) AS Dispute
From paysoft_results
Group By resultdate
Order By resultdate
change like this
Select
resultdate
, SUM(CASE WHEN (LOWER(result) = 'successful') THEN amount ELSE 0 END) AS
Successful_Payed
, SUM(CASE WHEN (LOWER(result) = 'successful') THEN 1 ELSE 0 END) AS Successful
, SUM(CASE WHEN (LOWER(result) = 'unsuccessful') THEN 1 ELSE 0 END) AS Unsuccessful
, SUM(CASE WHEN (LOWER(result) = 'tracking') THEN 1 ELSE 0 END) AS Tracking
, SUM(CASE WHEN (LOWER(result) = 'dispute') THEN 1 ELSE 0 END) AS Dispute
From paysoft_results
Group By resultdate
Order By resultdate

Grouping by Month of TimeStamp

I am attempting to group by twice, once by an individual level field and then by the month of the timestamp field.
Little new to SQL but here's what I came up with after reading another SO post here: SQL query to group by month part of timestamp
SELECT
VwNIMUserDim.USER_EMAIL_ADDRESS,
VwNIMEventFct.NIM_USER_ID,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 880 THEN 1 ELSE 0 END) AS APP_OPEN,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 881 THEN 1 ELSE 0 END) AS AUTODL_SETTINGS_SAVE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 882 THEN 1 ELSE 0 END) AS AUTO_QUERY_CONFIRM,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 883 THEN 1 ELSE 0 END) AS ISSUE_CLOSE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 884 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 885 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD_COMPLETE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 886 THEN 1 ELSE 0 END) AS PICKER_SEND_PICKS
FROM RDMAVWSANDBOX.VwNIMEventFct
GROUP BY NIM_USER_ID, MONTH('EVENT_GMT_TIMESTAMP')
The error message returned by my SQL client, Teradata, says:
"SELECT FAILED Error 3706 Syntax error expected something in between ',' and the MONTH keyword.
This is my first time doing two things: Grouping By twice and using the Month function.
What am I doing wrong here? How do I group by email address users in each month?
There's no MONTH function in Teradata/Standard SQL, it's EXTRACT(YEAR/MONTH/DAY/HOUR/MINUTE/SECOND):
EXTRACT(MONTH FROM EVENT_GMT_TIMESTAMP)
Your query as written will result in a PRODUCT (Cartesian) JOIN between the VwNIMUserDIm and VwNIMEventFct tables (views). I have taken the liberty to modify the SQL based on your comments to the previous response:
SELECT
User_.USER_EMAIL_ADDRESS,
Event_.NIM_USER_ID,
Event_.EVENT_GMT_TIMESTAMP(FORMAT 'yyyy-mm')(char(7)) AS EVENT_MONTH,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 880 THEN 1 ELSE 0 END) AS APP_OPEN,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 881 THEN 1 ELSE 0 END) AS AUTODL_SETTINGS_SAVE,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 882 THEN 1 ELSE 0 END) AS AUTO_QUERY_CONFIRM,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 883 THEN 1 ELSE 0 END) AS ISSUE_CLOSE,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 884 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 885 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD_COMPLETE,
SUM(CASE WHEN Event_.NIM_EVENT_TYPE_ID = 886 THEN 1 ELSE 0 END) AS PICKER_SEND_PICKS
FROM RDMAVWSANDBOX.VwNIMEventFct Event_
JOIN RDMAVWSANDBOX.VwNIMUserDim User_
ON Event_.NIM_USER_ID = User_.NIM_USER_ID
GROUP BY 1,2;
Possibly depending on database origin (MSSQL, mySQL, Oracle, DB2, Etc)
SELECT
VwNIMUserDim.USER_EMAIL_ADDRESS,
VwNIMEventFct.NIM_USER_ID,
MONTH(EVENT_GMT_TIMESTAMP),
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 880 THEN 1 ELSE 0 END) AS APP_OPEN,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 881 THEN 1 ELSE 0 END) AS AUTODL_SETTINGS_SAVE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 882 THEN 1 ELSE 0 END) AS AUTO_QUERY_CONFIRM,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 883 THEN 1 ELSE 0 END) AS ISSUE_CLOSE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 884 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 885 THEN 1 ELSE 0 END) AS ISSUE_DOWNLOAD_COMPLETE,
SUM(CASE WHEN NIM_EVENT_TYPE_ID = 886 THEN 1 ELSE 0 END) AS PICKER_SEND_PICKS
FROM RDMAVWSANDBOX.VwNIMEventFct
GROUP BY NIM_USER_ID, MONTH(EVENT_GMT_TIMESTAMP)

sum function not working properly

My database in SQL Server 2005:
My query is:
SELECT *
FROM TRADEFILE
WHERE CONVERT(DATETIME,SAUDA_DATE) LIKE 'MAR 1 2013%'
AND SCRIP_CODE='DLF' AND INST_TYPE LIKE 'FUT%'
This gives me result:
In this Buy=1 and Sell=2.
If we make sum of Buy Qty i.e. buy_sell=1 then it is 3000
and when we make sum for sell trade qty i.e. buy_sell=2 then it is 3000
But when I fire this query for getting same result as follows:
select
CONVERT(VARCHAR(11),sauda_date) AS sauda_date,
SUM(CASE
WHEN Buy_sell = 1 and scrip_code='DLF'
and Sauda_Date between convert(datetime,'01/03/2013')
and convert(datetime,'06/04/2013')
THEN Trade_Qty ELSE 0 END) AS BuyQty,
SUM(CASE
WHEN Buy_sell = 2 and scrip_code='DLF'
and Sauda_Date between convert(datetime,'01/03/2013')
and convert(datetime,'06/04/2013')
THEN Trade_Qty ELSE 0 END) AS SellQty ,
SUM(CASE
WHEN Buy_sell = 1 and scrip_code='DLF'
THEN Trade_Qty ELSE 0 END)
-SUM(CASE
WHEN Buy_sell = 2 and scrip_code='DLF'
THEN Trade_Qty ELSE 0 END) AS CarryForword
from tradefile
where scrip_code='DLF'
group by CONVERT(VARCHAR(11),sauda_date)
It gives me result as:
i.e. BuyQty=5000 and sellQty is 4000
while we have calculated it as 3000 and 3000 respectively.
How can it be different? is my sum() function working wrong??
Is my query is wrong?
The conditions are quite different so it is just plausible that the results are too.
Examples:
In your first query, you have a condition for PARTY_CODE. This is completely missing in the second query.
The same goes for INST_TYPE
The condition for SAUDA_DATE is very different. The first query only queries March, 1st, while the second queries everything between March, 1st and April, 6th.
I understood that first query you have given, has 3000 for buyin_qty and sell_qty.
In your second query which is having CASE statements misses some of your where condition from First query
AND PARTY_CODE='0L036'
AND INST_TYPE LIKE 'FUT%'
This should work:
select
CONVERT(VARCHAR(11),sauda_date) AS sauda_date,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) AS BuyQty,
SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) AS SellQty ,
SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END)
-SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) AS CarryForword
from tradefile
where scrip_code='DLF'
group by CONVERT(VARCHAR(11),sauda_date)