473,770 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to wrap a UNION query in a totals query?

I've got some SQL that works as far as returning a recordset from a series of
UNION statements.

viz:

SELECT whatever
UNION this
UNION that
UNION other

Now I want to group and sum on it's results.

Started out tying:

SELECT * FROM
(
union stuff
)

....but couldn't even get past the syntax check.
Where I'm headed is a sort of pivot table presentation of some hours data
associated with various projects with a column for each of six date ranges.

Bottom line: can somebody give me a pointer to the syntax needed to wrap those
UNION statements and then select/group/sum their results?
--
PeteCresswell
Jul 20 '05 #1
9 5507
Hi Pete

It is always best to post the DDL (create table statements), example data
(as insert statements), expected output and your current attempts.

There are loads of posts regarding Pivot tables/CrossTabs such as
http://tinyurl.com/i9mt

At a guess you are also trying to create a derived table such as

SELECT Col1, COUNT(*)
FROM ( SELECT 1 as Col1
UNION ALL SELECT 1
UNION ALL SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 2
UNION ALL SELECT 3 ) A
GROUP BY Col1

John

"(Pete Cresswell)" <x@y.z> wrote in message
news:o0******** *************** *********@4ax.c om...
I've got some SQL that works as far as returning a recordset from a series of UNION statements.

viz:

SELECT whatever
UNION this
UNION that
UNION other

Now I want to group and sum on it's results.

Started out tying:

SELECT * FROM
(
union stuff
)

...but couldn't even get past the syntax check.
Where I'm headed is a sort of pivot table presentation of some hours data
associated with various projects with a column for each of six date ranges.
Bottom line: can somebody give me a pointer to the syntax needed to wrap those UNION statements and then select/group/sum their results?
--
PeteCresswell

Jul 20 '05 #2
RE/
It is always best to post the DDL (create table statements), example data
(as insert statements), expected output and your current attempts.


I was trying for brevity in hopes of not depressing anybody...-)

Remember, you asked for it....

I've given up on the UNION statements - partially because they create such a
monster and I'm finding that "Divide and conquer" is the best approach for me:
do things in smaller, testable steps and then put the steps together.

Accordingly, I'm replacing the UNION with a work table and a series of queries
that populates it.

Were I'm at now is below. My current problem is coalescing the dates into the
single-record-per-project result. I'm guessing that I'll wind up creating
another temp table with a PeriodID, BeginDate, and EndDate and then, instead of
trying to Sum() the dates (a no-no...) I'll just convert them to a PeriodID and
join to the dates temp table at the very end to recover them.

Don't anybody get *too* indignant about this code: I'm a newbie and still
groping around....

-------------------------------------------------------------------------
--PURPOSE: To return the two recordsets to be used in loading
-- the Estimate edit screen or the work tables behind
-- an Estimate report:
-- > A single header rec with department, person's name, and so-forth
-- > Many records for various projects/estimating periods. These
records
-- are in a sort of pivot table presentation with one column for each
-- date range. i.e. one row contains data from many weeks reported.
--ACCEPTS: - PersonID of person doing the estimating
-- - A flag telling what the data is to be used for:
-- 1 = To Print a report
-- 2 = To load the estimate edit screen
-- - 12 dates: One for each first and last date in each estimating
period
--USED BY: rptEstimate..., frmEstimate

CREATE PROCEDURE spTimeSheet_Loa d
@PersonID int,
@UsedFor int,
@BeginDate1 datetime,
@EndDate1 datetime,
@BeginDate2 datetime,
@EndDate2 datetime,
@BeginDate3 datetime,
@EndDate3 datetime,
@BeginDate4 datetime,
@EndDate4 datetime,
@BeginDate5 datetime,
@EndDate5 datetime,
@BeginDate6 datetime,
@EndDate6 datetime,
AS

DECLARE @ErrNoData int,
@EstimatesFound Ct int,

-- --------------------------------------------------------------------
-- We don't know how to do figurative constants in TSQL, so we
-- do our own little workaround to avoid "magic numbers"
-- in the code

DECLARE @UsedForPrint int
DECLARE @UsedForLoad int
DECLARE @WeekType_Estim ate int

