Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12345»»»

Returning a column per date in a range Expand / Collapse
Author
Message
Posted Friday, January 6, 2012 6:01 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, October 21, 2014 7:02 AM
Points: 12, Visits: 84
Hi

I need to take a set of records for people with hotel check-in/check-out dates, and display a table that has a column for each date in the range, with a 1 if they need a room that night, or 0 if they don't.

e.g.
PersonID,Name,Checkin,Checkout
1,Fred,2012-01-02,2012-01-05
2,Bob,2012-01-01,2012-01-04

would produce the result:

PersonID,Name,Jan 1 2012,Jan 2 2012,Jan 3 2012,Jan 4 2012,Jan 5 2012
1,Fred,0,1,1,1,0
2,Bob,1,1,1,0,0

(people need a room on the night they check in, but not on the night they check out).

I'm not sure where to start! It looks like something that pivots are meant to address, but don't fully understand them yet, a stored proc or a table-value function. I'm inclined to think the table-value function would give me the most flexibility as I could join PersonID to other tables to get more data about the people if needed.

Any suggestions/similar sample code would be much appreciated.

Nick
Post #1231401
Posted Friday, January 6, 2012 6:09 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, September 9, 2014 2:06 AM
Points: 1,768, Visits: 8,318
IMO , this sort of formatting should be dealt with at the client level,

use SSRS, excel or whatever to do this.




Clear Sky SQL
My Blog
Kent user group
Post #1231404
Posted Friday, January 6, 2012 6:11 AM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Today @ 8:52 AM
Points: 1,037, Visits: 6,844
nick-1043370 (1/6/2012)
Hi

I need to take a set of records for people with hotel check-in/check-out dates, and display a table that has a column for each date in the range, with a 1 if they need a room that night, or 0 if they don't.

e.g.
PersonID,Name,Checkin,Checkout
1,Fred,2012-01-02,2012-01-05
2,Bob,2012-01-01,2012-01-04

would produce the result:

PersonID,Name,Jan 1 2012,Jan 2 2012,Jan 3 2012,Jan 4 2012,Jan 5 2012
1,Fred,0,1,1,1,0
2,Bob,1,1,1,0,0

(people need a room on the night they check in, but not on the night they check out).

I'm not sure where to start! It looks like something that pivots are meant to address, but don't fully understand them yet, a stored proc or a table-value function. I'm inclined to think the table-value function would give me the most flexibility as I could join PersonID to other tables to get more data about the people if needed.

Any suggestions/similar sample code would be much appreciated.

Nick


Can you provide some more detail about the date range, Nick?
Will it always be a single month, starting at the 1st? = simple
Random number of days, starting at random DOM = harder.

Cheers



Low-hanging fruit picker and defender of the moggies





For better assistance in answering your questions, please read this.




Understanding and using APPLY, (I) and (II) Paul White

Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Post #1231406
Posted Friday, January 6, 2012 6:28 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, October 21, 2014 7:02 AM
Points: 12, Visits: 84
Dave - Fair point, but there's a bit of (dull) background as to why I'm looking down other paths...

As it happens we do it in SSRS at the moment, but to keep my post from confusing everyone I didn't mention that once I've got the data returned in column-per-date format I then want to do some calculations, such as room cost, total room cost for all people each night etc.

If I use an SSRS matrix/tablix then I really struggle to then do the calculations because there's no handle to grab on to for each date if the columns are generated at runtime. I would set fixed columns for each date, but need to produce this report quite regularly, for different date ranges each time!

I still want to use SSRS to deliver the results to the user at the end. It would just help if the query behind that report already had a column for each date.
Post #1231415
Posted Friday, January 6, 2012 6:32 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, October 21, 2014 7:02 AM
Points: 12, Visits: 84
Hi Chris

The bummer is it's a different date range each time! Ideally I'd like whatever code I use to get the date range in question first, i.e. find the min check-in date and max check-out date from the dataset, and show date columns accordingly.

I didn't think it would be easy!
Post #1231418
Posted Friday, January 6, 2012 6:41 AM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Today @ 8:52 AM
Points: 1,037, Visits: 6,844
nick-1043370 (1/6/2012)
Hi Chris

The bummer is it's a different date range each time! Ideally I'd like whatever code I use to get the date range in question first, i.e. find the min check-in date and max check-out date from the dataset, and show date columns accordingly.

I didn't think it would be easy!


It's surprisingly easy when you have sample data to work with

Please could you read the article linked to in my sig, Nick? You're new here - welcome aboard - the article will explain to you how best to pose a question for a speedy and accurate reply (which you've done) and how to set up easily-consumable sample data.

Cheers



Low-hanging fruit picker and defender of the moggies





For better assistance in answering your questions, please read this.




Understanding and using APPLY, (I) and (II) Paul White

Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Post #1231423
Posted Sunday, January 8, 2012 6:48 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 8:02 PM
Points: 35,397, Visits: 31,955
nick-1043370 (1/6/2012)
Hi

I need to take a set of records for people with hotel check-in/check-out dates, and display a table that has a column for each date in the range, with a 1 if they need a room that night, or 0 if they don't.

