SQL aggregation query and sum columns - sql

I have this table (I put the name over needed colums)
iddip date idv idc val
47 2018-06-01 00:00:00.000 0 3 3 60 NULL NULL
47 2018-06-01 00:00:00.000 0 1 3 200 NULL NULL
47 2018-06-01 00:00:00.000 0 1 4 280 NULL NULL
43 2018-06-01 00:00:00.000 0 3 2 510 NULL NULL
53 2018-06-01 00:00:00.000 0 1 4 480 NULL NULL
29 2018-06-01 00:00:00.000 0 3 2 510 NULL NULL
2 2018-06-11 00:00:00.000 0 1 2 480 NULL NULL
47 2018-06-02 00:00:00.000 0 1 3 100 NULL NULL
I want to obtain this:
id idc Totidv1 Totidv3 TOT
47 3 300 60 360
47 4 280 0 280
43 2 0 510 510
53 4 480 0 480
29 2 0 510 510
2 2 480 0 480
The closest I can get is:
SELECT DISTINCT(iddip),IDCENTROCOSTO,tot=SUM(VALORE),ord=( SELECT SUM(isnull(VALORE,0)) FROM VALORIVOCICDC WHERE IDVOCE='1' and iddip=v.IDDIP and IDCENTROCOSTO ='3' GROUP BY iddip,IDCENTROCOSTO),
str=( SELECT SUM(isnull(VALORE,0)) FROM VALORIVOCICDC WHERE IDVOCE='3' and iddip=v.IDDIP and IDCENTROCOSTO ='3' GROUP BY iddip,IDCENTROCOSTO)
FROM VALORIVOCICDC v
GROUP BY v.iddip,IDCENTROCOSTO
But it returns wrong sums in totidv1 and totisv3, How can I do this? Thanks for any hint

You just need a GROUP BY here (not distinct) and a couple of CASE statements:
SELECT
id,
idc,
SUM(CASE WHEN idv=3 THEN idv ELSE 0 END) as totidv1,
SUM(CASE WHEN idv=1 THEN idv ELSE 0 END) as totidv3,
SUM(idv) as Tot
FROM yourtable
GROUP BY id, idc
Note that Distinct is not a function that you can call like SELECT DISTINCT(somecolumn) This is functionally equivalent to SELECT DISTINCT somecolumn... in that it works against the entire record set returned by the SELECT statement either way.

Related

T SQL CTE Previous Row Calculation