SET @UsedForPrint =1
SET @UsedForLoad =2
SET @ErrNoData =999
SET @WeekType_Estim ate =2

-- --------------------------------------------------------------------
-- See if there is any info for the Person/Dates in question
-- Bail out if not

SELECT @EstimatesFound Ct =
(
SELECT COUNT(*) FROM tblWeekReported
WHERE ((tblWeekReport ed.PersonID=@Pe rsonID) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(
(tblWeekReporte d.BeginDate=@Be ginDate1 AND
tblWeekReported .EndDate=@EndDa te1) OR
(tblWeekReporte d.BeginDate=@Be ginDate2 AND
tblWeekReported .EndDate=@EndDa te2) OR
(tblWeekReporte d.BeginDate=@Be ginDate3 AND
tblWeekReported .EndDate=@EndDa te3) OR
(tblWeekReporte d.BeginDate=@Be ginDate4 AND
tblWeekReported .EndDate=@EndDa te4) OR
(tblWeekReporte d.BeginDate=@Be ginDate5 AND
tblWeekReported .EndDate=@EndDa te5) OR
(tblWeekReporte d.BeginDate=@Be ginDate6 AND
tblWeekReported .EndDate=@EndDa te6)
)
)
)

IF ((@UsedFor = @UsedForPrint) AND (@EstimatesFoun dCt = 0))
RETURN @ErrNoData
-- --------------------------------------------------------------------
-- Set a parameter that prevents our work table create/populate operations
-- from appending unwanted recordsets to the output

SET NOCOUNT ON

-- =============== =============== =============== =============== ========
-- Create our work tables

-- ------------------
-- 1) Create a work table that will receive a pivoted version of our
-- data: up to six "WeekReport ed" periods per line

IF OBJECT_ID('temp db..#Extract1') IS NOT NULL DROP TABLE #Extract1;
CREATE TABLE #Extract1
(
WeekReportedLin eID int,
ProjectID int,

WeekReportedID_ Period1 int,
WeekReportedID_ Period2 int,
WeekReportedID_ Period3 int,
WeekReportedID_ Period4 int,
WeekReportedID_ Period5 int,
WeekReportedID_ Period6 int,

HoursAvailable_ Period1 Float,
HoursAvailable_ Period2 Float,
HoursAvailable_ Period3 Float,
HoursAvailable_ Period4 Float,
HoursAvailable_ Period5 Float,
HoursAvailable_ Period6 Float,

BeginDate_Perio d1 DateTime,
BeginDate_Perio d2 DateTime,
BeginDate_Perio d3 DateTime,
BeginDate_Perio d4 DateTime,
BeginDate_Perio d5 DateTime,
BeginDate_Perio d6 DateTime,

EndDate_Period1 DateTime,
EndDate_Period2 DateTime,
EndDate_Period3 DateTime,
EndDate_Period4 DateTime,
EndDate_Period5 DateTime,
EndDate_Period6 DateTime,

Hours_Period1 Float,
Hours_Period2 Float,
Hours_Period3 Float,
Hours_Period4 Float,
Hours_Period5 Float,
Hours_Period6 Float
);

-- ------------------
-- 2) Create a work table like the first one, whose mission in life
-- is to receive summed data from the first one.

IF OBJECT_ID('temp db..#Extract2') IS NOT NULL DROP TABLE #Extract2;
CREATE TABLE #Extract2
(
ProjectID int,

WeekReportedID_ Period1 int,
WeekReportedID_ Period2 int,
WeekReportedID_ Period3 int,
WeekReportedID_ Period4 int,
WeekReportedID_ Period5 int,
WeekReportedID_ Period6 int,

HoursAvailable_ Period1 Float,
HoursAvailable_ Period2 Float,
HoursAvailable_ Period3 Float,
HoursAvailable_ Period4 Float,
HoursAvailable_ Period5 Float,
HoursAvailable_ Period6 Float,

BeginDate_Perio d1 DateTime,
BeginDate_Perio d2 DateTime,
BeginDate_Perio d3 DateTime,
BeginDate_Perio d4 DateTime,
BeginDate_Perio d5 DateTime,
BeginDate_Perio d6 DateTime,

EndDate_Period1 DateTime,
EndDate_Period2 DateTime,
EndDate_Period3 DateTime,
EndDate_Period4 DateTime,
EndDate_Period5 DateTime,
EndDate_Period6 DateTime,

Hours_Period1 Float,
Hours_Period2 Float,
Hours_Period3 Float,
Hours_Period4 Float,
Hours_Period5 Float,
Hours_Period6 Float
);

