SQL Pivot Table Subtotal Syntax error - sql

Hoping someone can help me. I was able to put together this SQL script but it coming back with minor errors here and there. I'be been trying to debug for over a week now. Please help. the first error message is "Incorrect syntax near ')'." If you fixe that it keeps on throwing more out so I'm thinking I'm not coding this correctly. I am unable to save changes that do work. it tell me the save request was aborted. Working with SQL Server 2008 r2
SELECT
PublicationID AS PubID, (PubNum + '- ' + PubTitle) AS [Pub Descr],
CONVERT(Varchar(10), [Datestamp], 101) AS [Date Printed],
QtyPrinted AS [Qty Printed],
[2] AS [Tyler Inventory],
[1] AS [Central Inventory],
[3] AS [Mailing House Inventory],
(
SELECT SUM(S)
FROM
(
SELECT [1] UNION ALL
SELECT [2] UNION ALL
SELECT [3]
) AS T (S)) AS [Current Inventory],
RecycledQty AS [Recycled],
MailingVendorName AS [Mailing Vendor],
PrintVendorName AS [Print Vendor]
FROM
(
SELECT
PublicationID, LocationID, Balance, PubNum,
PubTitle, ItemPerCase, Datestamp, Deleted,
RecycledQty, MailingVendorName, PrintVendorName,
QtyPrinted
FROM
(
dbo.view_PubInventory_Main_Summary_RAW) x PIVOT (sum(balance) FOR
LocationID IN ([1], [2], [3])) p)
SELECT *
FROM
(SELECT PUBID, [Pub Descr], [Date Printed], [Qty Printed],
[Tyler Inventory], [Central Inventory],
[Mailing House Inventory], [Current Inventory], [Recycled],
[Mailing Vendor]
FROM GG
) AS T

Hard to follow exactly what you're after, but I think you want Current Inventory to just be [1]+[2]+[3], and you didn't alias your subquery. The query at the bottom looks fine.
SELECT PublicationID AS PubID
, PubNum + '- ' + PubTitle AS [Pub Descr]
, CONVERT(VARCHAR(10), [Datestamp], 101) AS [Date Printed]
, QtyPrinted AS [Qty Printed]
, [2] AS [Tyler Inventory]
, [1] AS [Central Inventory]
, [3] AS [Mailing House Inventory]
, [1]+[2]+[3] AS [Current Inventory]
, RecycledQty AS [Recycled]
, MailingVendorName AS [Mailing Vendor]
, PrintVendorName AS [Print Vendor]
FROM ( SELECT PublicationID
, LocationID
, Balance
, PubNum
, PubTitle
, ItemPerCase
, Datestamp
, Deleted
, RecycledQty
, MailingVendorName
, PrintVendorName
, QtyPrinted
FROM dbo.view_PubInventory_Main_Summary_RAW
PIVOT ( SUM(balance) FOR LocationID IN ( [1], [2], [3] ) ) p
)AS Sub

Related

Insert into table when the day is Monday

Is there a way in which I can insert data from one table into another when today is Monday?
I tried making something like the below, using CASE WHEN, however it doesn't quite work right, any help would be welcomed
INSERT INTO [dbo].[WF_All]
SELECT (CASE WHEN (DATENAME(WEEKDAY,FLOOR(convert(float,getdate()))))='MONDAY' THEN
(
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
)
ELSE NULL END )
yes , like this :
INSERT INTO [dbo].[WF_All]
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
WHERE DATENAME(WEEKDAY,GETDATE()) = 'Monday'
or
... WHERE DATEPART(WEEKDAY, GETDATE()) = 2 --Monday
Is this what you want.
if datename(weekday,getdate()) = 'MONDAY' then
INSERT INTO [dbo].[WF_All] (
-- column names go here
)
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]

SQL Case Expression with a Where Clause

