Get latest row and sum of a column in it togather - sql-server

In my table I have three columns amount,date,memberID. Now I want to get Latest amount inserted in to the table and the sum of whole amount inserted so far.
My Query was like this
SELECT amount , SUM(amount) as TotalAmount FROM [Transactions]
WHERE memberid = 1629 Order By Date DESC
But this throws an error like this
Msg 8120, Level 16, State 1, Line 1
Column 'Transactions.amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Can anyone point out what I am doing wrong here?

SELECT amount AS LatestAmount,
(SELECT SUM(amount) FROM [Transactions]) AS TotalAmount
FROM [Transactions]
WHERE date = (SELECT MAX(date) FROM [Transactions])
Note that in the event of a tie for more than one latest amount, the above query would produce one record for each tying transaction. If you want only one result, and you are using SQL Server 2008 or later, you can use TOP(1) to limit to a single result:
SELECT TOP(1) amount AS LatestAmount,
(SELECT SUM(amount) FROM [Transactions]) AS TotalAmount
FROM [Transactions]
WHERE date = (SELECT MAX(date) FROM [Transactions])

Just Add Group by clause
SELECT amount , SUM(amount) as TotalAmount FROM [Transactions]
GROUP BY amount WHERE memberid = 1629 Order By Date DESC

Related

Make a summary report in SQL Server

I'm working on this database that I want it to create a summary sum(Amount) report on the all the tables that will be specified. I tried this but it didn't get what I expected.
SELECT SUM(Amount) AS Expenditure
FROM Expenditure
WHERE Amount IS NOT NULL
UNION ALL
SELECT SUM(Amount)
FROM auxiliary
WHERE Category IS NOT NULL AND Amount >0;
This only shows
and this is want to achieve:
How do I make that possible?
SELECT 'Expenditure' AS TableName, SUM(Amount) AS Amount
FROM Expenditure
WHERE Amount IS NOT NULL
UNION ALL
SELECT 'Auxiliary' AS TableName, SUM(Amount) AS Amount
FROM auxiliary
WHERE Category IS NOT NULL AND Amount >0;

Column 'ACCOUNT.ACCOUNT_ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I am trying to get available balance on last(max) date. I am trying to write below query but it is showing error.
select ACCOUNT_ID,AVAIL_BALANCE,OPEN_DATE,MAX(LAST_ACTIVITY_DATE)
from ACCOUNT
group by CUST_ID;
Column 'ACCOUNT.ACCOUNT_ID' is invalid in the select list because it
is not contained in either an aggregate function or the GROUP BY
clause.
I am new to sql. Can anyone let me know where I am wrong in this query?
Any column not having a calculation/function on it must be in the GROUP BY clause.
select ACCOUNT_ID,AVAIL_BALANCE,OPEN_DATE,MAX(LAST_ACTIVITY_DATE)
from ACCOUNT
group by ACCOUNT_ID,AVAIL_BALANCE,OPEN_DATE;
If you're wanting the most recent row for each customer, think ROW_NUMBER(), not GROUP BY:
;With Numbered as (
select *,ROW_NUMBER() OVER (
PARTITION BY CUST_ID
ORDER BY LAST_ACTIVITY_DATE desc) rn
from Account
)
select ACCOUNT_ID,AVAIL_BALANCE,OPEN_DATE,LAST_ACTIVITY_DATE
from Numbered
where rn=1
I think you want to select one records having max(LAST_ACTIVITY_DATE) for each CUST_ID.
For this you can use TOP 1 WITH TIES like following.
SELECT TOP 1 WITH TIES account_id,
avail_balance,
open_date,
last_activity_date
FROM account
ORDER BY Row_number()
OVER (
partition BY cust_id
ORDER BY last_activity_date DESC)
Issue with your query is, you can't select non aggregated column in select if you don't specify those columns in group by
If you want to get the max activity date for a customer then your query should be as below
select CUST_ID, MAX(LAST_ACTIVITY_DATE)
from ACCOUNT
group by CUST_ID;
You can't select any other column which is not in the group by clause. The error message also giving the same message.
with query(CUST_ID, LAST_ACTIVITY_DATE) as
(
select
CUST_ID,
MAX(LAST_ACTIVITY_DATE) as LAST_ACTIVITY_DATE
from ACCOUNT
group by CUST_ID
)
select
a.ACCOUNT_ID,
a.AVAIL_BALANCE,
a.OPEN_DATE,
a.LAST_ACTIVITY_DATE
from ACCOUNT as a
inner join query as q
on a.CUST_ID = q.CUST_ID
and a.LAST_ACTIVITY_DATE = q.LAST_ACTIVITY_DATE