-- --------------------
-- 3) Populate first work table with multiple records for each timesheet
line.
-- We do this with a series of INSERT statements: one for each period.

-- ------------------
-- First of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period1,
HoursAvailable_ Period1,
BeginDate_Perio d1,
EndDate_Period1 ,
Hours_Period1
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate1) AND
(tblWeekReporte d.EndDate=@EndD ate1) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);

-- ------------------
-- Second of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period2,
HoursAvailable_ Period2,
BeginDate_Perio d2,
EndDate_Period2 ,
Hours_Period2
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate2) AND
(tblWeekReporte d.EndDate=@EndD ate2) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Third of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period3,
HoursAvailable_ Period3,
BeginDate_Perio d3,
EndDate_Period3 ,
Hours_Period3
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate3) AND
(tblWeekReporte d.EndDate=@EndD ate3) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);

-- ------------------
-- Fourth of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period4,
HoursAvailable_ Period4,
BeginDate_Perio d4,
EndDate_Period4 ,
Hours_Period4
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate4) AND
(tblWeekReporte d.EndDate=@EndD ate4) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Fifth of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period5,
HoursAvailable_ Period5,
BeginDate_Perio d5,
EndDate_Period5 ,
Hours_Period5
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate5) AND
(tblWeekReporte d.EndDate=@EndD ate5) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Sixth of six

INSERT INTO #Extract1
(
ProjectID,

WeekReportedID_ Period6,
HoursAvailable_ Period6,
BeginDate_Perio d6,
EndDate_Period6 ,
Hours_Period6
)

SELECT
tblWeekReported Line.ProjectID,

tblWeekReported Line.WeekReport edID,
tblWeekReported .HoursAvailable ,
tblWeekReported .BeginDate,
tblWeekReported .EndDate,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate6) AND
(tblWeekReporte d.EndDate=@EndD ate6) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);

-- --------------------------------------------------------------------
-- Summarize/Total the first work table's rotated/pivoted data into the second
work table
-- Same format, just boiled down to a single record per project.

INSERT INTO #Extract2
(
ProjectID,

WeekReportedID_ Period1,
WeekReportedID_ Period2,
WeekReportedID_ Period3,
WeekReportedID_ Period4,
WeekReportedID_ Period5,
WeekReportedID_ Period6,

HoursAvailable_ Period1,
HoursAvailable_ Period2,
HoursAvailable_ Period3,
HoursAvailable_ Period4,
HoursAvailable_ Period5,
HoursAvailable_ Period6,

BeginDate_Perio d1,
BeginDate_Perio d2,
BeginDate_Perio d3,
BeginDate_Perio d4,
BeginDate_Perio d5,
BeginDate_Perio d6,

EndDate_Period1 ,
EndDate_Period2 ,
EndDate_Period3 ,
EndDate_Period4 ,
EndDate_Period5 ,
EndDate_Period6 ,

Hours_Period1,
Hours_Period2,
Hours_Period3,
Hours_Period4,
Hours_Period5,
Hours_Period6
)

SELECT
ProjectID,

Sum(WeekReporte dID_Period1),
Sum(WeekReporte dID_Period2),
Sum(WeekReporte dID_Period3),
Sum(WeekReporte dID_Period4),
Sum(WeekReporte dID_Period5),
Sum(WeekReporte dID_Period6),

Sum(HoursAvaila ble_Period1),
Sum(HoursAvaila ble_Period2),
Sum(HoursAvaila ble_Period3),
Sum(HoursAvaila ble_Period4),
Sum(HoursAvaila ble_Period5),
Sum(HoursAvaila ble_Period6),