I'm using SQL Server 2016.
I have the below table:
SKU Shop Week ShopPrioirty Replen Open_Stk Open_Stk Calc
111 100 1 1 0 17 NULL
111 200 1 2 2 NULL NULL
111 300 1 3 0 NULL NULL
111 400 1 4 0 NULL NULL
222 100 2 1 5 17 NULL
222 200 2 2 5 NULL NULL
222 300 2 3 5 NULL NULL
222 400 2 4 5 NULL NULL
This is the desired result:
SKU Shop Week ShopPrioirty Replen Open_Stk Open_Stk Calc
111 100 1 1 0 17 17
111 200 1 2 2 NULL 17
111 300 1 3 0 NULL 15
111 400 1 4 0 NULL 15
222 100 2 1 20 17 17
222 200 2 2 15 NULL 12
222 300 2 3 12 NULL 7
222 400 2 4 10 NULL 2
I need to update the 'Open_Stk Calc' based on the previous row:
'Open_Stk Calc' - IIF('Replen'<=IIF('Open_Stk'>=0,'Open_Stk',0),'Replen',0)
I am using a CTE to update a row based on a calculation of the previous rows. This is my SQL:
;WITH CTE AS
(
SELECT
SKU,
[Shop],
[Week],
[Store_Priority],
[Replen],
[Open_Stk],
[Open_Stk Calc],
FIRST_VALUE([Open_Stk]) OVER ( PARTITION BY [SKU] ,[Week] ORDER BY [Store_Priority] ROWS UNBOUNDED PRECEDING)
-
ISNULL(SUM(IIF([Replen] <= IIF([Open_Stk]>=0,[Open_Stk],0),[Replen],0))
OVER (PARTITION BY [SKU] ,[Week] ORDER BY [Store_Priority] ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS CurrentStock
FROM [tblTEST])
UPDATE CTE
SET [Open_Stk Calc] = CurrentStock
However, this produces the following result:
SKU Shop Week ShopPrioirty Replen Open_Stk Open_Stk Calc
111 100 1 1 0 17 17
111 200 1 2 2 NULL 17
111 300 1 3 0 NULL 17
111 400 1 4 0 NULL 17
And not the desired result - where have I gone wrong?
As one can see in the MS documentation, the OVER clauses supports specific kind of functions:
Ranking functions
Aggregate functions
Analytic functions
NEXT VALUE FOR function
None of them include IIF, as Luis Cazares noted in their comment.
Your code indicates you do have a clue about what you are doing - maybe you forgot to put your IIF inside a SUM?

Creating a string of combined values from a SQL Server table

I built a SQL query which returns the following results:
ID Number ID IndexColumn String_To_Use Checking_ID
0000 1 0000 1 -2
1000 2 1000 2 -2
1020 3 1020 3 -2
1130 4 1130 4 -2
1198 5 NULL 9999 NULL NULL
1199 6 1199 5 -2
1210 7 1210 6 -2
1240 8 NULL 9999 NULL NULL
1250 9 NULL 9999 NULL NULL
1260 10 1260 7 7
1261 11 NULL 9999 NULL NULL
1280 12 NULL 9999 NULL NULL
1296 13 NULL 9999 NULL NULL
1298 14 NULL 9999 NULL NULL
1299 15 1299 8 8
1501 16 NULL 9999 NULL NULL
I need to populate the column "String_To_Use" with "ID" values in such a way that If "Checking_ID" column has values -2 more than once repeating (it means user chose IDs in a range), these repeating values would be displayed as "0000-1130"; if values -2 is not being repeated, then for example "1260".
Based on this logic, the above table will contain the following values in the String_To_Use column:
ID Number ID IndexColumn String_To_Use Checking_ID
0000 1 0000 1 0000-1130 -2
1000 2 1000 2 0000-1130 -2
1020 3 1020 3 0000-1130 -2
1130 4 1130 4 0000-1130 -2
1198 5 NULL 9999 NULL NULL
1199 6 1199 5 0000-1210 -2
1210 7 1210 6 0000-1210 -2
1240 8 NULL 9999 NULL NULL
1250 9 NULL 9999 NULL NULL
1260 10 1260 7 1260 7
1261 11 NULL 9999 NULL NULL
1280 12 NULL 9999 NULL NULL
1296 13 NULL 9999 NULL NULL
1298 14 NULL 9999 NULL NULL
1299 15 1299 8 1299 8
1501 16 NULL 9999 NULL NULL
thank you!!
You need to define groups of "adjacency". In this case, you can simply do a cumulative sum of the number of times that checking_id is not -2.
After that, the rest is window functions and string manipulation:
select t.*,
(case when checking_id <> -2
then min(id) over (partition by grp) + '-' + max(id) over (partition by grp)
else id
end) as string_to_use
from (select t.*,
sum(case when checking_id <> -2 then 1 else 0 end) over (order by id) as grp
from t
) t;
This version assumes that id is a string. If it is a number, the code is easily adapted by cluttering it with cast() or convert().
select t.*,
(case when Checking_id = -2
then min(id) over (partition by grp) + '-' + max(id) over (partition by grp)
else id
end) as string_to_use
from (select t.*
,sum(case when Checking_id = -2 then 1 else 0 end) over (partition by id) as grp
from t
) t order by id;
ID Number ID IndexColumn String_To_Use Checking_id grp string_to_use
0000 1 0000 1 -2 1 0000 -1210
1000 2 1000 2 -2 1 0000 -1210
1020 3 1020 3 -2 1 0000 -1210
1130 4 1130 4 -2 1 0000 -1210
1198 5 NULL 9999 NULL NULL 0 NULL
1199 6 1199 5 -2 1 0000 -1210
1210 7 1210 6 -2 1 0000 -1210
1240 8 NULL 9999 NULL NULL 0 NULL
1250 9 NULL 9999 NULL NULL 0 NULL
1260 10 1260 7 7 0 1260
1261 11 NULL 9999 NULL NULL 0 NULL
1280 12 NULL 9999 NULL NULL 0 NULL
1296 13 NULL 9999 NULL NULL 0 NULL
1298 14 NULL 9999 NULL NULL 0 NULL
1299 15 1299 8 8 0 1299
1501 16 NULL 9999 NULL NULL 0 NULL

proc sql statement to sum on values/rows that match a condition

I have a data table like below:
Table 1:
ROWID PERSONID YEAR pidDifference TIMETOEVENT DAYSBETVISIT
10 111 2009 . 100 .
110 120 2009 9 10 .
231 120 2009 0 20 10
222 120 2010 0 40 20
221 222 2009 102 10 30
321 222 2009 0 30 20
213 222 2009 0 10 20
432 321 2009 99 10 0
211 432 2009 111 20 10
212 432 2009 0 20 0
I want to sum over the DAYSBETVISIT column only when the pidDifference value is 0 for each PERSONID. So I wrote the following proc sql statement.
proc sql;
create table table5 as
(
select rowid, YEAR, PERSONID, pidDifference, TIMETOEVENT, DAYSBETVISIT,
SUM(CASE WHEN PIDDifference = 0 THEN DaysBetVisit ELSE 0 END)
from WORK.Table4_1
group by PERSONID,TIMETOEVENT, YEAR
);
quit;
However, the result I got was not summing the DAYSBETVISIT values in rows where PIDDifference = 0 within the same PERSONID. It just output the same value as was present in DAYSBETVISIT in that specific row.
Column that I NEED (sumdays) but don't get with above statement (showing the resultant column using above statement as OUT:
ROWID PERSONID YEAR pidDifference TIMETOEVENT DAYSBETVISIT sumdays OUT
10 111 2009 . 100 . 0 0
110 120 2009 9 10 . 0 0
231 120 2009 0 20 10 30 10
222 120 2010 0 40 20 30 20
221 222 2009 102 10 30 0 0
321 222 2009 0 30 20 40 20
213 222 2009 0 10 20 40 20
432 321 2009 99 10 0 0 0
211 432 2009 111 20 10 0 0
212 432 2009 0 20 0 0 0
I do not know what I am doing wrong.
I am using SAS EG Version 7.15, Base SAS version 9.4.
For your example data it looks like you just need to use two CASE statements. One to define which values to SUM() and another to define whether to report the SUM or not.
proc sql ;
select personid, piddifference, daysbetvisit, sumdays
, case when piddifference = 0
then sum(case when piddifference=0 then daysbetvisit else 0 end)
else 0 end as WANT
from expect
group by personid
;
quit;
Results
pid
PERSONID Difference DAYSBETVISIT sumdays WANT
--------------------------------------------------------
111 . . 0 0
120 0 10 30 30
120 0 20 30 30
120 9 . 0 0
222 0 20 40 40
222 0 20 40 40
222 102 30 0 0
321 99 0 0 0
432 0 0 0 0
432 111 10 0 0
SAS proc sql doesn't support window functions. I find the re-merging aggregations to be a bit difficult to use, except in the obvious cases. So, use a subquery or join and group by:
proc sql;
create table table5 as
select t.rowid, t.YEAR, t.PERSONID, t.pidDifference, t.TIMETOEVENT, t.DAYSBETVISIT,
tt.sum_DaysBetVisit
from WORK.Table4_1 t left join
(select personid, sum(DaysBetVisit) as sum_DaysBetVisit
from WORK.Table4_1
group by personid
having min(pidDifference) = max(pidDifference) and min(pidDifference) = 0
) tt
on tt.personid = t.personid;
Note: This doesn't handle NULL values for pidDifference. If that is a concern, you can add count(pidDifference) = count(*) to the having clause.

Fifo Inventory with SQL

I need one adaptation for the first table because there are negative issues points and I need the net table considerating the negatives points as debit of the first time of issue. E.g:
FechaEmi Cuenta PtosEmi PtosCan
30/06/2015 1 100 0
31/07/2015 1 120 0
31/08/2015 1 130 0
31/08/2015 1 0 55
30/09/2015 1 50 0
31/10/2015 1 30 0
30/11/2015 1 70 0
31/12/2015 1 95 0
31/01/2016 1 50 0
29/02/2016 1 0 74
31/03/2016 1 50 0
30/04/2016 1 15 0
30/06/2015 2 20 0
31/07/2015 2 30 0
31/08/2015 2 40 0
30/09/2015 2 350 0
30/06/2015 3 150 0
31/07/2015 3 120 0
31/08/2015 3 0 56
31/08/2015 3 220 0
30/06/2015 4 70 0
31/07/2015 4 134 0
31/08/2015 4 12 0
30/06/2015 5 97 0
31/07/2015 5 130 0
31/08/2015 5 15 0
30/09/2015 5 135 0
31/10/2015 5 20 0
30/11/2015 5 140 0
31/12/2015 5 25 0
31/01/2016 5 145 0
29/02/2016 5 0 25
where:
FechaEmi= Date;
Cuenta=ID;
PtosEmi=Issues points;
PtosCan=Canceled points
I want this table
FechaEmi Cuenta PtosEmi
30/06/2015 1 0
31/07/2015 1 91
31/08/2015 1 130
30/09/2015 1 50
31/10/2015 1 30
30/11/2015 1 70
31/12/2015 1 95
31/01/2016 1 50
31/03/2016 1 50
30/04/2016 1 15
30/06/2015 2 20
31/07/2015 2 30
31/08/2015 2 40
30/09/2015 2 350
30/06/2015 3 94
31/07/2015 3 120
31/08/2015 3 220
30/06/2015 4 70
31/07/2015 4 134
31/08/2015 4 12
30/06/2015 5 72
31/07/2015 5 130
31/08/2015 5 15
30/09/2015 5 135
31/10/2015 5 20
30/11/2015 5 140
31/12/2015 5 25
31/01/2016 5 145
I have this code. The problem is that doesn't do anything with the points that were debited in a date that there are not issues point. How can you recommend me change that query? Thanks!
with cte as(
select Fechaemi, Cuenta,PtosEmi,PtosCan
,row_number() over (partition by Fechaemi,Cuenta order by Fechaemi,Cuenta) as rank
from emision)
select a.Fechaemi, a.Cuenta,a.PtosEmi - coalesce(b.PtosCan, 0) stock
from cte a
left join cte b on
a.FechaEmi= b.FechaEmi and a.Cuenta = b.Cuenta and a.rank = b.rank - 1
where a.PtosEmi - coalesce(b.PtosCan, 0) > 0 order by a.cuenta asc, a.fechaemi asc
SQL FIDDLE DEMO
with totalPay as(
SELECT Cuenta, SUM(PtosCan) TotalPayment
FROM emision
GROUP BY Cuenta
),
totalDebt as (
SELECT FechaEmi, Cuenta, (SELECT SUM(PtosEmi)
FROM emision e2
WHERE e2.FechaEmi <= e.FechaEmi
AND e2.Cuenta = e.Cuenta
) AS TotalDebt
FROM emision e
WHERE e.PtosEmi <> 0
)
select
e.FechaEmi,
e.Cuenta,
e.PtosEmi,
td.TotalDebt,
tp.TotalPayment,
CASE
WHEN td.TotalDebt < tp.TotalPayment THEN 0
WHEN td.TotalDebt - tp.TotalPayment > PtosEmi THEN PtosEmi
ELSE td.TotalDebt - tp.TotalPayment
END Remaining
FROM
totalDebt td inner join
totalPay tp on td.Cuenta = tp.Cuenta inner join
emision e on td.FechaEmi = e.FechaEmi AND td.Cuenta = e.Cuenta
WHERE
e.PtosEmi <> 0
Possibly not the most elegant, but explicit way:
WITH
PtosEmi AS(
SELECT FechaEmi, cuenta, SUM(PtosEmi) as PtosEmi
FROM table1
GROUP BY FechaEmi, cuenta),
PtosCan AS (
SELECT MIN(FechaEmi) as FechaEmi, cuenta, SUM(PtosCan) as PtosCan
FROM table1
GROUP BY cuenta)
SELECT
e.FechaEmi,
e.cuenta,
e.ptosemi,
c.ptoscan,
e.ptosemi - COALESCE(c.ptoscan, 0) total
FROM
PtosEmi e LEFT JOIN
PtosCan c ON e.FechaEmi = c.FechaEmi AND e.cuenta = c.cuenta
ORDER BY e.cuenta, e.FechaEmi
This is based on the assumption that you cannot have cancellations before anything was issued for give cuenta.
Also if you have more cancelled items in total compared to what was issued initially, total value will be negative.
http://sqlfiddle.com/#!6/9ac40/11
Update
as you want to reduce cancellations line by line here is updated query:
WITH
ptosemi AS(
SELECT FechaEmi, cuenta,
PtosEmi as PtosEmi,
SUM(PtosEmi) OVER (PARTITION BY cuenta ORDER BY FechaEmi) runsum
FROM table1),
PtosCan AS (
SELECT cuenta, SUM(PtosCan) as PtosCan
FROM table1
GROUP BY cuenta)
SELECT
e.FechaEmi,
e.cuenta,
e.ptosemi,
e.runsum,
c.ptoscan,
CASE
WHEN e.runsum <= c.ptoscan
THEN 0
WHEN c.ptoscan BETWEEN e.runsum - e.ptosemi AND e.runsum
THEN e.runsum - COALESCE(c.ptoscan, 0)
ELSE e.ptosemi END total
FROM
ptosemi e LEFT JOIN
PtosCan c ON e.cuenta = c.cuenta
ORDER BY e.cuenta, e.FechaEmi
http://sqlfiddle.com/#!6/8036c2/25

SQL Server 2008 Pivot, no Aggregation, complex data

I've seen a lot of "Pivot, No Agg" posts, but all of them seem to involve some pretty simple data to pivot, so the solutions work fairly well and easily. But how about when the data isn't as simple?
I'd like to turn this:
wwnID Tenant WeekOfTheMonth ReportingDate TotalEmployeesPerBranch TotalOpenCount TotalClosedCount OpenCount_TitleAndEscrow ClosedCount_TitleAndEscrow OpenCount_EscrowOnly ClosedCount_EscrowOnly OpenCount_PreListingTask ClosedCount_PreListingTask OFPE CFPE OpenCount_TitleOnly ClosedCount_TitleOnly CurrentBusinessDay TotalBusinessDaysMTD ReportingDateId CreatedDate
----------- -------------------------------------------------- -------------- ----------------------- --------------------------------------- -------------- ---------------- ------------------------ -------------------------- -------------------- ---------------------- ------------------------ -------------------------- --------------------------------------- --------------------------------------- ------------------- --------------------- ------------------ -------------------- --------------- -----------------------
3 King 1 2014-08-08 00:00:00.000 144.00 235 0 137 0 64 0 34 0 4.81 0.00 270 0 7 21 411 2014-09-05 08:53:11.313
5 King 2 2014-08-15 00:00:00.000 150.00 399 0 224 0 112 0 63 0 4.62 0.00 524 0 12 21 412 2014-09-05 08:53:19.573
7 King 3 2014-08-22 00:00:00.000 150.00 584 0 335 0 159 0 90 0 4.76 0.00 721 0 17 21 413 2014-09-05 08:53:26.980
9 King 4 2014-08-31 00:00:00.000 150.00 797 0 436 0 226 0 135 0 5.18 0.00 946 0 21 21 414 2014-09-05 08:53:35.593
4 Pierce 1 2014-08-08 00:00:00.000 21.00 85 0 31 0 39 0 15 0 12.00 0.00 54 0 7 21 411 2014-09-05 08:53:11.670
6 Pierce 2 2014-08-15 00:00:00.000 22.00 160 0 62 0 74 0 24 0 12.41 0.00 83 0 12 21 412 2014-09-05 08:53:20.000
8 Pierce 3 2014-08-22 00:00:00.000 22.00 222 0 82 0 107 0 33 0 12.41 0.00 127 0 17 21 413 2014-09-05 08:53:27.407
10 Pierce 4 2014-08-31 00:00:00.000 23.00 272 0 99 0 130 0 43 0 10.96 0.00 159 0 21 21 414 2014-09-05 08:53:36.063
into this:
Data Types Week 1 Week 2 Week 3 Week 4
------------------------------- ----------- ----------- ----------- -----------
Tenant King King King King
ReportingDate 8/8/2014 8/15/2014 8/22/2014 8/31/2014
TotalEmployeesPerBranch 144 150 150 150
TotalOpenCount 235 399 584 797
TotalClosedCount 0 0 0 0
OpenCount_TitleAndEscrow 137 224 335 436
ClosedCount_TitleAndEscrow 0 0 0 0
OpenCount_EscrowOnly 64 112 159 226
ClosedCount_EscrowOnly 0 0 0 0
OpenCount_PreListingTask 34 63 90 135
ClosedCount_PreListingTask 0 0 0 0
OFPE 4.81 4.62 4.76 5.18
CFPE 0 0 0 0
OpenCount_TitleOnly 270 524 721 946
ClosedCount_TitleOnly 0 0 0 0
CurrentBusinessDay 7 12 17 21
TotalBusinessDaysMTD 21 21 21 21
ReportingDateId 411 412 413 414
CreatedDate 9/5/2014 9/5/2014 9/5/2014 9/5/2014
Tenant Pierce Pierce Pierce Pierce
ReportingDate 8/8/2014 8/15/2014 8/22/2014 8/31/2014
TotalEmployeesPerBranch 21 22 22 23
TotalOpenCount 85 160 222 272
TotalClosedCount 0 0 0 0
OpenCount_TitleAndEscrow 31 62 82 99
ClosedCount_TitleAndEscrow 0 0 0 0
OpenCount_EscrowOnly 39 74 107 130
ClosedCount_EscrowOnly 0 0 0 0
OpenCount_PreListingTask 15 24 33 43
ClosedCount_PreListingTask 0 0 0 0
OFPE 12 12.41 12.41 10.96
CFPE 0 0 0 0
OpenCount_TitleOnly 54 83 127 159
ClosedCount_TitleOnly 0 0 0 0
CurrentBusinessDay 7 12 17 21
TotalBusinessDaysMTD 21 21 21 21
ReportingDateId 411 412 413 414
CreatedDate 9/5/2014 9/5/2014 9/5/2014 9/5/2014
I've tried several methods of pivoting, and none of them seem to do the trick, but if anyone out there knows a way to do it, that'd be fantastic!
Thanks ahead of time!
UPDATE
This works beautifully! (initial variable declarations are for the where clause toward the end)
DECLARE #ReportDate DATETIME = '2014-08-31';
DECLARE #RepDateId INT = ( SELECT MAX([WRD].[ReportingDateID])
FROM [SMS].[dbo].[WSOBReportingDates] AS WRD
WHERE ( [WRD].[ReportingDate] <= #ReportDate )
AND ( [WRD].[Submitted] = 1 ) );
DECLARE #WSOBRepDate DATETIME = ( SELECT [WRD].[ReportingDate]
FROM [SMS].[dbo].[WSOBReportingDates] AS WRD
WHERE [WRD].[ReportingDateID] = #RepDateId );
DECLARE #WSOBStartDate DATETIME = DATEADD(mm, DATEDIFF(mm, 0, #WSOBRepDate), 0);
SELECT Datatype
, MAX(CASE WHEN WeekOfTheMonth = 1 THEN value ELSE '0' END) Week1
, MAX(CASE WHEN WeekOfTheMonth = 2 THEN value ELSE '0' END) Week2
, MAX(CASE WHEN WeekOfTheMonth = 3 THEN value ELSE '0' END) Week3
, MAX(CASE WHEN WeekOfTheMonth = 4 THEN value ELSE '0' END) Week4
FROM ( SELECT WeekOfTheMonth
, DataType
, Value
, SortOrder
, Sequence = ROW_NUMBER() OVER ( PARTITION BY WeekOfTheMonth ORDER BY wwnId )
FROM [dbo].[SSRS_WSOBWeeklyNumbers] AS SWWN
CROSS APPLY ( SELECT 'Tenant'
, [SWWN].[Tenant]
, 1
UNION ALL
SELECT 'ReportingDate'
, CONVERT(VARCHAR(10), [SWWN].[ReportingDate], 120)
, 2
UNION ALL
SELECT 'TotalEmployeesPerBranch'
, CAST([SWWN].[TotalEmployeesPerBranch] AS VARCHAR(10))
, 3
UNION ALL
SELECT 'TotalOpenCount'
, CAST([SWWN].[TotalOpenCount] AS VARCHAR(10))
, 4
UNION ALL
SELECT 'TotalClosedCount'
, CAST([SWWN].[TotalClosedCount] AS VARCHAR(10))
, 5
UNION ALL
SELECT 'OpenCount_TitleAndEscrow'
, CAST([SWWN].[OpenCount_TitleAndEscrow] AS VARCHAR(10))
, 6
UNION ALL
SELECT 'ClosedCount_TitleAndEscrow'
, CAST([SWWN].[ClosedCount_TitleAndEscrow] AS VARCHAR(10))
, 7
UNION ALL
SELECT 'OpenCount_EscrowOnly'
, CAST([SWWN].[OpenCount_EscrowOnly] AS VARCHAR(10))
, 8
UNION ALL
SELECT 'ClosedCount_EscrowOnly'
, CAST([SWWN].[ClosedCount_EscrowOnly] AS VARCHAR(10))
, 9
UNION ALL
SELECT 'OpenCount_PreListingTask'
, CAST([SWWN].[OpenCount_PreListingTask] AS VARCHAR(10))
, 10
UNION ALL
SELECT 'ClosedCount_PreListingTask'
, CAST([SWWN].[ClosedCount_PreListingTask] AS VARCHAR(10))
, 11
UNION ALL
SELECT 'OFPE'
, CAST([SWWN].[OFPE] AS VARCHAR(10))
, 12
UNION ALL
SELECT 'CFPE'
, CAST([SWWN].[CFPE] AS VARCHAR(10))
, 13
UNION ALL
SELECT 'OpenCount_TitleOnly'
, CAST([SWWN].[OpenCount_TitleOnly] AS VARCHAR(10))
, 14
UNION ALL
SELECT 'ClosedCount_TitleOnly'
, CAST([SWWN].[ClosedCount_TitleOnly] AS VARCHAR(10))
, 15
UNION ALL
SELECT 'CurrentBusinessDay'
, CAST([SWWN].[CurrentBusinessDay] AS VARCHAR(10))
, 16
UNION ALL
SELECT 'TotalBusinessDaysForMonth'
, CAST([SWWN].[TotalBusinessDaysMTD] AS VARCHAR(10))
, 17
UNION ALL
SELECT 'ReportingDateId'
, CAST([SWWN].[ReportingDateId] AS VARCHAR(10))
, 18
UNION ALL
SELECT 'CreatedDate'
, CAST([SWWN].[CreatedDate] AS VARCHAR(10))
, 19 ) c ( DataType, Value, SortOrder )
WHERE [SWWN].[ReportingDate] BETWEEN #WSOBStartDate AND #ReportDate ) d
GROUP BY DataType
, Sequence
, SortOrder
ORDER BY Sequence
, SortOrder;
and results in:
Datatype Week1 Week2 Week3 Week4
-------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
Tenant King King King King
ReportingDate 2014-08-08 2014-08-15 2014-08-22 2014-08-31
TotalEmployeesPerBranch 144.00 150.00 150.00 150.00
TotalOpenCount 235 399 584 797
TotalClosedCount 0 0 0 0
OpenCount_TitleAndEscrow 137 224 335 436
ClosedCount_TitleAndEscrow 0 0 0 0
OpenCount_EscrowOnly 64 112 159 226
ClosedCount_EscrowOnly 0 0 0 0
OpenCount_PreListingTask 34 63 90 135
ClosedCount_PreListingTask 0 0 0 0
OFPE 4.81 4.62 4.76 5.18
CFPE 0.00 0.00 0.00 0.00
OpenCount_TitleOnly 270 524 721 946
ClosedCount_TitleOnly 0 0 0 0
CurrentBusinessDay 7 12 17 21
TotalBusinessDaysForMonth 21 21 21 21
ReportingDateId 411 412 413 414
CreatedDate Sep 5 201 Sep 5 201 Sep 5 201 Sep 5 201
Tenant Pierce Pierce Pierce Pierce
ReportingDate 2014-08-08 2014-08-15 2014-08-22 2014-08-31
TotalEmployeesPerBranch 21.00 22.00 22.00 23.00
TotalOpenCount 85 160 222 272
TotalClosedCount 0 0 0 0
OpenCount_TitleAndEscrow 31 62 82 99
ClosedCount_TitleAndEscrow 0 0 0 0
OpenCount_EscrowOnly 39 74 107 130
ClosedCount_EscrowOnly 0 0 0 0
OpenCount_PreListingTask 15 24 33 43
ClosedCount_PreListingTask 0 0 0 0
OFPE 12.00 12.41 12.41 10.96
CFPE 0.00 0.00 0.00 0.00
OpenCount_TitleOnly 54 83 127 159
ClosedCount_TitleOnly 0 0 0 0
CurrentBusinessDay 7 12 17 21
TotalBusinessDaysForMonth 21 21 21 21
ReportingDateId 411 412 413 414
CreatedDate Sep 5 201 Sep 5 201 Sep 5 201 Sep 5 201
Thanks tons for the answer!
You'll need to UNPIVOT all those columns first, then convert your Weeks into new columns. But in order to UNPIVOT the data, you'll have to convert all of the data types to be the same.
Since you are using SQL Server 2008, you can use CROSS APPLY to unpivot. The basic syntax will be:
select
WeekOfTheMonth,
DataType,
Value
from yourtable
cross apply
(
select 'Tenant', Tenant union all
select 'ReportingDate', convert(varchar(10), ReportingDate, 120) union all
select 'TotalEmployeesPerBranch', cast(TotalEmployeesPerBranch as varchar(10)) union all
select 'TotalOpenCount', cast(TotalOpenCount as varchar(10)) union all
select 'TotalClosedCount', cast(TotalClosedCount as varchar(10)) union all
select 'OpenCount_TitleAndEscrow', cast(OpenCount_TitleAndEscrow as varchar(10)) union all
select 'ClosedCount_TitleAndEscrow', cast(ClosedCount_TitleAndEscrow as varchar(10)) union all
select 'OpenCount_EscrowOnly', cast(OpenCount_EscrowOnly as varchar(10)) union all
select 'ClosedCount_EscrowOnly', cast(ClosedCount_EscrowOnly as varchar(10)) union all
select 'OpenCount_PreListingTask', cast(OpenCount_PreListingTask as varchar(10))
--- union all more columns
) c (DataType, value);
See SQL Fiddle with Demo. Then you'd apply the PIVOT to your Weeks:
select DataType,
Week1 = [1],
Week2 = [2],
Week3 = [3],
Week4 = [4]
from
(
select
WeekOfTheMonth,
DataType,
Value,
so,
seq = row_number() over(partition by WeekOfTheMonth order by wwnId)
from yourtable
cross apply
(
select 'Tenant', Tenant, 1 union all
select 'ReportingDate', convert(varchar(10), ReportingDate, 120), 2 union all
select 'TotalEmployeesPerBranch', cast(TotalEmployeesPerBranch as varchar(10)), 3 union all
select 'TotalOpenCount', cast(TotalOpenCount as varchar(10)), 4 union all
select 'TotalClosedCount', cast(TotalClosedCount as varchar(10)), 5 union all
select 'OpenCount_TitleAndEscrow', cast(OpenCount_TitleAndEscrow as varchar(10)), 6 union all
select 'ClosedCount_TitleAndEscrow', cast(ClosedCount_TitleAndEscrow as varchar(10)), 7 union all
select 'OpenCount_EscrowOnly', cast(OpenCount_EscrowOnly as varchar(10)),8 union all
select 'ClosedCount_EscrowOnly', cast(ClosedCount_EscrowOnly as varchar(10)), 9 union all
select 'OpenCount_PreListingTask', cast(OpenCount_PreListingTask as varchar(10)), 10
) c (DataType, value, so)
) d
pivot
(
max(value)
for WeekOfTheMonth in ([1], [2], [3], [4])
)p
order by seq, so
See SQL Fiddle with Demo.
Or you can use an aggregate function to create the new columns:
select Datatype,
max(case when WeekOfTheMonth = 1 then value else '0' end) Week1,
max(case when WeekOfTheMonth = 2 then value else '0' end) Week2,
max(case when WeekOfTheMonth = 3 then value else '0' end) Week3,
max(case when WeekOfTheMonth = 4 then value else '0' end) Week4
from
(
select
WeekOfTheMonth,
DataType,
Value,
so,
seq = row_number() over(partition by WeekOfTheMonth order by wwnId)
from yourtable
cross apply
(
select 'Tenant', Tenant, 1 union all
select 'ReportingDate', convert(varchar(10), ReportingDate, 120), 2 union all
select 'TotalEmployeesPerBranch', cast(TotalEmployeesPerBranch as varchar(10)), 3 union all
select 'TotalOpenCount', cast(TotalOpenCount as varchar(10)), 4 union all
select 'TotalClosedCount', cast(TotalClosedCount as varchar(10)), 5 union all
select 'OpenCount_TitleAndEscrow', cast(OpenCount_TitleAndEscrow as varchar(10)), 6 union all
select 'ClosedCount_TitleAndEscrow', cast(ClosedCount_TitleAndEscrow as varchar(10)), 7 union all
select 'OpenCount_EscrowOnly', cast(OpenCount_EscrowOnly as varchar(10)),8 union all
select 'ClosedCount_EscrowOnly', cast(ClosedCount_EscrowOnly as varchar(10)), 9 union all
select 'OpenCount_PreListingTask', cast(OpenCount_PreListingTask as varchar(10)), 10
) c (DataType, value, so)
) d
group by datatype, seq, so
order by seq, so
See SQL Fiddle with Demo