Days between two days by month SQLBest table schema to store daily hits for many items?calculate days and...
When distributing a Linux kernel driver as source code, what's the difference between Proprietary and GPL license?
Multiple null checks in Java 8
If I have Haste cast on me, does it reduce the casting time for my spells that normally take more than a turn to cast?
How does holding onto an active but un-used credit card affect your ability to get a loan?
Manager has noticed coworker's excessive breaks. Should I warn him?
Why do we interpret the accelerated expansion of the universe as the proof for the existence of dark energy?
Boss asked me to sign a resignation paper without a date on it along with my new contract
In the Lost in Space intro why was Dr. Smith actor listed as a special guest star?
What does it mean when an external ID field follows a DML Statement?
How to know if I am a 'Real Developer'
Coworker is trying to get me to sign his petition to run for office. How to decline politely?
Why are "square law" devices important?
Why write a book when there's a movie in my head?
SQL Server 2017 crashes when backing up because filepath is wrong
Build ASCII Podiums
Can I legally make a website about boycotting a certain company?
Is it Safe to Plug an Extension Cord Into a Power Strip?
Exploding Numbers
How do I handle a blinded enemy which wants to attack someone it's sure is there?
Draw triangle with text in vertices/edges
Can I do anything else with aspersions other than cast them?
Buying a "Used" Router
Integral problem. Unsure of the approach.
What does "don't have a baby" imply or mean in this sentence?
Days between two days by month SQL
Best table schema to store daily hits for many items?calculate days and equally distribute remainingWhat is the best way to get all data for a date range, plus the last event just before the range?Get Date LimitationDate Range Limit SQLFind the days difference between two dates per monthConverting Monthly Rolling SUM (YTD) back to Monthly numbersFilling Empty Values when Calculating Standard DeviationDays in between two dates group by monthcalculate count by month and year
I have a new job where I am re-learning SQL (oh the joy) after years of not using it.
I currently have a table that looks something like this:
RoomNumber,
BlockID,
ModelEndDate,
DepartureDate,
DATEDIFF(DAY, StartDate, EndDate) AS NumDays
So essentially there is a model applied to each room, which has an enddate. If a resident leaves early we set the DepartureDate
and calculate how many days left in the Model.
EDIT Some background on how this actually is calculated (as I should have probably included it). Each room is occupied at different periods throughout the year, and has associated models to show what those dates are. E.g. one room may have the following:
ModelStartDate,
ModelEndDate,
Period
As a fairly standard rule of thumb, each room usually has three periods. I currently just calculate the total number of free days by either working out the difference between the start and end dates or (if departure is mid-model) I would work out the difference between the DepartureDate and ModelEndDate. I then group by Room giving me the totalfreedays.
What I now need to do is work out how these days are spread by month per block (many rooms to a block). So, if somebody was to Depart very early in the year, they would free up a load of days in each month for that room. For financial reporting I want to be able to say how many free days, per month, per block (summing all rooms within the Block). Ideally I would like a table that looks like the following:
BlockID,
DaysFreeSept,
DaysFreeOct,
DaysFreeNov
etc
I am having a little trouble understanding how I should accomplish this, I have looked through a few answers on here but they are mighty confusing.
Cheers for any help you can give me.
This is on SQL Server 2008 R2 (10.50)
sql-server sql-server-2008-r2
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
I have a new job where I am re-learning SQL (oh the joy) after years of not using it.
I currently have a table that looks something like this:
RoomNumber,
BlockID,
ModelEndDate,
DepartureDate,
DATEDIFF(DAY, StartDate, EndDate) AS NumDays
So essentially there is a model applied to each room, which has an enddate. If a resident leaves early we set the DepartureDate
and calculate how many days left in the Model.
EDIT Some background on how this actually is calculated (as I should have probably included it). Each room is occupied at different periods throughout the year, and has associated models to show what those dates are. E.g. one room may have the following:
ModelStartDate,
ModelEndDate,
Period
As a fairly standard rule of thumb, each room usually has three periods. I currently just calculate the total number of free days by either working out the difference between the start and end dates or (if departure is mid-model) I would work out the difference between the DepartureDate and ModelEndDate. I then group by Room giving me the totalfreedays.
What I now need to do is work out how these days are spread by month per block (many rooms to a block). So, if somebody was to Depart very early in the year, they would free up a load of days in each month for that room. For financial reporting I want to be able to say how many free days, per month, per block (summing all rooms within the Block). Ideally I would like a table that looks like the following:
BlockID,
DaysFreeSept,
DaysFreeOct,
DaysFreeNov
etc
I am having a little trouble understanding how I should accomplish this, I have looked through a few answers on here but they are mighty confusing.
Cheers for any help you can give me.
This is on SQL Server 2008 R2 (10.50)
sql-server sql-server-2008-r2
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24
add a comment |
I have a new job where I am re-learning SQL (oh the joy) after years of not using it.
I currently have a table that looks something like this:
RoomNumber,
BlockID,
ModelEndDate,
DepartureDate,
DATEDIFF(DAY, StartDate, EndDate) AS NumDays
So essentially there is a model applied to each room, which has an enddate. If a resident leaves early we set the DepartureDate
and calculate how many days left in the Model.
EDIT Some background on how this actually is calculated (as I should have probably included it). Each room is occupied at different periods throughout the year, and has associated models to show what those dates are. E.g. one room may have the following:
ModelStartDate,
ModelEndDate,
Period
As a fairly standard rule of thumb, each room usually has three periods. I currently just calculate the total number of free days by either working out the difference between the start and end dates or (if departure is mid-model) I would work out the difference between the DepartureDate and ModelEndDate. I then group by Room giving me the totalfreedays.
What I now need to do is work out how these days are spread by month per block (many rooms to a block). So, if somebody was to Depart very early in the year, they would free up a load of days in each month for that room. For financial reporting I want to be able to say how many free days, per month, per block (summing all rooms within the Block). Ideally I would like a table that looks like the following:
BlockID,
DaysFreeSept,
DaysFreeOct,
DaysFreeNov
etc
I am having a little trouble understanding how I should accomplish this, I have looked through a few answers on here but they are mighty confusing.
Cheers for any help you can give me.
This is on SQL Server 2008 R2 (10.50)
sql-server sql-server-2008-r2
I have a new job where I am re-learning SQL (oh the joy) after years of not using it.
I currently have a table that looks something like this:
RoomNumber,
BlockID,
ModelEndDate,
DepartureDate,
DATEDIFF(DAY, StartDate, EndDate) AS NumDays
So essentially there is a model applied to each room, which has an enddate. If a resident leaves early we set the DepartureDate
and calculate how many days left in the Model.
EDIT Some background on how this actually is calculated (as I should have probably included it). Each room is occupied at different periods throughout the year, and has associated models to show what those dates are. E.g. one room may have the following:
ModelStartDate,
ModelEndDate,
Period
As a fairly standard rule of thumb, each room usually has three periods. I currently just calculate the total number of free days by either working out the difference between the start and end dates or (if departure is mid-model) I would work out the difference between the DepartureDate and ModelEndDate. I then group by Room giving me the totalfreedays.
What I now need to do is work out how these days are spread by month per block (many rooms to a block). So, if somebody was to Depart very early in the year, they would free up a load of days in each month for that room. For financial reporting I want to be able to say how many free days, per month, per block (summing all rooms within the Block). Ideally I would like a table that looks like the following:
BlockID,
DaysFreeSept,
DaysFreeOct,
DaysFreeNov
etc
I am having a little trouble understanding how I should accomplish this, I have looked through a few answers on here but they are mighty confusing.
Cheers for any help you can give me.
This is on SQL Server 2008 R2 (10.50)
sql-server sql-server-2008-r2
sql-server sql-server-2008-r2
edited Nov 2 '16 at 11:07
user958551
asked Nov 2 '16 at 9:27
user958551user958551
112
112
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24
add a comment |
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24
add a comment |
2 Answers
2
active
oldest
votes
Making the following assumptions:
- Month is calculated from ModelEndDate
- Days free is calculated by summing CAST(ModelEndDate - DepartureDate AS INT)
WITH room AS (
SELECT BlockID,
ModelEndMonth = DATEADD(MONTH,DATEDIFF(MONTH,'19000101',ModelEndDate),'19000101'),
DaysFree = DATEDIFF(DAY,DepartureDate,ModelEndDate))
SELECT BlockID,
ModelEndMonth,
DaysFree = SUM(DaysFree)
FROM dbo.YourTable
GROUP BY BlockID,
ModelEndMonth;
This code sample will get you part way there (apologies for any syntax errors but I am writing free-hand without a schema to query). You would then need to PIVOT the output to achieve the result-set in your required format. See PIVOT on Technet for an example.
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of theModelEndDate
(great stuff) and then calculating how many Months between theModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of theModelEndDate
?
– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out theTotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if theDepartureDate
is between the start and end date of the model, if it is I sum the days between theDepartureDate
and theModelEndDate
if not I sum the days between theModelStartDate
andModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.
– user958551
Nov 2 '16 at 11:00
add a comment |
This is a situation that might benefit from use of a date table. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Then you can join on the date table for all dates between the DepartureDate and the ModelEndDate, something like this:
Select y.BlockID,
DaysFreeJan = Sum(CASE WHEN d.MonthName = 'January' THEN 1 END),
DaysFreeFeb = Sum(CASE WHEN d.MonthName = 'February'THEN 1 END),
...
From dbo.YourTable As y
Join dbo.DateTable On d
On y.DepartureDate < d.DateKey
And y.ModelEndDate >= d.DateKey
Group By y.BlockID;
So each row of your table will join to multiple rows in your date table, then this query counts how many of those rows there are in each month.
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "182"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f153996%2fdays-between-two-days-by-month-sql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Making the following assumptions:
- Month is calculated from ModelEndDate
- Days free is calculated by summing CAST(ModelEndDate - DepartureDate AS INT)
WITH room AS (
SELECT BlockID,
ModelEndMonth = DATEADD(MONTH,DATEDIFF(MONTH,'19000101',ModelEndDate),'19000101'),
DaysFree = DATEDIFF(DAY,DepartureDate,ModelEndDate))
SELECT BlockID,
ModelEndMonth,
DaysFree = SUM(DaysFree)
FROM dbo.YourTable
GROUP BY BlockID,
ModelEndMonth;
This code sample will get you part way there (apologies for any syntax errors but I am writing free-hand without a schema to query). You would then need to PIVOT the output to achieve the result-set in your required format. See PIVOT on Technet for an example.
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of theModelEndDate
(great stuff) and then calculating how many Months between theModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of theModelEndDate
?
– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out theTotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if theDepartureDate
is between the start and end date of the model, if it is I sum the days between theDepartureDate
and theModelEndDate
if not I sum the days between theModelStartDate
andModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.
– user958551
Nov 2 '16 at 11:00
add a comment |
Making the following assumptions:
- Month is calculated from ModelEndDate
- Days free is calculated by summing CAST(ModelEndDate - DepartureDate AS INT)
WITH room AS (
SELECT BlockID,
ModelEndMonth = DATEADD(MONTH,DATEDIFF(MONTH,'19000101',ModelEndDate),'19000101'),
DaysFree = DATEDIFF(DAY,DepartureDate,ModelEndDate))
SELECT BlockID,
ModelEndMonth,
DaysFree = SUM(DaysFree)
FROM dbo.YourTable
GROUP BY BlockID,
ModelEndMonth;
This code sample will get you part way there (apologies for any syntax errors but I am writing free-hand without a schema to query). You would then need to PIVOT the output to achieve the result-set in your required format. See PIVOT on Technet for an example.
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of theModelEndDate
(great stuff) and then calculating how many Months between theModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of theModelEndDate
?
– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out theTotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if theDepartureDate
is between the start and end date of the model, if it is I sum the days between theDepartureDate
and theModelEndDate
if not I sum the days between theModelStartDate
andModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.
– user958551
Nov 2 '16 at 11:00
add a comment |
Making the following assumptions:
- Month is calculated from ModelEndDate
- Days free is calculated by summing CAST(ModelEndDate - DepartureDate AS INT)
WITH room AS (
SELECT BlockID,
ModelEndMonth = DATEADD(MONTH,DATEDIFF(MONTH,'19000101',ModelEndDate),'19000101'),
DaysFree = DATEDIFF(DAY,DepartureDate,ModelEndDate))
SELECT BlockID,
ModelEndMonth,
DaysFree = SUM(DaysFree)
FROM dbo.YourTable
GROUP BY BlockID,
ModelEndMonth;
This code sample will get you part way there (apologies for any syntax errors but I am writing free-hand without a schema to query). You would then need to PIVOT the output to achieve the result-set in your required format. See PIVOT on Technet for an example.
Making the following assumptions:
- Month is calculated from ModelEndDate
- Days free is calculated by summing CAST(ModelEndDate - DepartureDate AS INT)
WITH room AS (
SELECT BlockID,
ModelEndMonth = DATEADD(MONTH,DATEDIFF(MONTH,'19000101',ModelEndDate),'19000101'),
DaysFree = DATEDIFF(DAY,DepartureDate,ModelEndDate))
SELECT BlockID,
ModelEndMonth,
DaysFree = SUM(DaysFree)
FROM dbo.YourTable
GROUP BY BlockID,
ModelEndMonth;
This code sample will get you part way there (apologies for any syntax errors but I am writing free-hand without a schema to query). You would then need to PIVOT the output to achieve the result-set in your required format. See PIVOT on Technet for an example.
edited Nov 2 '16 at 10:49
answered Nov 2 '16 at 10:06
Andy JonesAndy Jones
1,24148
1,24148
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of theModelEndDate
(great stuff) and then calculating how many Months between theModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of theModelEndDate
?
– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out theTotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if theDepartureDate
is between the start and end date of the model, if it is I sum the days between theDepartureDate
and theModelEndDate
if not I sum the days between theModelStartDate
andModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.
– user958551
Nov 2 '16 at 11:00
add a comment |
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of theModelEndDate
(great stuff) and then calculating how many Months between theModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of theModelEndDate
?
– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out theTotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if theDepartureDate
is between the start and end date of the model, if it is I sum the days between theDepartureDate
and theModelEndDate
if not I sum the days between theModelStartDate
andModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.
– user958551
Nov 2 '16 at 11:00
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of the
ModelEndDate
(great stuff) and then calculating how many Months between the ModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of the ModelEndDate
?– user958551
Nov 2 '16 at 10:37
Absolutely no need to apologise when you are offering help. Thanks for your time! Conceptually, what is the WITH function at the beginning doing? Looking at it I would guess that it is taking the end part of the
ModelEndDate
(great stuff) and then calculating how many Months between the ModelEndDate
and the date given to it. I am just slightly confused how that will then result in what I need, won't that just group the total free days by the month of the ModelEndDate
?– user958551
Nov 2 '16 at 10:37
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
The WITH is a common table expression to avoid having to write the ModelEndMonth logic twice, once in the select list and once in the group by. ModelEndMonth was based on one of my listed assumptions as I wasn't sure from the question what you meant by month. So when you say DaysFreeSept, what is meant by Sept? i.e. what logic to you apply to your data to work out Sept?
– Andy Jones
Nov 2 '16 at 10:51
So, I currently just work out the
TotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if the DepartureDate
is between the start and end date of the model, if it is I sum the days between the DepartureDate
and the ModelEndDate
if not I sum the days between the ModelStartDate
and ModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.– user958551
Nov 2 '16 at 11:00
So, I currently just work out the
TotalFreeDays
across a few DateModels (each room actually has between 3 and 12 models), which is fairly simple, I check if the DepartureDate
is between the start and end date of the model, if it is I sum the days between the DepartureDate
and the ModelEndDate
if not I sum the days between the ModelStartDate
and ModelEndDate
. I then group by room which produces a list of rooms and their Totalfreedays. I was just looking for some logic that could split that query into how many days were in march, how many in april etc.– user958551
Nov 2 '16 at 11:00
add a comment |
This is a situation that might benefit from use of a date table. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Then you can join on the date table for all dates between the DepartureDate and the ModelEndDate, something like this:
Select y.BlockID,
DaysFreeJan = Sum(CASE WHEN d.MonthName = 'January' THEN 1 END),
DaysFreeFeb = Sum(CASE WHEN d.MonthName = 'February'THEN 1 END),
...
From dbo.YourTable As y
Join dbo.DateTable On d
On y.DepartureDate < d.DateKey
And y.ModelEndDate >= d.DateKey
Group By y.BlockID;
So each row of your table will join to multiple rows in your date table, then this query counts how many of those rows there are in each month.
add a comment |
This is a situation that might benefit from use of a date table. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Then you can join on the date table for all dates between the DepartureDate and the ModelEndDate, something like this:
Select y.BlockID,
DaysFreeJan = Sum(CASE WHEN d.MonthName = 'January' THEN 1 END),
DaysFreeFeb = Sum(CASE WHEN d.MonthName = 'February'THEN 1 END),
...
From dbo.YourTable As y
Join dbo.DateTable On d
On y.DepartureDate < d.DateKey
And y.ModelEndDate >= d.DateKey
Group By y.BlockID;
So each row of your table will join to multiple rows in your date table, then this query counts how many of those rows there are in each month.
add a comment |
This is a situation that might benefit from use of a date table. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Then you can join on the date table for all dates between the DepartureDate and the ModelEndDate, something like this:
Select y.BlockID,
DaysFreeJan = Sum(CASE WHEN d.MonthName = 'January' THEN 1 END),
DaysFreeFeb = Sum(CASE WHEN d.MonthName = 'February'THEN 1 END),
...
From dbo.YourTable As y
Join dbo.DateTable On d
On y.DepartureDate < d.DateKey
And y.ModelEndDate >= d.DateKey
Group By y.BlockID;
So each row of your table will join to multiple rows in your date table, then this query counts how many of those rows there are in each month.
This is a situation that might benefit from use of a date table. https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Then you can join on the date table for all dates between the DepartureDate and the ModelEndDate, something like this:
Select y.BlockID,
DaysFreeJan = Sum(CASE WHEN d.MonthName = 'January' THEN 1 END),
DaysFreeFeb = Sum(CASE WHEN d.MonthName = 'February'THEN 1 END),
...
From dbo.YourTable As y
Join dbo.DateTable On d
On y.DepartureDate < d.DateKey
And y.ModelEndDate >= d.DateKey
Group By y.BlockID;
So each row of your table will join to multiple rows in your date table, then this query counts how many of those rows there are in each month.
answered Nov 2 '16 at 11:40
mendosimendosi
1,974520
1,974520
add a comment |
add a comment |
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f153996%2fdays-between-two-days-by-month-sql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Suggest you don't do integer math on date types. Try DATEDIFF (Transact-SQL)
– Michael Green
Nov 2 '16 at 10:24