Sum(BeginDate_P eriod1),
Sum(BeginDate_P eriod2),
Sum(BeginDate_P eriod3),
Sum(BeginDate_P eriod4),
Sum(BeginDate_P eriod5),
Sum(BeginDate_P eriod6),

Sum(EndDate_Per iod1),
Sum(EndDate_Per iod2),
Sum(EndDate_Per iod3),
Sum(EndDate_Per iod4),
Sum(EndDate_Per iod5),
Sum(EndDate_Per iod6),

Sum(Hours_Perio d1),
Sum(Hours_Perio d2),
Sum(Hours_Perio d3),
Sum(Hours_Perio d4),
Sum(Hours_Perio d5),
Sum(Hours_Perio d6)

FROM #Extract1
GROUP BY #Extract1.Proje ctID;
-- =============== =============== =============== =============== =======
-- BEGIN GENERATING OUTPUT
-- Reset a parameter so that subsequent SELECT...; statements will each
-- append a recordset to the output stream

SET NOCOUNT OFF

-- --------------------------------------------------------------------
-- For our first output table return a "Header Info" record that contains
-- information about the person doing the estimating

SELECT
@PersonID,
tlkpDepartment. DepartmentNameL ong,
tlkpDepartment. DepartmentNameS hort,
tlkpGroup.Group NameLong,
tlkpGroup.Group NameShort,
tlkpPerson.Empl oyeeNumber,
tlkpPerson.Name Last,
tlkpPerson.Name First,
tlkpPerson.Name Middle,
tlkpVendor.Vend orName

FROM ((tlkpPerson
LEFT JOIN tlkpVendor ON tlkpPerson.Vend orID = tlkpVendor.Vend orID)
LEFT JOIN tlkpGroup ON tlkpPerson.Grou pID = tlkpGroup.Group ID)
LEFT JOIN tlkpDepartment ON tlkpGroup.Depar tmentID =
tlkpDepartment. DepartmentID

WHERE tlkpPerson.Pers onID=@PersonID;
-- --------------------------------------------------------------------
-- Produce our second-and-last output table: A copy of the records in Extract#2

-- ------------------------------------------ End
---------------------------------
GO

-------------------------------------------------------------------------
--
PeteCresswell
Jul 20 '05 #3
Here's the current final product (that returns what I want - albiet maybe not as
elegantly as it could...)
=============== ==============
--PURPOSE: To return the two recordsets to be used in loading
-- the Estimate edit screen or the work tables behind
-- an Estimate report:
-- > A single header rec with department, person's name, and so-forth
-- > Many records for various projects/estimating periods. These
records
-- are in a sort of pivot table presentation with one column for each
-- date range. i.e. one row contains data from many weeks reported.
--ACCEPTS: - PersonID of of person doing the estimating
-- - A flag telling what the data is to be used for:
-- 1 = To Print a report
-- 2 = To load the estimat edit screen
-- - 12 dates: One for each first and last date in each estimating
period
--USED BY: rptEstimate..., frmEstimate

CREATE PROCEDURE spEstimate_Load
@PersonID int,
@UsedFor int,
@BeginDate1 datetime,
@EndDate1 datetime,
@BeginDate2 datetime,
@EndDate2 datetime,
@BeginDate3 datetime,
@EndDate3 datetime,
@BeginDate4 datetime,
@EndDate4 datetime,
@BeginDate5 datetime,
@EndDate5 datetime,
@BeginDate6 datetime,
@EndDate6 datetime
AS

DECLARE @EstimatesFound Ct int

-- --------------------------------------------------------------------
-- We don't know how to do figurative constants in TSQL, so we
-- do our own little workaround to document avoid "magic numbers"
-- in the code

DECLARE @ErrNoData int,
@UsedForPrint int,
@UsedForLoad int,
@WeekType_Estim ate int

SET @UsedForPrint =1
SET @UsedForLoad =2
SET @ErrNoData =999
SET @WeekType_Estim ate =2

-- --------------------------------------------------------------------
-- See if there is any info for the Person/Dates in question
-- Bail out if not

