Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rows into Columns

Status
Not open for further replies.

RJL1

Technical User
Oct 3, 2002
228
US
I have a query that return a list of carrier by date

Code:
DECLARE @STARTDATE   DATETIME
DECLARE @ENDDATE     DATETIME

SET @STARTDATE = '03/01/2011'
SET @ENDDATE   = '03/01/2011'
-----------------------------------------------------------
SELECT
------------------- SHIPMENT HEADER  -----------------------
'ACTUAL_SHIP_DATE_TIME' = CONVERT (VARCHAR(30),SH.ACTUAL_SHIP_DATE_TIME,101),
SH.WAREHOUSE,
SH.COMPANY,
SH.CARRIER
------------------------------------------------------------
FROM
SHIPMENT_HEADER SH WITH(NOLOCK)
------------------------------------------------------------
WHERE
SH.ACTUAL_SHIP_DATE_TIME IS NOT NULL
AND SH.COMPANY   = '317'
AND SH.WAREHOUSE = '029'
AND CONVERT (VARCHAR(30),SH.ACTUAL_SHIP_DATE_TIME,101)
    BETWEEN @STARTDATE AND @ENDDATE
------------------------------------------------------------

Query Results

Code:
DATE         WAREHOUSE   COMPANY    CARREIR

03/01/2011   29          317        CPUX
03/01/2011   29          317        CPUX
03/01/2011   29          317        PRONTO
03/01/2011   29          317        PRONTO
03/01/2011   29          317        CPUX
03/01/2011   29          317        FEDEX
03/01/2011   29          317        FEDEX
03/01/2011   29          317        FEDEX
03/01/2011   29          317        FEDEX
03/01/2011   29          317        GROUND

This would sum up to

GROUND = 1
PRONTO = 2
CPUX = 3
FEDEX= 4

I need to display this as

Code:
DATE         WAREHOUSE   COMPANY  GROUND PRONTO CPUX FEDEX
   
03/01/2011   29          317      1      2      3    4

What would be the best way to accomplish this with a list of carreir that can change fron day to day. Some day we could have 4 carreir some day 5-6.

Thanks
RJL

 
If you don't know your types in advance, then you're talking about dynamic PIVOT. Otherwise static pivot.

I also want to point out the problem with your date checks in the original query. Using CONVERT function makes your query non-sargable.

Rather than fixing the query for you, I'm giving you link by Aaron Bertrand that explains the date related queries

Bad habits to kick : mis-handling date / range queries


PluralSight Learning Library
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top