Unique vs MAX in SQL statement

I have a table with three columns:
PERSON
VISITOR
DATE
The table is basically a transactional table. The following is true:
There are multiple rows per person
There are multiple rows per visitor
There are multiple rows of a given person/visitor combination.
Assumed unique person/date combination
What I need is
I want visitor for each Person's MAX Date.
I cannot have multiple persons in the output.
Person must be unique.
visitor may repeat.
I have tried:
SELECT
ROW_NUMBER() OVER (PARTITION BY PERSON, VISITOR ORDER BY Date DESC) row_num,
PERSON,
VISITOR as VISITOR
FROM
`TABLE`
ORDER BY
PERSON
Maybe this... not sure I fully understand question. Sample data /expected results would help.
You said you wanted only the 1 person with the visitor per max date so the row_num of 1 will be the record w/ the max date. and since we partition by person it will not matter if person A had 3 visitors. only the person and their Most recent visitor will be listed.
WITH cte as (
SELECT ROW_NUMBER() OVER (PARTITION BY PERSON ORDER BY Date DESC) row_num
, PERSON
, VISITOR as VISITOR
FROM `TABLE`)
SELECT *
FROM cte
WHERE row_Num = 1
I think this can be done with a cross apply too though i'm not as good at using them yet...
SELECT A.Person, A.Visitor, A.Date
FROM table A
CROSS APPLY (SELECT TOP 1 *
FROM TABLE B
WHERE A.Person = B.Person
and A.Visitor = B.Visitor
and A.Date = B.Date
ORDER BY DATE DESC) C
Essentially the inner query runs for each record on the outer query; thus only the top most record will be returned thus the newest date.
select a.* from myTable as a inner join (
SELECT person, max(date) as maxDate from myTable group by person
) as b
on a.date = b.maxDate
and a.person = b.person;
I am weak in reading and writing English.
In my opinion the answer may be:
SELECT `PERSON`, `VISITOR`, MAX(`DATE`) AS `DATE`
FROM `TABLE`
GROUP BY `PERSON`, `VISITOR`;

GROUP BY date not datetime in SQL Server

I am trying to write a query to count every date in my database as you can see here :
SELECT
[SubmitDateTime],
COUNT(*)
FROM
[ParkingDB].[dbo].[Traffic]
GROUP BY
submitdatetime
The result is :
I think SQL Server is grouping my date based on date+time and it's my problem, but in fact I need to group them based on date. I use this type of query :
SELECT
[SubmitDateTime],
COUNT(*)
FROM
[ParkingDB].[dbo].[Traffic]
GROUP BY
CAST(myDateTime AS DATE)
But it doesn't work. I'm getting this error:
Msg 8120, Level 16, State 1, Line 3 Column
'ParkingDB.dbo.Traffic.SubmitDateTime' is invalid in the select list
because it is not contained in either an aggregate function or the
GROUP BY clause.
You also need to modify the columns in your SELECT statement:
SELECT
CAST([SubmitDateTime] AS DATE),
COUNT(*)
FROM [ParkingDB].[dbo].[Traffic]
GROUP BY
CAST([SubmitDateTime] AS DATE)
When using GROUP BY clause, all non-aggregated columns in the SELECT statement must appear in the GROUP BY clause.
Can you try the query below?
SELECT
CAST(myDateTime AS DATE) [SubmitDateTime],
COUNT(*)
FROM [ParkingDB].[dbo].[Traffic]
GROUP BY
CAST(myDateTime AS DATE)

Select a random database row based on another query

For internal control we would like to select a single random invoice for each of multiple invoice types and regions.
Here's the SQL to get a set of distinct Invoice Types and Regions
select InvoiceType,RegionID
from Invoices
group by InvoiceType, RegionID
For each row this returns I need to fetch a random row with that InvoiceType and RegionID. This is how I'm fetching random rows:
SELECT top 1
CustomerID
,InvoiceNum
,Name
FROM Invoices
JOIN Customers on Customers.CustomerID=Invoices.CustomerID
where InvoiceType=X and RegionID=Y
ORDER BY NEWID
But I don't know how to run this select statement foreach() row the first statement returns. I could do it programmatically but I would prefer an option using only a stored procedure as this query isn't supposed to need a program.
WITH cteInvoices AS (
SELECT CustomerID, InvoiceNum, Name,
ROW_NUMBER() OVER(PARTITION BY InvoiceType, RegionID ORDER BY NEWID()) AS RowNum
FROM Invoices
)
SELECT c.CustomerID, c.InvoiceNum, c.Name
FROM cteInvoices c
WHERE c.RowNum = 1;

Resources