SELECT @EstimatesFound Ct =
(
SELECT COUNT(*) FROM tblWeekReported
WHERE ((tblWeekReport ed.PersonID=@Pe rsonID) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(
(tblWeekReporte d.BeginDate=@Be ginDate1 AND
tblWeekReported .EndDate=@EndDa te1) OR
(tblWeekReporte d.BeginDate=@Be ginDate2 AND
tblWeekReported .EndDate=@EndDa te2) OR
(tblWeekReporte d.BeginDate=@Be ginDate3 AND
tblWeekReported .EndDate=@EndDa te3) OR
(tblWeekReporte d.BeginDate=@Be ginDate4 AND
tblWeekReported .EndDate=@EndDa te4) OR
(tblWeekReporte d.BeginDate=@Be ginDate5 AND
tblWeekReported .EndDate=@EndDa te5) OR
(tblWeekReporte d.BeginDate=@Be ginDate6 AND
tblWeekReported .EndDate=@EndDa te6)
)
)
)

IF ((@UsedFor = @UsedForPrint) AND (@EstimatesFoun dCt = 0))
RETURN @ErrNoData
-- --------------------------------------------------------------------
-- Set a parameter that prevents our work table create/populate operations
-- from appending unwanted recordsets to the output

SET NOCOUNT ON
-- =============== =============== =============== =============== ========
-- Create our work tables

-- ------------------
-- 1) Create a work table that will receive a pivoted version of our
-- data: up to six "WeekReport ed" periods per line

IF OBJECT_ID('temp db..#Extract1') IS NOT NULL DROP TABLE #Extract1;
CREATE TABLE #Extract1
(
WeekReportedLin eID int,
ProjectID int,

HoursAvailable_ Period1 Float,
HoursAvailable_ Period2 Float,
HoursAvailable_ Period3 Float,
HoursAvailable_ Period4 Float,
HoursAvailable_ Period5 Float,
HoursAvailable_ Period6 Float,

Hours_Period1 Float,
Hours_Period2 Float,
Hours_Period3 Float,
Hours_Period4 Float,
Hours_Period5 Float,
Hours_Period6 Float
);

-- ------------------
-- 2) Create a work table like the first one, whose mission in life
-- is to receive summed data from the first one.

IF OBJECT_ID('temp db..#Extract2') IS NOT NULL DROP TABLE #Extract2;
CREATE TABLE #Extract2
(
ProjectID int,

HoursAvailable_ Period1 Float,
HoursAvailable_ Period2 Float,
HoursAvailable_ Period3 Float,
HoursAvailable_ Period4 Float,
HoursAvailable_ Period5 Float,
HoursAvailable_ Period6 Float,

Hours_Period1 Float,
Hours_Period2 Float,
Hours_Period3 Float,
Hours_Period4 Float,
Hours_Period5 Float,
Hours_Period6 Float
);
-- --------------------
-- 3) Populate first work table with multiple records for each timesheet line.
-- We do this with a series of INSERT statements: one for each period.

-- ------------------
-- First of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period1,
Hours_Period1
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate1) AND
(tblWeekReporte d.EndDate=@EndD ate1) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);

-- ------------------
-- Second of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period2,
Hours_Period2
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate2) AND
(tblWeekReporte d.EndDate=@EndD ate2) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Third of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period3,
Hours_Period3
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate3) AND
(tblWeekReporte d.EndDate=@EndD ate3) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);

-- ------------------
-- Fourth of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period4,
Hours_Period4
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate4) AND
(tblWeekReporte d.EndDate=@EndD ate4) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Fifth of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period5,
Hours_Period5
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate5) AND
(tblWeekReporte d.EndDate=@EndD ate5) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- ------------------
-- Sixth of six

INSERT INTO #Extract1
(
ProjectID,
HoursAvailable_ Period6,
Hours_Period6
)

SELECT
tblWeekReported Line.ProjectID,
tblWeekReported .HoursAvailable ,
tblHour.Hours

FROM (tblWeekReporte d
INNER JOIN tblWeekReported Line ON tblWeekReported .WeekReportedID =
tblWeekReported Line.WeekReport edID)
INNER JOIN tblHour ON tblWeekReported Line.WeekReport edLineID =
tblHour.WeekRep ortedLineID

