简体   繁体   中英

Getting first week of date in mysql

I have a lot of table and i need to get the gross income of a movie, now my problem is i don't know how to get the sum of first week only of a movie.

This is what i need.

+-------------------------------------------+
|    title  |   Week one      |  Week one   |
|           |   (Wed-Sun)     | (Mon-Tue)   |
+-------------------------------------------+
| title 1   | 50000           |    10000    |
+-------------------------------------------+

If the starting show of a movie is wed then i should make 3 column, first column is title , second column is the wed-sun and third is mon-tue .

Is this possible to query like select movie, sum(wed-sun), sum(mon-tue) Thanks in advance

This is my answer based on how I understand your question.

SELECT movie, sum(wed-sun), sum(mon-tue) CONVERT(date, getdate()) as day
FROM thetable
WHERE thedate(BETWEEN first AND last) 
GROUP BY day

You can user DAYOFWEEK() if you are using date type for that. See http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_dayofweek

For week days from mon-tue

SUM(CASE WHEN DAYOFWEEK(DATE)=2 THEN 1 WHEN DAYOFWEEK(DATE)=3 THEN 1 ELSE 0 END)

For week days from wed-sun

SUM(CASE WHEN DAYOFWEEK(DATE)=4 THEN 1 WHEN DAYOFWEEK(DATE)=5 THEN 1 WHEN DAYOFWEEK(DATE)=6 THEN 1 WHEN DAYOFWEEK(DATE)=7 THEN 1 WHEN DAYOFWEEK(DATE)=1 THEN 1 ELSE 0 END)

If you use WEEKDAY instead of DAYOFWEEK you can shorten the case statements:

SELECT
     movie_id, 
     title,
     SUM(CASE WHEN WEEKDAY(date_field) < 2 THEN field_to_sum ELSE 0 END) `mon-tue`,
     SUM(CASE WHEN WEEKDAY(date_field) > 1 THEN field_to_sum ELSE 0 END) `wed-sun`
FROM
    movies
/* optional WHERE */
GROUP_BY movie_id

Obviously you want WEEKDAY FUNCTION , it returns the weekday index starting from 0-Monday.

Assume you have table Movies with title and starting_show_date columns, and value_table with action_date and amount columns.

You can sum amount by splitting amounts to two parts like this:

select
    movies.title,
    sum(case when value_table.action_date
        < dateadd(movies.starting_show_date , interval  7 -WEEKDAY(movies.starting_show_date) day)
             then value_table.amount else 0 end) as FirstWeek,
    sum(case when value_table.action_date
        >= dateadd(movies.starting_show_date , interval  7 -WEEKDAY(movies.starting_show_date) day)
             then value_table.amount else 0 end) as OtherWeeks
from
    movies
inner join
    value_table
on
    movies.id = value_table.movie_id
group by 
    movies.title

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