SQL statement exercise instance 3 average sales wait time

Source: Internet
Author: User
There is a Sales table with two columns: Sales date and customer. a SQL statement is required for calculation.

There is a Sales table with two columns: Sales date and customer. a SQL statement is required for calculation.

The Code is as follows:
--- 1. average sales wait time
--- There is a Sales table with two columns: Sales date and customer. a SQL statement is required for calculation.
-- Average number of days between two purchases by each customer
-- Assume that the same person will not buy twice a day
Create table sales
(
Custname varchar (10) not null,
Saledate datetime not null
)
Go
Insert sales
Select 'zhang san', '2014-1-1-1 'union
Select 'zhang san', '2017-11-1 'union
Select 'zhang san', '2014-1-1-1 'union
Select 'wang 5', '2017-2-1 'union
Select 'wang 5', '2017-4-1 'union
Select 'Li si', '2014-1-1-1 'union
Select 'Li si', '2017-5-1 'union
Select 'Li si', '2014-9-1 'union
Select 'Li si', '2014-1-1-1 'union
Select 'zhao 6', '2014-1-1-1 'union
Select 'Qian tu', '2014-1-1-1 'union
Select 'qiantu ', '2017-3-1' union
Select 'zhang san', '2017-9-1'
Go
Select custname, DATEDIFF (d, min (saledate), max (saledate)/(COUNT (*)-1) as avgday
From sales
Group by custname
Having count (*)> 1
Go
Select custname, case when count (*)> 1 then DATEDIFF (d, min (saledate), max (saledate)/(COUNT (*)-1)
Else DATEDIFF (d, min (saledate), max (saledate) end
As avgday
From sales
Group by custname
-- Having count (*)> 1
Go
Drop table sales

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.