WHERE
(
(tblWeekReporte d.BeginDate=@Be ginDate6) AND
(tblWeekReporte d.EndDate=@EndD ate6) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(tblWeekReporte d.PersonID=@Per sonID)
);
-- --------------------------------------------------------------------
-- Summarize/Total the first work table's rotated/pivoted data into the second
work table
-- Same format, just boiled down to a single record per project.

INSERT INTO #Extract2
(
ProjectID,

HoursAvailable_ Period1,
HoursAvailable_ Period2,
HoursAvailable_ Period3,
HoursAvailable_ Period4,
HoursAvailable_ Period5,
HoursAvailable_ Period6,

Hours_Period1,
Hours_Period2,
Hours_Period3,
Hours_Period4,
Hours_Period5,
Hours_Period6
)

SELECT
ProjectID,

Sum(HoursAvaila ble_Period1),
Sum(HoursAvaila ble_Period2),
Sum(HoursAvaila ble_Period3),
Sum(HoursAvaila ble_Period4),
Sum(HoursAvaila ble_Period5),
Sum(HoursAvaila ble_Period6),

Sum(Hours_Perio d1),
Sum(Hours_Perio d2),
Sum(Hours_Perio d3),
Sum(Hours_Perio d4),
Sum(Hours_Perio d5),
Sum(Hours_Perio d6)

FROM #Extract1
GROUP BY #Extract1.Proje ctID;
-- =============== =============== =============== =============== =======
-- BEGIN GENERATING OUTPUT
-- Reset a parameter so that subsequent SELECT...; statements will each
-- append a recordset to the output stream

SET NOCOUNT OFF

-- --------------------------------------------------------------------
-- For our first output table return a "Header Info" record that contains
-- information about the person doing the estimating

SELECT
@PersonID AS PersonID,
tlkpDepartment. DepartmentNameL ong,
tlkpDepartment. DepartmentNameS hort,
tlkpGroup.Group NameLong,
tlkpGroup.Group NameShort,
tlkpPerson.Empl oyeeNumber,
tlkpPerson.Name Last,
tlkpPerson.Name First,
tlkpPerson.Name Middle,
tlkpVendor.Vend orName

FROM ((tlkpPerson
LEFT JOIN tlkpVendor ON tlkpPerson.Vend orID = tlkpVendor.Vend orID)
LEFT JOIN tlkpGroup ON tlkpPerson.Grou pID = tlkpGroup.Group ID)
LEFT JOIN tlkpDepartment ON tlkpGroup.Depar tmentID =
tlkpDepartment. DepartmentID

WHERE tlkpPerson.Pers onID=@PersonID;
-- --------------------------------------------------------------------
-- Produce our second-and-last output table: A copy of the records in Extract#2
with dates
-- recovered via a join on DateID

SELECT
*,
@BeginDate1 AS BeginDate_Perio d1,
@BeginDate2 AS BeginDate_Perio d2,
@BeginDate3 AS BeginDate_Perio d3,
@BeginDate4 AS BeginDate_Perio d4,
@BeginDate5 AS BeginDate_Perio d5,
@BeginDate6 AS BeginDate_Perio d6,

@EndDate1 AS EndDate_Period1 ,
@EndDate2 AS EndDate_Period2 ,
@EndDate3 AS EndDate_Period3 ,
@EndDate4 AS EndDate_Period4 ,
@EndDate5 AS EndDate_Period5 ,
@EndDate6 AS EndDate_Period6

FROM #Extract2

-- ------------------------------------------ End
---------------------------------
GO

