SQL Server 2008 Pivot, no Aggregation, complex data - sql

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

Related

Sum 2 column from different rows

I extract data from my table by use below query.
SELECT ID ,Desc_Cars ,DocID ,TabID
,(Select Dist1 where TabID = 85)
,(Select Dist2 where TabID = 86)
,(Select Days1 where TabID = 85)
,(Select Days2 where TabID = 85)
,(Select Days3 where TabID = 86)
FROM Details
where DocID = 16
I have following part of table in SQL:
ID
Desc_Cars
DocID
TabID
Dist1
Dist2
Days1
Days2
Days3
607
Car1
16
85
481
NULL
11
0
NULL
608 Car2
16
85
2072
NULL
21
2
NULL
609
Car3
16
85
333
NULL
15
6
NULL
610
Car4
16
85
1564
NULL
14
0
NULL
611
Car1
16
86
NULL
118
NULL
NULL
4
612
Car2
16
86
NULL
12
NULL
NULL
0
613
Car3
16
86
NULL
133
NULL
NULL
10
614
Car4
16
86
NULL
777
NULL
NULL
17
How can I SUM columns Dist1+Dist2 and Days1+Days2+Days3 to get that result
Desc_Cars
Sum_Dist
Sum_Days
Car1
599
15
Car2
2084
23
Car3
555
31
Car4
2341
31
I always operate on 1 DocID. Each DocID has always 2 tables: TabID 85 and 86
............................
Hi, the reason why I use Select in Select was that TabID 85 & 86 has values in other columns too
SELECT ID ,Desc_Cars ,DocID ,TabID
,Dist1
,Dist2
,Days1
,Days2
,Days3
FROM Details
where DocID = 16
ID
Desc_Cars
DocID
TabID
Dist1
Dist2
Days1
Days2
Days3
607
Car1
16
85
481
NULL
11
0
NULL
608
Car2
16
85
2072
NULL
21
2
NULL
609
Car3
16
85
333
NULL
15
6
NULL
610
Car4
16
85
1564
NULL
14
0
NULL
611
Car1
16
86
2129
118
10
2101
4
612
Car2
16
86
612
12
2
601
0
613
Car3
16
86
52
133
2
55
10
614
Car4
16
86
59
777
3
800
17
https://dbfiddle.uk/sAH7sv89
expected result, sum values like on picture:
Probably easiest to do with a self join:
select d1.Desc_Cars,
SUM(COALESCE(d1.Dist1, 0) + COALESCE(d2.Dist2, 0)) Sum_Dist,
SUM(COALESCE(d1.Days1, 0) + COALESCE(d1.Days2, 0) + COALESCE(d2.Days3, 0)) Sum_Days
from Details d1
join details d2
on d1.Desc_cars = d2.Desc_cars
and d1.tabid = d2.tabid-1
and d1.docid = d2.docid
where d1.DocID = 16
group by d1.Desc_Cars
Fiddle
#Jarlh:s version, letting the aggregate deal with nulls is more elegant in my opinion
select d1.Desc_Cars,
SUM(d1.Dist1) + SUM(d2.Dist2) Sum_Dist,
SUM(d1.Days1) + SUM(d1.Days2) + SUM(d2.Days3) Sum_Days
from Details d1
join details d2
on d1.Desc_cars = d2.Desc_cars
and d1.tabid = d2.tabid-1
and d1.docid = d2.docid
where d1.DocID = 16
group by d1.Desc_Cars
If tabid is not guaranteed to be consecutive, you can use row_number to match with next one:
with t (Desc_Cars, DocID, Dist1, Dist2, Days1, Days2, Days3, rn) AS (
select Desc_Cars, DocID, Dist1, Dist2, Days1, Days2, Days3
, row_number() over (partition by Desc_Cars, DocID order by tabid) as rn
from Details
)
select d1.Desc_Cars,
SUM(d1.Dist1) + SUM(d2.Dist2) Sum_Dist,
SUM(d1.Days1) + SUM(d1.Days2) + SUM(d2.Days3) Sum_Days
from t d1
join t d2
on d1.Desc_cars = d2.Desc_cars
and d1.rn = d2.rn-1
and d1.docid = d2.docid
group by d1.Desc_Cars;
Do a GROUP BY:
select Desc_Cars,
SUM(Dist1) + SUM(Dist2) Sum_Dist,
SUM(Days1) + SUM(Days2) + SUM(Days3) Sum_Days
from Details
where DocID = 16 -- <-- perhaps this condition is needed?
group by Desc_Cars

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

SQL aggregation query and sum columns

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.

Count and SUM using case

I have table like this, name: Table.dbo
Amount Desc Month SM code ID
$32,323.00 Bla1 1 121 3 2424221
$4,242.00 Bla2 1 A1 3 2424221
$3,535.00 Bla3 1 A3 1 3230824
$4,984.00 Bla4 1 433 1 3230824
$47,984.00 Bla5 1 B1 1 3230824
$3,472.00 Bla6 1 D2 27 2297429
$3,239.00 Bla7 1 124 27 2297429
$4,249.00 Bla8 1 114 24 3434334
$2,492.00 Bla9 1 132 24 3434334
$424.00 Bla10 2 232 3 2424221
$24,242.00 Bla7 2 124 3 2424221
$242,424 Bla4 2 433 1 3230824
$533.00 Bla13 2 235 1 3230824
$4,342.00 Bla14 2 223 1 3230824
$24,242.00 Bla15 2 224 27 2297429
$24,242.00 Bla1 2 121 27 2297429
$4,242.00 Bla17 2 432 24 3434334
$24,224.00 Bla9 2 132 24 3434334
I wrote this query :
select
[SM],
count(*) as TotalCntOfSM,
sum(case when [code] between 4 and 27 then 1 else 0 end) as TotalCntOfSM_R,
sum(case when [code] in (1,2,3) then 1 else 0 end) as TotalCntOfSM_B,
sum(case when [code] in (1) then 1 else 0 end) as TotalCntofSM_B1,
sum(case when [code] in (2) then 1 else 0 end) as TotalCntofSM_B2,
sum(case when [code] in (3) then 1 else 0 end) as TotalCntofSM_B3,
sum([Amount]) As TotalAmount
****[How can I sum the Amount for the SM if the code is between 4 and 27?** For example]**
from [Table]
group by [SM]
order by TotalCntOfSM desc
How can I sum the Amount for the SM if the code is between 4 and 27 or the code is in (1,2,3) only (For example).
Thank you very much!
Exactly like qxg said - Replace
****[How can I sum the Amount for the SM if the code is between 4 and 27?** For example]** `
with
sum(case when [code] between 4 and 27 then [Amount] else 0 end) as SMAmount
If you want to total up amount for code between 4 and 27 or for codes 1,2,3
sum(case when [code] between 1 and 27 then [Amount] else 0 end) as SMAmount
You can write the above also as
sum(case when [code] between 4 and 27 OR [code] in (1,2,3) then [Amount] else 0 end) as SMAmount

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