Add grand total to totals in SQL - sql-server-2008

I have the bellow query and it works.
I just need to add a line at the bottom that gives the grand total
SELECT ItemType.Description,
SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item
on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType
on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving
on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description

Use CTE and UNION the rows with grand total row.
with CTE
(
SELECT ItemType.Description,
SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where
InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description
)
SELECT Description,TOTAL FROM CTE
UNION
SELECT 'GRAND TOTAL',SUM(TOTAL) FROM CTE

use your returned result as temp result
;WITH TEMP AS(
SELECT ItemType.Description, SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item
on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType
on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving
on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description
)
SELECT * FROM TEMP
UNION
SELECT 'BIG SUM',SUM(TOTAL) TEMP

Related

Snowflake Function input is datetime, but when i call the function it's not quite working

with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test(temp.DateTime::DATETIME, 0))) --this works with datetime
when i run this query above, i get Processing aborted due to error 300010:391167117; incident 3245754.. I believe this is an issue with the temp.datetime -- when i run the same codebut hardcoding the function input, i get the desired output.
with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test('2021-12-02 10:03:0.00'::datetime, 0))) --this works with datetime
it seems that that somwehere along the line, it's not liking the date format i put in. it's not returning me an error of not liking the input.
here is the function.
CREATE OR REPLACE FUNCTION DB_BI_DEV.RAW_CPMS_AAR.cfn_GetShiftIDFromDateTime (dateTime TIMESTAMP_NTZ(9), shiftCalendarID int)
RETURNS table (shiftID int)
AS
$$
WITH T0 (ShiftCalendarID, CurDay, PrvDay)
AS (
SELECT TOP 1
ID AS ShiftCalendarID,
DATEDIFF( day, BeginDate, dateTime ) % PeriodInDays + 1 AS CurDay,
( CurDay + PeriodInDays - 2 ) % PeriodInDays + 1 AS PrvDay
FROM RAW_CPMS_AAR.ShiftCalendar
WHERE ID = shiftCalendarID
OR ( shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= dateTime )
ORDER BY BeginDate DESC
),
T1 (TimeValue)
AS (
SELECT TIME_FROM_PARTS(
EXTRACT(HOUR FROM dateTime),
EXTRACT(MINUTE FROM dateTime),
EXTRACT(SECOND FROM dateTime))
)
SELECT ID as shiftID
FROM RAW_CPMS_AAR.Shift, T0, T1
WHERE Shift.ShiftCalendarID = T0.ShiftCalendarID
AND ( ( FromDay = T0.CurDay AND FromTimeOfDay <= T1.TimeValue AND TillTimeOfDay > T1.TimeValue )
OR ( FromDay = T0.CurDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= T1.TimeValue )
OR ( FromDay = T0.PrvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > T1.TimeValue )
)
$$
;

SQLSERVER Running Balance

Actually i have problem on my query to get the running balance , i have debit and credit transaction i need one column to showing the cumulative running balance this is the code i used :
Select * From (
Select D.AccNo, H.[Date], A.AccountName, H.TrxNo,
(Case When ((D.Remark = '') or (D.Remark is Null)) Then H.Trxnote Else D.Remark End) As TrxDetailDescA,
(D.Debit * 1) AS DebitValue, (D.Credit * 1) AS CreditValue,SUM(COALESCE(D.Debit, 0) - COALESCE(D.Credit, 0)) AS Balance
From TblHeadTrans H, TblTransDetails D, TblAccount A
Where H.Guid = D.[LineNo]
And D.AccNo = A.AccountNo
And H.[Date] >= '01-01-2022' And H.[Date] <= '10-07-2022' And D.AccNo >= '1003'
group by AccNo,H.[Date],A.AccountName,H.TrxNo,D.Remark,h.Trxnote,d.Debit,d.Credit
Union All
Select D.AccNo, Null As TrxDate, A.AccountName, Null As TrxNo,
'Opening Balance' As TrxDetailDesc,
Case When (Sum(D.Debit * 1) - Sum(D.Credit *1)) < 0 then 0
Else (Sum(D.Debit * 1) - Sum(D.Credit * 1)) End As DebitValue,
Case When (Sum(D.Credit * 1) - Sum(D.Debit * 1)) < 0 then 0
Else (Sum(D.Credit * 1) - Sum(D.Debit * 1)) End As CreditValue
, SUM(COALESCE(d.Debit, 0) - COALESCE(d.credit, 0)) AS Balance
From TblHeadTrans H, TblTransDetails D, TblAccount A
Where H.guid = D.[LineNo] And D.AccNo = A.AccountNo
And d.[Date] < '01-01-2022' And D.accno = '1003'
Group By D.AccNo, A.AccountName,H.Date,H.TrxNo
) ReportData
WHERE 1=1
Order By AccNo, [Date], TrxNo
and the result showing as the picture:
the result

SSRS Predicament with expressions