=============== ==============
--
PeteCresswell
Jul 20 '05 #4
(Pete Cresswell) (x@y.z) writes:
Here's the current final product (that returns what I want - albiet
maybe not as elegantly as it could...)
Since you are crazy enough to post your code, permit me just two comments,
both a bit on the style side, but nevertheless:
SELECT @EstimatesFound Ct =
(
SELECT COUNT(*) FROM tblWeekReported
WHERE ((tblWeekReport ed.PersonID=@Pe rsonID) AND
(tblWeekReporte d.WeekType=@Wee kType_Estimate) AND
(
(tblWeekReporte d.BeginDate=@Be ginDate1 AND
tblWeekReported .EndDate=@EndDa te1) OR
(tblWeekReporte d.BeginDate=@Be ginDate2 AND
tblWeekReported .EndDate=@EndDa te2) OR
(tblWeekReporte d.BeginDate=@Be ginDate3 AND
tblWeekReported .EndDate=@EndDa te3) OR
(tblWeekReporte d.BeginDate=@Be ginDate4 AND
tblWeekReported .EndDate=@EndDa te4) OR
(tblWeekReporte d.BeginDate=@Be ginDate5 AND
tblWeekReported .EndDate=@EndDa te5) OR
(tblWeekReporte d.BeginDate=@Be ginDate6 AND
tblWeekReported .EndDate=@EndDa te6)
)
)
)
Use aliases. This makes your queries more consice, and easier to read:

SELECT @EstimatesFound Ct =
(SELECT COUNT(*)
FROM tblWeekReported wr
WHERE ((wr.PersonID=@ PersonID) AND
(wr.WeekType=@W eekType_Estimat e) AND
((wr.BeginDate= @BeginDate1 AND wr.EndDate=@End Date1) OR
(wr.BeginDate=@ BeginDate2 AND wr.EndDate=@End Date2) OR
(wr.BeginDate=@ BeginDate3 AND wr.EndDate=@End Date3) OR
(wr.BeginDate=@ BeginDate4 AND wr.EndDate=@End Date4) OR
(wr.BeginDate=@ BeginDate5 AND wr.EndDate=@End Date5) OR
(wr.BeginDate=@ BeginDate6 AND wr.EndDate=@End Date6) )
)
)

Since this query only accesses one table, many programmers would use any
prefix, and I have to count myself amoung those. However, as soon there
is more than tables in a query, you always use prefixes. Even if a column
name is not unambiguous today, it may not be tomorrow.

CREATE TABLE #Extract1
(
WeekReportedLin eID int,
ProjectID int,

HoursAvailable_ Period1 Float,
HoursAvailable_ Period2 Float,
HoursAvailable_ Period3 Float,
HoursAvailable_ Period4 Float,
HoursAvailable_ Period5 Float,
HoursAvailable_ Period6 Float,
...


In my opinon you should always include explicit NULL/NOT NULL indicators.
If you don't specify, there is a default, but whether that default is
NULL or NOT NULL depends on SET commands set at run-time, so you can
get surprises if you don't tell what you want.

--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #5
Hi Erland,

Looks like the correspondence course fron the John Bell school or dyslexic
posting is working!! :)
Since this query only accesses one table, many programmers would use any
Since this query only accesses one table, many programmers would not use
any
prefix, and I have to count myself amoung those. However, as soon there
is more than tables in a query, you always use prefixes. Even if a column
is more than one table in a query, you should always use prefixes. Even if a
column
name is not unambiguous today, it may not be tomorrow.


name is not ambiguous today, it may not be tomorrow.

Looks like I better start planning the graduation ceremony!

John
Jul 20 '05 #6
RE/
Use aliases. This makes your queries more consice, and easier to read:


I like it. Will change over ASAP.

What about the "NULLS" biz? Does that refer to whether-or-not Null is allowed
as a value?
--
PeteCresswell
Jul 20 '05 #7
The nulls are to do do with the ANSI_NULL_DEFAU LT setting for the database
which can be different from database to database.

When this option is set to ON, all user-defined data types or columns that
are not explicitly defined as NOT NULL during a CREATE TABLE or ALTER TABLE
statement default to allowing null values. See:
http://msdn.microsoft.com/library/de...asp?frame=true

John

"(Pete Cresswell)" <x@y.z> wrote in message
news:qq******** *************** *********@4ax.c om...
RE/
Use aliases. This makes your queries more consice, and easier to read:
I like it. Will change over ASAP.

What about the "NULLS" biz? Does that refer to whether-or-not Null is

allowed as a value?
--
PeteCresswell

