简体   繁体   中英

Perfoming SQL query or stored procedure?

We have some data that looks like this:

***listing_id,log_date,event***
2112,<date>,stage_1
2112,<date>,stage_2
2112,<date>,sold
2113,<date>,stage_1
2113,<date>,stage_6
2114,<date>,stage_1
2114,<date>,sold

I want to get listing_id, the duration(max_date - min_date) for which it is listed in case it's sold.

How do I achieve these reuslts when my data store is a MS SQL server?

GROUP BY and DATEDIFF along with a few CASE should do

select
    listing_id,
    datediff(dd, min(log_date),
        case
            when count(case when event = 'sold' then 1 end) > 0 then
                max(case when event = 'sold' then log_date end)
            else
                max(log_date)
        end
    ) duration,
    case 
        when count(case when event = 'sold' then 1 end) > 0 then 
            'Yes'
        else
            'No'
    end was_sold
from your_table
group by
    listing_id
;

You can use the below if you want to get the earliest sold date

min(case when event = 'sold' then log_date end)

datediff(dd,....) return difference in days. For more info, check this out

Not really enough detail in your question so I am guessing but maybe something like;

SELECT 
    listing_id,
    MIN(log_date) AS Start,
    MAX(log_date) AS Finish,
    datediff(day, MIN(log_date), MAX(log_date) AS Duration
FROM YourTable
GROUP BY 
    listing_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM