Sum certain rows in sql - ssms

I want to sum different rows of my table into a different column. I have a Id column which have multiple times. When I try to sum the time table it says cannot sum time data type.
Here is what my query looks like atm:
select t.Id,
a.EndTime,
cast(A.Endtime as time)[time]
from [plugin.tickets].Ticket as T
join
[plugin.tickets].TicketActivity as TA ON TA.TicketId = T.Id
join
dbo.Activity as A on A.Id = TA.ActivityId
Here is the output of this query:
As you can see there are id numbers which have multiple times. How can I sum these values?
EDIT:
I have changed my query as following:
select t.Id
,a.EndTime
,convert (varchar(5), EndTime,108) as Tijd
from [plugin.tickets].Ticket as T
join
[plugin.tickets].TicketActivity as TA ON TA.TicketId = T.Id
join
dbo.Activity as A on A.Id = TA.ActivityId
I just want to sum these where the ID number is the same.
Thanks,
Shabby

You should look into the two functions DATEPART and DATEADD. I'm assuming your useing T-SQL here. So you would take the time field convert that to hour which would give you 17 for example and then use date add on the End Time field.
https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017

Related

How to get the sum of transaction amount happened in one date?

I am trying to write a query that will give me transaction amount sum happened in one date. The problem is , when I added column date in my query, I get individual values not their sum. The requirement for this query is to have one entry for each merchant but i am getting multiple rows for one merchant.
SELECT SUBSTR(m.MERCHANTLASTNAME, 1, 36) Name1,
m.MERCHANTBANKBSB MerchantAccbsb,
m.MERCHANTBANKACCNR Merchant_act,
m.MERCHANTID merchantid,
t.transactiondate date1,
sum(t.TRANSACTIONAMOUNT) as total
FROM fss_merchant m
JOIN fss_terminal term
ON m.MERCHANTID = term.MERCHANTID
JOIN FSS_DAILY_TRANSACTION t
ON term.TERMINALID = t.TERMINALID
group by t.transactiondate, SUBSTR(m.MERCHANTLASTNAME, 1, 36), m.MERCHANTID, m.MERCHANTBANKBSB, m.MERCHANTBANKACCNR,
m.MERCHANTLASTNAME
Output of my query:
I want to get one entry per each merchant with the sum of transaction amount in one day, not multiple rows of transaction in that day.
You can calculate the total amount in different inner query with the truncated date and join it with FSS_MERCHANT table so that issues described by #SatishSK and #mangusta is taken care.
You can use the following query:
SELECT
SUBSTR(M.MERCHANTLASTNAME, 1, 36) NAME1,
M.MERCHANTBANKBSB MERCHANTACCBSB,
M.MERCHANTBANKACCNR MERCHANT_ACT,
M.MERCHANTID MERCHANTID,
M_DATA.TRANSACTIONDATE DATE1,
M_DATA.TOTAL AS TOTAL
FROM
FSS_MERCHANT M
INNER JOIN (
SELECT
TERM.MERCHANTID MERCHANTID,
TRUNC(T.TRANSACTIONDATE) TRANSACTIONDATE,
SUM(T.TRANSACTIONAMOUNT) AS TOTAL
FROM
FSS_TERMINAL TERM
JOIN FSS_DAILY_TRANSACTION T ON TERM.TERMINALID = T.TERMINALID
GROUP BY
TERM.MERCHANTID,
TRUNC(T.TRANSACTIONDATE)
) M_DATA ON ( M.MERCHANTID = M_DATA.MERCHANTID );
Good luck!!
t.transactiondate column might contain date+time values. Use TRUNC(t.transactiondate) where you are using just t.transactiondate. You will get sum(transaction amount) "Date-wise" for each merchant.
OR
Filter out rows based on "Date" value in WHERE clause to retrieve data pertaining to a specific date.
Probably the reason is that you have included both m.MERCHANTLASTNAME and SUBSTR(m.MERCHANTLASTNAME,1,36) into the group by clause.
In case if there are entries with same SUBSTR(m.MERCHANTLASTNAME,1,36) but different m.MERCHANTLASTNAME, this is going to yield duplicates. You need to remove m.MERCHANTLASTNAME from group by clause