I have an SSRS dataset that looks like this:
The dataset rows are generated independent of each other using UNION ALL.
I need to display these rows in my report as is, but I need to add an additional row that will calculate Total Won / Total Lost, so the result should look like this:
This is just sample as I have more columns (1 per month) and the whole thing is broken down by product, so if I have 10 different products, I will have 10 different tablix tables.
Basically I need to somehow create an expression that will only calculate values in 2 rows of the tablix out of 3 (based on the value of the Status column) and take into consideration that some values can be zeroes.
Here's the query (I simplified it a bit for better understanding):
select * from
(
select 'Created' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
) created
pivot
(
count(created.opportunityid)
for created.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivCreated
union all
select * from
(
select 'Won' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and regionalfeeincome >= 250000
and fo.jna is not null
) won
pivot
(
count(won.opportunityid)
for won.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivWon
union all
select * from
(
select 'Lost' as 'State', fo.groupidname, fo.businessidname ' Business', fo.opportunityid
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.actualclosedate >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
and fo.sys_phasename <> 'Pre-Bid'
) lost
pivot
(
count(lost.opportunityid)
for lost.groupidname in ([Boston], [Chicago], [Colombia], [Group D.C.], [Houston], [Los Angeles], [New York], [San Francisco], [Seattle], [Toronto])
) pivLost
TIA
-TS.
I can't fully test this as I don't have time to build sample data but it should work...
If you use this as your report's dataset query then you should be able to add a simple matrix with a row group by State and a column group by City
/*
You can optimise this a bit but I've kept it fairly procedural so it's easier to follow
*/
-- First do your 3 basic queries but this time we don't pivot and we dump the results into temp tables
-- I've also removed columns that don't appear to be used based on your sample output and remaned a column to City to make it easier to read
select 'Total Created' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Created
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
select 'Total Won' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Won
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
and fo.jna is not null
select 'Total Lost' as 'State', fo.groupidname as City, COUNT(*) AS Cnt
INTO #Lost
from FilteredOpportunity fo
where fo.regionidname = 'Americas Region'
and fo.createdon >= dateadd(year, -1, getdate())
and fo.regionalfeeincome >= 250000
and fo.sys_phasename <> 'Pre-Bid'
-- Now we calculate your Ratio
SELECT
'Win Ratio' as 'State'
, coalesce(w.City, l.City) as City -- use coalesce in case 1 side of join is null
, CASE WHEN ISNULL(l.cnt,0) = 0 THEN 0 ELSE w.Cnt/l.Cnt END as Cnt -- if lost is null or 0 return 0 else calc ratio
into #Ratio
FROM #Won w
full join #Lost l on w.City = l.City
-- finaly, get the results and add a sort to help the report row sorting.
SELECT 1 as Sort, * FROM #Created
UNION SELECT 2, * FROM #Won
UNION SELECT 3, * FROM #Lost
UNION SELECT 4, * FROM #Ratio

Creating a calendar in sql

We use a lookup table in a database for grouping weeks, months and years. Sadly the chap who created it has long since gone and the calendar runs out at the end of the year! So I really need to find a way of adding to it! Its set up with the following columns:
I'm not very good in sql(MS2008) to be honest and ive stuggeled with it, we cant set anything new up as everything is built around this!
you can do smth like this, but I don't get why your calendar starts from March?
declare #Date_Start date, #Date_End date
select #Date_Start = '20130101'
select #Date_End = '20131231'
;with
CTE_Dates as (
select #Date_Start as [Date]
union all
select dateadd(dd, 1, [Date])
from CTE_Dates
where [Date] < #Date_End
),
CTE_Calendar as (
select
[Date],
datename(dw, [Date]) as [Day],
datepart(ww, [Date]) as [Week],
datepart(mm, [Date]) as [MonthID],
dateadd(mm, datediff(mm, 0, getdate()), 0) as [Month],
datepart(yy, [Date]) as [YearID],
dateadd(yy, datediff(yy, 0, getdate()), 0) as [Year],
datepart(qq, [Date]) as [QuarterID],
dateadd(qq, datediff(qq, 0, getdate()), 0) as [Quarter]
from CTE_Dates
)
select
row_number() over (order by [Date]) + #Start_ID - 1 as ID,
*
from CTE_Calendar
option (maxrecursion 0)
SQL FIDDLE EXAMPLE

Group by, with rank and sum - not getting correct output

I'm trying to sum a column with rank function and group by month, my code is
select dbo.UpCase( REPLACE( p.Agent_name,'.',' '))as Agent_name, SUM(convert ( float ,
p.Amount))as amount,
RANK() over( order by SUM(convert ( float ,Amount )) desc ) as arank
from dbo.T_Client_Pc_Reg p
group by p.Agent_name ,p.Sale_status ,MONTH(Reg_date)
having [p].Sale_status='Activated'
Currently I'm getting all total value of that column not month wise
Name amount rank
a 100 1
b 80 2
c 50 3
for a amount 100 is total amount till now but , i want get current month total amount not last months..
Maybe you just need to add a WHERE clause? Here is a minor re-write that I think works generally better. Some setup in tempdb:
USE tempdb;
GO
CREATE TABLE dbo.T_Client_Pc_Reg
(
Agent_name VARCHAR(32),
Amount INT,
Sale_Status VARCHAR(32),
Reg_date DATETIME
);
INSERT dbo.T_Client_Pc_Reg
SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'NotActivated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()-40;
Then the query:
SELECT
Agent_name = UPPER(REPLACE(Agent_name, '.', '')),
Amount = SUM(CONVERT(FLOAT, Amount)),
arank = RANK() OVER (ORDER BY SUM(CONVERT(FLOAT, Amount)) DESC)
FROM dbo.T_Client_Pc_Reg
WHERE Reg_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
AND Reg_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
AND Sale_status = 'Activated'
GROUP BY UPPER(REPLACE(Agent_name, '.', ''))
ORDER BY arank;
Now cleanup:
USE tempdb;
GO
DROP TABLE dbo.T_Client_Pc_Reg;