Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

sql server - SQL First and Last Transaction Report

I have a table in SQL, that looks a little similar to the table below:

[enter image description here]1

My goal is to generate a first and Last Transaction report. I want to know when did customer X make their first purchase and what is the date of their most recent purchase. I would like to group my results by Store and add all the transaction if they happen on the same day.

For instance, if John do made 2 expenses at walmart on Jan 15th and that's their most recent transaction, I would like those two expenses to be Summed in my report.

Here is the final result I'd expect from a table like on the example above:

[enter image description here]2

With what I have tried so far, I am only getting 1 value back

The SQL looks a little similar to

Select 
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store
From transaction
GROUp by 
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store

I know I have to use some types of nested query to get the result(maybe) but I have been unsuccessful.

question from:https://stackoverflow.com/questions/65852015/sql-first-and-last-transaction-report

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

here is one way , double group by :

SELECT
    SN    , SID    , CustomerName    , BankAccount    , store
    , MIN(TransDate) firsttrans
    , MAX(TransDate) lasttrans
    , price          lasttransprice
FROM
    (
        SELECT
            SN, SID , CustomerName, BankAccount, store , TransDate
            , SUM(price) price
        FROM
            TRANSACTION
        GROUP BY
            SN, SID, CustomerName, BankAccount, TransDate, store
    ) xx
GROUP BY
    SN, SID, CustomerName, BankAccount, store, price

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...