Jul 20 '05 #8
(Pete Cresswell) (x@y.z) writes:
What about the "NULLS" biz? Does that refer to whether-or-not Null is
allowed as a value?


Yes.

nisse int NOT NULL
kalle int NULL

nisse does permits NULL, but kalle does. But in:

nisse int,
kalle int,

You don't know whether NULL are accepted or not. Well, at least I don't.
There are two settings which controls the default, at it is all very
confusing.

--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #9
Did you alias the virtual table?

SELECT * FROM
(
SELECT whatever
UNION this
UNION that
UNION other
) AS MYBIGUNION -- ALIAS TO UNION
"(Pete Cresswell)" <x@y.z> wrote in message
news:o0******** *************** *********@4ax.c om...
I've got some SQL that works as far as returning a recordset from a series of UNION statements.

viz:

SELECT whatever
UNION this
UNION that
UNION other

Now I want to group and sum on it's results.

Started out tying:

SELECT * FROM
(
union stuff
)

...but couldn't even get past the syntax check.
Where I'm headed is a sort of pivot table presentation of some hours data
associated with various projects with a column for each of six date ranges.
Bottom line: can somebody give me a pointer to the syntax needed to wrap those UNION statements and then select/group/sum their results?
--
PeteCresswell

Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3579
by: Steve | last post by:
I have a products table where the PK is ProductID. Also have the standard Orders table and OrderDetails table. I created a query that joins the Orders table and OrderDetails table. The query includes the OrderDate field from the Orders table and the ProductID field from the OrderDetails table. I added a criteria to the OrderDate field to limit the orders to the past year. Then I converted the query to a totals query to get the total sold of...
5
1922
by: Alicia | last post by:
Hello everyone based on the data, I created a union query which produces this. SELECT ,,, 0 As ClosedCount FROM UNION SELECT ,, 0 AS OpenedCount, FROM ORDER BY , ;
4
2081
by: stephena | last post by:
Hello all, hope someone can help. I recently built a report showing the distribution of money in and out of the company. Simplified version of which looks like: DECEMBER 2004 TELEPHONE SALES: INTERNET: TOTAL: £1200 £1000 £2200 I then built a sub-report showing adjustments, eg:
15
5657
by: Rolan | last post by:
There must be a way to enhance the performance of a query, or find a plausible workaround, but I seem to be hitting a wall. I have tried a few tweaks, however, there has been no improvement. Simply, I'm including one calcualtion from a separate table/query. It sums the total units sold to date by ProductID number and is used in other select queries to perform various calculations. Perhaps there is an advantage in working with a maximum...
2
4342
by: mattytee123 | last post by:
I have about 20 tables, of which I would like to do a union query and count of how many of each different code there is? The simplified verson of the table is structured like this. Code Count 1234 1 2468 1 1234 1 2468 1
7
3538
by: Mark Carlyle via AccessMonster.com | last post by:
I have this update query that I am trying to run. I know the syntax is messed up but do not know how to correct it. Select 'UPDATE', Transactions,'Set = where = ' From "Get Daily Balances" Transactions = name of the table I want to update balance = name of the field i want to update daily balance= name of the query result that I want to move to the table
4
3398
by: New Guy | last post by:
I'm trying to work with a system that somebody else built and I am confounded by the following problem: There is a table of payments and a table of charges. Each client has charges and payments during the month. I'd like to get the totals of the payments and of the charges for each client. When I run the following query, I get huge numbers that appear as if the join is not working correctly.
4
3134
by: lorirobn | last post by:
Hi, I have a report displaying items that are missing from a room. I created 2 queries, the first getting the items IN the room, and the second being an "unmatched" query that references the first query where Item is Null. I use a subreport for the details, and the results display correctly. However, the Report_Details event of the subreport is executed about 2 or 3 times more than I would expect (I think 3 times when I have a
2
1969
by: sara | last post by:
I am helping a non-profit track their elder clients and care given to the clients. The organization would like a report that shows various info on ALL clients, such as: # in each town, # and Percent Male, Female, Smoker, # in age range # that use wheelchair or walker.
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10102
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.