SQL: Query new rows of a new date

i have table as shown here in this picture --> http://www.directupload.net/file/d/3710/lj7etq5j_png.htm
I need the correct Query to get only data_id 10.
The query should be like this: Compare the latest date rows (2014-08-08) with the earliest date rows (2014-08-06). If there is a row on 2014-08-08 which is NOT at 2014-08-06, this row should returned.
I already tried it with self-joins and Sub-Selects, but i did't get it work.
Thx for any help!
Maybe something like this is what you're looking for?
select * from Table1
where
data not in (
select data from Table1
where dataOfDate = (select min(dataofdate) from Table1)
)
and dataOfDate = (select max(dataofdate) from Table1)
The first where clause compares the data field of the returned rows to the data field in the set of oldest rows and the second where clause limits the set of rows the the newest.
Note that I'm only comparing rows based on thedatafield, so you might have to change the query if you want to includenextTableIdin the comparison.
Here is a sample SQL Fiddle.
How about something like this:
SELECT d1.* FROM Dates d1 LEFT JOIN Dates d2 ON d1.nextTableId = d2.nextTableId WHERE d1.dataofDate = '2014-08-08' AND d2.dataofDate = '2014-08-06' AND d2.data_id IS NULL;
SELECT `data_id`
FROM `my_table`
WHERE `dataOfDate` = (SELECT MAX(`dataOfDate`) FROM `my_table`)
AND `nextTableId` NOT IN (
SELECT `nextTableId` FROM `my_table` WHERE `dataOfDate` = (SELECT MIN(`dataOfDate`) FROM `my_table`)
)
select all rows with max date
that don't have values amongst rows with min date
edit ops, too late

Unpivot date columns to a single column of a complex query in Oracle