I have the following example Data set that was created by the following query that sets an employee as "Active' or 'Inactive" based on if they worked any hours during a month.
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name]
FullName
Status
Alan Brewer
Active
Alejandro McGuel
Inactive
Alex Nayberg
Active
Im trying to get rid of all the 'Active' Status rows so that my query only displays those who are 'inactive'. I attempted to add WHERE Status = Inactive between the FROM and GROUP BY expression but it returns no results. (Does not give an error, just returns empty columns).
Anyone know what I am missing?
You can't add a WHERE condition on the Status column just like that since it's not available to WHERE clause .. you can use that query as inline view and do the condition check in outer query like
select * from (
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name] ) xxx
where Status != 'Active';
You need a HAVING clause, but also for your requirement you don't need the CASE expression:
SELECT CONCAT([First Name],' ', [Last Name]) AS FullName,
'Inactive' [Status]
FROM dbo.hours
GROUP BY [first name], [last name]
HAVING SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]) = 0
CTE will work as well:
with cte as(
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name])
select FullName from cte where Status <> 'Active'

How can I use Sum, Cast and Partition by functions together?

How can I use Sum, Cast and Partition by functions together?
I get error.
Conversion failed when converting the nvarchar value '693.41' to data
type int."
I tried this
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Full query is at the below.
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],[Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
First, identify the rows that have problems. You are converting to an int, so:
select price
from Testing2
where try_convert(int, price) is null and price is not null;
At least some of the values will have decimal points (as in your example). To see if this is the only problem, I would suggest converting to a decimal next:
select price
from Testing2
where try_convert(decimal(20, 4), price) is null and price is not null;
If this returns nothing, you are set. If not, you will need to figure out how to address these exceptions.
Then, I would phrase the calculation using decimals and not floats:
SUM(TRY_CAST([total price] AS DECIMAL(20, 4))) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Monetary amounts should generally be represented using fixed-point values rather than approximate floating point values. The issue with floating point values is that information may be lost. Consider this example with reals:
select cast(1000000 as real) + cast(0.01 as real),
cast(1000000 as decimal(20, 4)) + cast(0.01 as decimal(20, 4))
Integer will not have decimal values, and it will throw an error.
If I use this, similar to the example you have.
Declare #val nvarchar(10) = '10.24'
select cast (#val as int)
I get this following error.
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value '10.24' to data type int.
Now to avoid this error, I can round the digit to 0 decimal places and convert as Int. Also, I would recommend to use Try_Cast to avoid any cases of actual nvarchar values(it would convert it to null) if you are using sql server 2012 or more.
Declare #val nvarchar(10) = '10.24'
select Try_cast (round(#val,0) as int) as valuen
Output, I think this will work in your sum function.
valuen
10
Why don't you cast it in inner query with decimal(16,9) instead of int
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM([total price]) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],cast([Total Price] as decimal(16,9)) as [Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
If you have a combination of string and number as your column value and you want to sum up the number. For SQL Server 2012+ you can use TRY_CAST or TRY_CONVERT to avoid any casting errors.
TRY_CAST (Transact-SQL)
In your scenario, you are not using proper data type for casting, you have values like 693.41 which can't be casted to INT, instead you should use DECIMAL datatype.
One more suggestion, instead of using NOT LIKE, better use <> in SQL Server like following.
Change
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
to
([Date] <> '0' OR JOB# <> '0' OR [JOB TYPE] <> '0')
One possible solution is to firstly convert the nvarchar value to decimal and then to integer:
CAST(CAST([total price] AS FLOAT) AS INT)
However, in this way the decimal part is lost if it matters to you.

SQL - UNION ALL instead of JOIN

Can someone please help me figure out how to write this script using UNION ALL? Currently it is using JOIN instead of UNION ALL.
SELECT
ISNULL(#vol2016.Destination, #vol2017.Destination) AS [Destination],
ISNULL(#vol2016.[Volume 2016],0) AS [Volume 2016],
ISNULL(#vol2017.[Volume 2017],0) AS [Volume 2017],
ISNULL(#vol2017.[Volume 2017],0) - ISNULL(#vol2016.[Volume 2016],0) AS [Developement]
FROM(
SELECT
[year], [Destination], CAST(SUM([Volume]) as INT) as [Volume 2016]
FROM [dbo].[dw_lc_full_aggregated_1]
WHERE [entry_type] = 'Country upload'
AND [year]='2016'
GROUP BY [year], [Destination]) #vol2016
FULL JOIN
(SELECT
[year], [Destination], CAST(SUM([Volume]) as INT) as [Volume 2017]
FROM [dbo].[dw_lc_full_aggregated_1]
WHERE [entry_type] = 'Country upload' AND [year]='2017'
GROUP BY [year], [Destination]) #vol2017
ON [#vol2016].Destination=[#vol2017].Destination
So the output should be in three columns. Destination, Volume 2016, Volume 2017.
Use this query:
SELECT [year]
, [Destination]
, CAST(SUM([Volume]) as INT) AS [Volume]
FROM
(
SELECT [year]
, [Destination]
, [Volume]
FROM [dbo].[dw_lc_full_aggregated_1]
WHERE [entry_type] = 'Country upload' AND [year]='2016'
UNION ALL
SELECT [year]
, [Destination]
, [Volume]
FROM [dbo].[dw_lc_full_aggregated_1]
WHERE [entry_type] = 'Country upload' AND [year]='2017'
) AS T
GROUP BY [year],[Destination]
You can actually make life a lot more simple for yourself with conditional aggregation (A CASE statement inside the SUM())
SELECT
[Destination],
[Volume_2016],
[Volume_2017],
[Volume_2017] - [Volume_2016] AS [Development]
FROM
(
SELECT
[Destination],
CAST(SUM(CASE WHEN [year] = '2016' THEN [Volume] END) as INT) [Volume_2016],
CAST(SUM(CASE WHEN [year] = '2017' THEN [Volume] END) as INT) [Volume_2017]
FROM
[dbo].[dw_lc_full_aggregated_1]
WHERE
[entry_type] = 'Country upload'
AND [year] IN ('2016', '2017')
GROUP BY
[Destination]
)
AS pivoted_agreggate
EDIT: [Year] removed from GROUP BY (copy and paste error)

Arithmetic overflow error converting expression to data type datetime in SQL Server 2008

I am executing below SQL Script which is throwing error Arithmetic overflow error converting expression to data type datetime
I have searched for this error in SO and google but I'm not able to figure out the solution.
Below is mine Longggggggggg SQL Query
DECLARE #TimeByDay DATETIME
DECLARE #TimeByDay2 DATETIME
SET #TimeByDay = '1/1/2012'
SET #TimeByDay2 = '12/31/2014'
SELECT p1.ProjectName ,
p1.EnterpriseProjectTypeName ,
p1.[Legacy System ID] ,
p1.ProjectDescription ,
p1.ProjectOwnerName ,
p1.[Gate Approvers] ,
p1.[Team Members] ,
p1.[Project Sponsor] ,
p1.[Idea Project Type] ,
p1.[Compliance Project] ,
p1.[Product Category] ,
p1.[Relevant Functional Area] ,
p1.Initiative ,
p1.[OPEX Transformation] ,
p1.[Commodity Type] ,
p1.[LSS Training Project] ,
p1.[Project Status Comments] ,
p1.[Project Status] ,
p1.Phase ,
p1.[Innovation Matrix Class] ,
p1.[Legacy Project Manager] ,
p1.[AOP Line Number] ,
p1.[AOP Project Name] ,
p1.[Approval Level] ,
p1.Assumptions ,
p1.[Belt Name] ,
p1.[Benefits Impact] ,
p1.[Bus Impact or Bus Y] ,
p1.[Business Sponsor] ,
p1.[Code Name] ,
p1.[Complexity Risk Level] ,
p1.[Complexity Risk Score] ,
p1.[Critical to Quality] ,
p1.Deliverables ,
p1.[Development Risk] ,
p1.[Estimated Duration] ,
p1.[Financial Uncertainty] ,
p1.[Financial Rep] ,
p1.[External Dependencies] ,
p1.[Financial Risk Level] ,
p1.[Financial Risk Score] ,
p1.[Idea Functional Area] ,
p1.[Idea Beneftting Location] ,
p1.[Idea Reviewer Comments] ,
p1.[Idea Comments] ,
p1.[Idea Sector] ,
p1.[Idea Submitters Email] ,
p1.[Idea Submission Date] ,
p1.[Idea Submitter Phone] ,
p1.[Idea Reviewer Name] ,
p1.[Idea Description_] ,
p1.[Idea Est Revenue Benefit] ,
p1.[Idea Name] ,
p1.[Idea Product Category] ,
p1.[Idea Est Savings Benefit] ,
p1.[Idea Number] ,
p1.[Idea Review Date] ,
p1.[Idea Est Balance Sheet Benefit] ,
p1.[Idea Est Investment] ,
p1.[Idea Submitter Email] ,
p1.[IR Project Type] ,
p1.[Idea Sources] ,
p1.[Idea Submitter] ,
p1.[Implementation Risk] ,
p1.[Technology Capabilities Risk] ,
p1.[Market Uncertainty] ,
p1.[Legal Regulatory Risk] ,
p1.[Investment Risk] ,
p1.Mentor ,
p1.[Out of Scope] ,
p1.[Project Scope] ,
p1.[Project Start Date] ,
p1.[Project Finish Date] ,
p1.[Mandated by whom?] ,
p1.[Reason for Action] ,
p1.[Project Champion] ,
p1.[Process Owner] ,
p1.[Target State (Box 3 of A3)] ,
p1.[Problem Statement] ,
p1.[Project Interaction] ,
p1.[Strategic Goal/Business Case] ,
p1.[Sending Leader(s)] ,
p1.[Receiving Leader(s)] ,
p1.[Process Definition] ,
p1.[Things That Can Be Improved] ,
p1.[Idea Estimated Duration] ,
p1.[ST IT Cost Center] ,
p1.[Top Project] ,
p1.[Reason For Action (Box 1 of A3)] ,
p1.[Initial State] ,
p1.[Impact of not meeting mandate] ,
p1.[Primary Proponent Department] ,
p1.[Project Financial Benefit Status] ,
p1.[Project Resource Status] ,
p1.[Project Schedule Status] ,
p1.[Project Investment Status] ,
p1.[Project Success Factors] ,
p1.[Support Required] ,
p1.[Project Milestones] ,
p1.[Project Constraints] ,
p1.[Other Funding Source] ,
p1.[Project Cost Center] ,
p1.[Initial State (Box 2 of A3)] ,
p1.CostCenterName ,
p1.CostCategoryName ,
YEAR(p1.TimeByDay) AS Year ,
MONTH(p1.TimeByDay) AS Month ,
p1.Actuals ,
p1.Budget ,
p1.Forecast ,
p1.PhaseName ,
p1.ProjectUID ,
CONVERT(VARCHAR(20), p1.ProjectCreatedDate, 101) AS ProjectCreatedDate ,
CONVERT(VARCHAR(20), p1.ProjectModifiedDate, 101) AS ProjectModifiedDate
FROM [IR.ST.EPM Custom Flds and Financial Data] p1
--WHERE p1.TimeByDay >= CAST(#TimeByDay AS DATETIME)
-- AND p1.TimeByDay <= CAST(#TimeByDay2 AS DATETIME)
WHERE p1.timebyday >= #TimeByDay
AND p1.timebyday <=#TimeByDay2
AND p1.StageEntryDate IS NOT NULL
AND p1.StageCompletionDate IS NOT NULL
I'm not sure what needs to be change here.
Sorry for duplicate!
It's the start of your script where you assign strings to DATETIMEs. This involves an implicit conversion, as if the RDBMS adds the CONVERT() in there for you. And in your case it's failing.
Try a more universal date-time format instead...
SET #TimeByDay = '20120101'
SET #TimeByDay2 = '20141231'