e.g.
PersonID,Name,Checkin,Checkout
1,Fred,2012-01-02,2012-01-05
2,Bob,2012-01-01,2012-01-04

would produce the result:

PersonID,Name,Jan 1 2012,Jan 2 2012,Jan 3 2012,Jan 4 2012,Jan 5 2012
1,Fred,0,1,1,1,0
2,Bob,1,1,1,0,0

(people need a room on the night they check in, but not on the night they check out).

I'm not sure where to start! It looks like something that pivots are meant to address, but don't fully understand them yet, a stored proc or a table-value function. I'm inclined to think the table-value function would give me the most flexibility as I could join PersonID to other tables to get more data about the people if needed.

Any suggestions/similar sample code would be much appreciated.

Nick


Ok... I'm confused. People would almost always need the room for the night they checkin and never need a room for the night they checkout. Why would BOB not need his room for the last two nights and why would Fred not need his room on the day of Checkin (according to the data you posted).

Also, where are you getting THAT bit of information from?


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1232175
Posted Monday, January 9, 2012 12:46 AM


SSCrazy Eights

SSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy EightsSSCrazy Eights

Group: General Forum Members
Last Login: 2 days ago @ 9:36 PM
Points: 9,927, Visits: 11,189
USE tempdb
-- Test data
CREATE TABLE dbo.Reservations
(
PersonID integer NOT NULL,
CheckIn date NOT NULL,
CheckOut date NOT NULL,

CHECK (CheckOut >= CheckIn)
)
GO
INSERT dbo.Reservations
(PersonID, CheckIn, CheckOut)
VALUES
(1, {D '2012-01-02'}, {D '2012-01-05'}),
(2, {D '2012-01-01'}, {D '2012-01-04'})

CREATE TABLE #Unpivoted
(
PersonID integer NOT NULL,
TheDate date NOT NULL,

PRIMARY KEY (TheDate, PersonID),
UNIQUE (PersonID, TheDate)
);

-- Standard in-line numbers table
WITH
N1 AS (SELECT N1.n FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS N1 (n)),
N2 AS (SELECT L.n FROM N1 AS L CROSS JOIN N1 AS R),
N3 AS (SELECT L.n FROM N2 AS L CROSS JOIN N2 AS R),
N4 AS (SELECT L.n FROM N3 AS L CROSS JOIN N3 AS R),
Numbers AS (SELECT ROW_NUMBER() OVER (ORDER BY @@SPID) AS n FROM N4)
-- Unpivot so there is one row per reservation date per person
INSERT #Unpivoted
(PersonID, TheDate)
SELECT
R.PersonID,
Occupied.TheDate
FROM dbo.Reservations AS R
CROSS APPLY
(
SELECT TOP(DATEDIFF(DAY, R.CheckIn, R.CheckOut))
DATEADD(DAY,Numbers.n - 1, R.CheckIn)
FROM Numbers
ORDER BY
Numbers.n
) AS Occupied (TheDate)

-- Dynamic SQL for the cross-tab
DECLARE
@SQL nvarchar(max) =
N'SELECT U.PersonID ' +
(
-- Construct the dynamic pivot
SELECT
N',SUM(CASE WHEN U.TheDate = ''' +
CA.date_string +
N''' THEN 1 ELSE 0 END) AS ' +
QUOTENAME(CA.date_string)
FROM
(
-- Unique dates in the unpivoted set
SELECT
U.TheDate,
CONVERT(char(8), U.TheDate, 112) AS date_string
FROM #Unpivoted AS U
GROUP BY U.TheDate
) AS CA
ORDER BY
CA.TheDate
FOR XML
PATH (''), TYPE
).value('./text()[1]', 'NVARCHAR(MAX)') +
N' FROM #Unpivoted AS U GROUP BY U.PersonID'

-- For debugging
SELECT @SQL

-- Return results
EXECUTE (@SQL)

-- Tidy up
DROP TABLE #Unpivoted
DROP TABLE dbo.Reservations

Output:




Paul White
SQL Server MVP
SQLblog.com
@SQL_Kiwi


  Post Attachments 
Forum.png (315 views, 2.81 KB)
Post #1232227
Posted Monday, January 9, 2012 7:04 AM
Say Hey Kid

Say Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey Kid

Group: General Forum Members
Last Login: Yesterday @ 10:35 AM
Points: 662, Visits: 513
Jeff Moden (1/8/2012)
Ok... I'm confused. People would almost always need the room for the night they checkin and never need a room for the night they checkout. Why would BOB not need his room for the last two nights and why would Fred not need his room on the day of Checkin (according to the data you posted).

Jeff, The OP's data is fine, as is his result set. The thing here is that he wants a column for each day in the report range, whether people were using rooms or not. Thus the 1's and 0's in his output data are correct - Fred checked in on 2nd, NOT the first day of the report.
Post #1232393
Posted Monday, January 9, 2012 10:28 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 8:02 PM
Points: 35,397, Visits: 31,955
Agh! I totally misread the dates, Bob. Thank you for the correction. More coffee, please.

With that little revelation, it looks like Paul sussed the problem with his code.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1232914
« Prev Topic | Next Topic »

Add to briefcase 12345»»»

Permissions Expand / Collapse