Hi guys, I am stuck with a stubborn problem which I am unable to solve. Am trying to compile a report wherein all the dates coming from different tables would need to come into a single date field in the report. Ofcourse, the max or the most recent date from all these date columns needs to be added to the single date column for the report. I have multiple users of multiple branches/courses for whom the report would be generated.
There are multiple blogs and the latest date w.r.t to the blogtitle needs to be grouped, i.e. max(date_value) from the six date columns should give the greatest or latest date for that blogtitle.
Expected Result:
select u.batch_uid as ext_person_key, u.user_id, cm.batch_uid as ext_crs_key, cm.crs_id, ir.role_id as
insti_role, (CASE when b.JOURNAL_IND = 'N' then
'BLOG' else 'JOURNAL' end) as item_type, gm.title as item_name, gm.disp_title as ITEM_DISP_NAME, be.blog_pk1 as be_blogPk1, bc.blog_entry_pk1 as bc_blog_entry_pk1,bc.pk1,
b.ENTRY_mod_DATE as b_ENTRY_mod_DATE ,b.CMT_mod_DATE as BlogCmtModDate, be.CMT_mod_DATE as be_cmnt_mod_Date,
b.UPDATE_DATE as BlogUpDate, be.UPDATE_DATE as be_UPDATE_DATE,
bc.creation_date as bc_creation_date,
be.CREATOR_USER_ID as be_CREATOR_USER_ID , bc.creator_user_id as bc_creator_user_id,
b.TITLE as BlogTitle, be.TITLE as be_TITLE,
be.DESCRIPTION as be_DESCRIPTION, bc.DESCRIPTION as bc_DESCRIPTION
FROM users u
INNER JOIN insti_roles ir on u.insti_roles_pk1 = ir.pk1
INNER JOIN crs_users cu ON u.pk1 = cu.users_pk1
INNER JOIN crs_mast cm on cu.crsmast_pk1 = cm.pk1
INNER JOIN blogs b on b.crsmast_pk1 = cm.pk1
INNER JOIN blog_entry be on b.pk1=be.blog_pk1 AND be.creator_user_id = cu.pk1
LEFT JOIN blog_CMT bc on be.pk1=bc.blog_entry_pk1 and bc.CREATOR_USER_ID=cu.pk1
JOIN gradeledger_mast gm ON gm.crsmast_pk1 = cm.pk1 and b.grade_handler = gm.linkId
WHERE cu.ROLE='S' AND BE.STATUS='2' AND B.ALLOW_GRADING='Y' AND u.row_status='0'
AND u.available_ind ='Y' and cm.row_status='0' and and u.batch_uid='userA_157'
I am getting a resultset for the above query with multiple date columns which I want > > to input into a single columnn. The dates have to be the most recent, i.e. max of the dates in the date columns.
I have successfully done the Unpivot by using a view to store the above
resultset and put all the dates in one column. However, I do not
want to use a view or a table to store the resultset and then do
Unipivot simply because I cannot keep creating views for every user
one would query for.
The max(date_value) from the date columns need to be put in one single column. They are as follows:
* 1) b.entry_mod_date, 2) b.cmt_mod_date ,3) be.cmt_mod_date , 4) b.update_Date ,5) be.update_date, 6) bc.creation_date *
Apologies that I could not provide the desc of all the tables and the
fields being used.
Any help to get the above mentioned max of the dates from these
multiple date columns into a single column without using a view or a
table would be greatly appreciated.*
It is not clear what results you want, but the easiest solution is to use greatest().
with t as (
YOURQUERYHERE
)
select t.*,
greatest(entry_mod_date, cmt_mod_date, cmt_mod_date, update_Date,
update_date, bc.creation_date
) as greatestdate
from t;
select <columns>,
case
when greatest (b_ENTRY_mod_DATE) >= greatest (BlogCmtModDate) and greatest(b_ENTRY_mod_DATE) >= greatest(BlogUpDate)
then greatest( b_ENTRY_mod_DATE )
--<same implementation to compare each time BlogCmtModDate and BlogUpDate separately to get the greatest then 'date'>
,<columns>
FROM table
<rest of the query>
UNION ALL
Select <columns>,
case
when greatest (be_cmnt_mod_Date) >= greatest (be_UPDATE_DATE)
then greatest( be_cmnt_mod_Date )
when greatest (be_UPDATE_DATE) >= greatest (be_cmnt_mod_Date)
then greatest( be_UPDATE_DATE )
,<columns>
FROM table
<rest of the query>
UNION ALL
Select <columns>,
GREATEST(bc_creation_date)
,<columns>
FROM table
<rest of the query>

Group by Week beginning Sunday

I have a table with eventdatetime , userid etc. The data is inserted in the table daily.
For the report , I need to give count of userid , projectid grouped by week : Tue-Mon for a month range at a time.
I need help on grouping the data by week for month. I'm using Oracle.
select count(distinct( table1.projectid))as Projects, count(distinct( table2.userid)) as Users,??
from table1
join table 2
on table1.a= table2.a
where table1.e='1'
and table1.eventdatetime between sysdate-30 and sysdate-1
group by ??
I want the output to be grouped by week like :
WeekBegin
2013-04-14
2013-04-21
http://www.techonthenet.com/oracle/functions/to_char.php Use the To_Char function with IW to get the week. Then you can GROUP BY that IW value.
Note that the date the Oracle week starts on is dependent on the language settings of the database. Some countries start on Sunday and some Monday. You'll have to look at your settings to see. If it already starts on Sunday, then you're in luck!
if the example you have posted is your work in progress version - before worrying about getting the days of the week in you should look into getting the basics of the query right
you are selecting e.projectid and u.userid but you haven't got any tables named e or u in your query - it looks like you want to alias them as e and u?
the where clause of your query is also looking for the table e which isn't present
in that case you should change
from table1
join table2
on table1.a= table2.a
to
from table1 e -- select from table1 using alias e
join table2 u -- join table2 using alias u
on ( e.a = u.a ) -- joining on column a from table1 (e) = a from table2 (u)
once you have replaced the a's in the on section with the column names you want to join using it might well run after you remove the last column ", ??" from the select - perhaps something along these lines
select
count (e.projectid) PROJECTS,
count (u.userid) USERS
from table1 e
join table2 u
on ( e.a = u.a )
where e.FILTERING_COLUMN = '1'
and e.eventdatetime >= sysdate-30
note that as sysdate is the current time on the server (depending on localisation and session settings) you can use greater than sysdate-30 instead of between which may well be give the query optimiser an easier time if the table is suitable indexed
the basic rule for grouping is that to select a column you need to either be grouping by it or using an aggregate function such as COUNT()
so you'll probably want something like
select
count (e.projectid) PROJECTS,
count (u.userid) USERS,
to_char(e.eventdatetime,'MM') MONTH
from table1 e
join table2 u
on ( e.a = u.a )
where e.FILTERING_COLUMN = '1'
and e.eventdatetime >= sysdate-30
group by e.eventdatetime
though this won't be the most optimal way to do this it would be easier if you posted the schemas involved in the issue

SQL Server adjust each value in a column by another table

I have two tables, TblVal and TblAdj.
In TblVal I have a bunch of values that I need adjusted according to TblAdj for a given TblVal.PersonID and TblVal.Date and then returned in some ViewAdjustedValues. I must apply only those adjustments where TblAdj.Date >= TblVal.Date.
The trouble is that since all the adjustments are either a subtraction or a division, they need to be made in order. Here is the table structure:
TblVal: PersonID, Date, Value
TblAdj: PersonID, Date, SubtractAmount, DivideAmount
I want to return ViewAdjustedValues: PersonID, Date, AdjValue
Can I do this without iterating through TblAdj using a WHILE loop and an IF block to either subtract or divide as necessary? Is there some nested SELECT table magic I can perform that would be faster?
I think you can do it without a loop, but whether you want to or not is another question. A query that I think works is below (SQL Fiddle here). The key ideas are as follows:
Each SubtractAmount has the ultimate effect of subtracting SubtractAmount divided by the product of all later DivideAmounts for the same PersonID. The Date associated with the PersonID isn't relevant to this adjustment (fortunately). The CTE AdjustedAdjustments contains these adjusted SubtractAmount values.
The initial Value for a PersonID gets divided by the product of all DivideAmount values on or after that persons Date.
EXP(SUM(LOG(x))) works as an aggregate product if all values of x are positive. You should constrain your DivideAmount values to assure this, or adjust the code accordingly.
If there are no DivideAmounts, the associated product is NULL and changed to 1. Similarly, NULL sums of adjusted SubtractAmount values are changed to zero. A left join is used to preserve an values that are not subject to any adjustments.
SQL Server 2012 supports an OVER clause for aggregates, which was helpful here to aggregate "all later DivideAmounts."
WITH AdjustedAdjustments AS (
select
PersonID,
Date,
SubtractAmount/
EXP(
SUM(LOG(COALESCE(DivideAmount,1)))
OVER (
PARTITION BY PersonID
ORDER BY Date
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
)
) AS AdjustedSubtract,
DivideAmount
FROM TblAdj
)
SELECT
p.PersonID,
p.Value/COALESCE(EXP(SUM(LOG(COALESCE(DivideAmount,1)))),1)
-COALESCE(SUM(a.AdjustedSubtract),0) AS AmountAdjusted
FROM TblVal AS p
LEFT OUTER JOIN AdjustedAdjustments AS a
ON a.PersonID = p.PersonID
AND a.Date >= p.Date
GROUP BY p.PersonID, p.Value, p.Date;
Try something like following:
with CTE_TblVal (PersonID,Date,Value)
as
(
select A.PersonID, A.Date, A.Value
from TblVal A
inner join TblAdj B
on A.PersonID = B.PersonID
where B.Date >= A.Date
)
update CTE_TblVal
set Date = TblAdj.Date,
Value = TblAdj.Value
from CTE_TblVal
inner join TblAdj
on CTE_Tblval.PersonID = TblAdj.PersonID
output inserted.* into ViewAdjustedValues
select * from ViewAdjustedValues