So i have this:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(period)
FROM (SELECT DISTINCT period FROM atbv_Accounting_Transactions WHERE lAccountNO LIKE '6%' AND Period LIKE '2017%') AS Periods
SET #DynamicPivotQuery =
N'SELECT lAccountNo, ' + #ColumnName + '
FROM (SELECT
lAccountNo, period, SUM(Amount) As Total
FROM atbv_Accounting_Transactions
WHERE lAccountNO LIKE ''6%'' AND Period LIKE ''2017%''
GROUP BY lAccountNo, period
) AS T
PIVOT(SUM(TOTAL)
FOR period IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
It returns me this:
How do i remove decimal places within select itself. I cannot edit column in the table and reduce the decimal places.So i need to edit this query to return values without decimals.
Thanks!
Should just change SUM(Amount) to cast(SUM(Amount) as int) or perhaps floor(SUM(Amount)) and it will do the trick.
Related
I was trying to do a dynamic pivot on two columns to rearrange some data. Her is my original table:
Initial table
I used the flowing code to pivot the BRAND based on CountryID and GenericArticle but I get following result (as you can see the table doesn't seem to be GROUPed BY)
Result after pivot
Here is my Pivot Code:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Brand)
FROM (SELECT DISTINCT [Brand]
FROM #tempProgCov) AS Country
SET #DynamicPivotQuery =
N'SELECT [CountryID], [GenericArticle], ' + #ColumnName + '
INTO ##ProgCovPivot
FROM #tempProgCov as Src
PIVOT
(
SUM([Coverage])
FOR [Brand] IN (' + #ColumnName + ')
) as Pvt'
EXEC sp_executesql #DynamicPivotQuery
Any help highly appreciated, thx!
PS, was expecting something like this:
Desired result
Never-mind, I solved it eventually, was just under my eye. Problem was in source table select:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Brand)
FROM (SELECT DISTINCT [Brand]
FROM #tempProgCov) AS Country
SET #DynamicPivotQuery =
N'SELECT [CountryID], [GenericArticle], ' + #ColumnName + '
INTO ##ProgCovPivot
FROM (SELECT CountryID,
Brand,
GenericArticle,
Coverage
FROM #tempProgCov) as Src
PIVOT
(
SUM([Coverage])
FOR [Brand] IN (' + #ColumnName + ')
) as Pvt'
EXEC sp_executesql #DynamicPivotQuery
I'm trying to use This question to perform a dynamic pivot, but I want to use a CTE to get the initial data.
My query looks like this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
WITH dataSet (coDate, TransactionDate, TotalBalance, TransDate, collected)
AS
( *SELECT STATEMENT )
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category)
FROM dataSet c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT coDate, ' + #cols + ' from
(
select coDate
, TotalBalance
, collected
, TransDate
from dataSet
) x
pivot
(
SUM(collected)
for category in (' + #cols + ')
) p '
execute(#query)
And the error SQL gives me is Incorrect syntax near the keyword 'SET'. I did try adding a semicolon and go as well as a comma before the SET statement, but this the first time I've used PIVOT so I'm not sure how CTE interacts with it.
I have a text field in my database:
DECLARE #vchText varchar(max) =
This is a string<>Test1<>Test2<>Test
That #vchText parameter should return like this:
This is a string:
1. Test1
2. Test2
3. Test
Anyone think of a good way to correct this. I was thinking the STUFF and CHARINDEX Functions with a WHILE LOOP...?
Something I should also note would be that there might not be only 1,2,3 items in the list there could be lots more so I can't build it so its static and only handles 1,2,3 it should be able to work for any number of items in the list.
Try this. Break the string into parts.
First part - This is a list:
Second part - 1.Test1 1.Test2 1.Test3
Convert the second part into rows using the delimiter Space. Then add row_number to the rows. Append the row_number and column data.
Finally convert the different rows into single row delimited by space and append it with the first part
DECLARE #NOTE VARCHAR(max) = 'This is a list: 1.Test1 1.Test2 1.Test3',
#temp VARCHAR(max),
#output VARCHAR(max)
SELECT #temp = Substring(#NOTE, Charindex(':', #NOTE) + 2, Len(#note))
SELECT #output = LEFT(#NOTE, Charindex(':', #NOTE) + 1)
SELECT #output += CONVERT(VARCHAR(10), Row_number() OVER (ORDER BY col))
+ Substring(col, Charindex('.', col), Len(col))
+ ' '
FROM (SELECT Split.a.value('.', 'VARCHAR(100)') col
FROM (SELECT Cast ('<M>' + Replace(#temp, ' ', '</M><M>') + '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) ou
SELECT #output -- This is a list: 1.Test1 2.Test2 3.Test3
I was able to do it with a loop and use the stuff and charindex below.
DECLARE #vchText varchar(max) =
This is a string<>Test1<>Test2<>Test
DECLARE #positionofNextX INT = CHARINDEX('<>', #vchText)
DECLARE #nbrOFListItems INT = 1
WHILE #positionofNextX != 0
BEGIN
SET #NOTE = STUFF( #vchText, #positionofNextX, 4, CAST(#nbrOFListItems AS VARCHAR(1)) + '. ')
SET #positionofNextX = CHARINDEX('<>', #vchText)
--increment the list item number
SET #nbrOFListItems = #nbrOFListItems + 1
END
print #vchText
I am examining a third party SQL Server 2008 database. In this database, there are 2 columns CREATED_DATETIME and UPDATED_DATETIME, which are present in majority of the tables, but probably not all.
I want to find the minimum and maximum value of these 2 columns across all tables in the database which have these 2 columns. That will give me a fair idea that the data in the database is from which period to which period.
How can I write such a query?
Something like the following should work
DECLARE #C1 AS CURSOR,
#TABLE_SCHEMA SYSNAME,
#TABLE_NAME SYSNAME,
#HasCreated BIT,
#HasUpdated BIT,
#MaxDate DATETIME,
#MinDate DATETIME,
#SQL NVARCHAR(MAX)
SET #C1 = CURSOR FAST_FORWARD FOR
SELECT TABLE_SCHEMA,
TABLE_NAME,
COUNT(CASE
WHEN COLUMN_NAME = 'CREATED_DATETIME' THEN 1
END) AS HasCreated,
COUNT(CASE
WHEN COLUMN_NAME = 'UPDATED_DATETIME' THEN 1
END) AS HasUpdated
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ( 'CREATED_DATETIME', 'UPDATED_DATETIME' )
GROUP BY TABLE_SCHEMA,
TABLE_NAME
OPEN #C1;
FETCH NEXT FROM #C1 INTO #TABLE_SCHEMA , #TABLE_NAME , #HasCreated , #HasUpdated ;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = N'
SELECT #MaxDate = MAX(D),
#MinDate = MIN(D)
FROM ' + QUOTENAME(#TABLE_SCHEMA) + '.' + QUOTENAME(#TABLE_NAME) + N'
CROSS APPLY (VALUES ' +
CASE WHEN #HasCreated = 1 THEN N'(CREATED_DATETIME),' ELSE '' END +
CASE WHEN #HasUpdated = 1 THEN N'(UPDATED_DATETIME),' ELSE '' END + N'
(#MaxDate),
(#MinDate)) V(D)
'
EXEC sp_executesql
#SQL,
N'#MaxDate datetime OUTPUT, #MinDate datetime OUTPUT',
#MaxDate = #MaxDate OUTPUT,
#MinDate = #MinDate OUTPUT
FETCH NEXT FROM #C1 INTO #TABLE_SCHEMA , #TABLE_NAME , #HasCreated , #HasUpdated ;
END
SELECT #MaxDate AS [#MaxDate], #MinDate AS [#MinDate]
select MIN(CREATED_DATETIME) MinCREATED_DATETIME_Table1, MAX(CREATED_DATETIME) MaxCREATED_DATETIME_Table1, MIN(CREATED_DATETIME) MinCREATED_DATETIME_Table2, MAX(CREATED_DATETIME) MaxCREATED_DATETIME_Table2 from Table1, Table2
Run this script in SSMS (CTrl+T=text results, F5=execute query):
SET NOCOUNT ON;
SELECT 'SELECT MIN('
+ QUOTENAME(c.COLUMN_NAME)
+ ') AS '
+ QUOTENAME('Min '+c.TABLE_NAME+'.'+c.COLUMN_NAME)
+ ', MAX('
+ QUOTENAME(c.COLUMN_NAME)
+ ') AS '
+ QUOTENAME('Max_'+c.TABLE_NAME+'.'+c.COLUMN_NAME)
+ CHAR(13)
+ 'FROM ' + QUOTENAME(c.TABLE_SCHEMA)+'.'+QUOTENAME(c.TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.COLUMN_NAME IN ('CREATED_DATETIME', 'UPDATED_DATETIME')
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME;
SET NOCOUNT OFF;
It will generate another script. Execute generated script.
Example (generated script for master database and all tables with low column name > WHERE c.COLUMN_NAME IN (N'low')):
SELECT MIN([low]) AS [Min spt_fallback_dev.low], MAX([low]) AS [Max_spt_fallback_dev.low]
FROM [dbo].[spt_fallback_dev]
SELECT MIN([low]) AS [Min spt_values.low], MAX([low]) AS [Max_spt_values.low]
FROM [dbo].[spt_values]
Run the script mentioned in the link below. You will have to slightly alter as per your requirements.
SCRIPT to Search every Table and Field
I am working on a appliaction in which I have a following schema
Tasks Master
Task_ID
Task_Name
Task_Details
Task_ID
Task_Date
Task_Count (can be any number like 2 or 3 or 4 or 40)
the Input Form is like that which the staff will fill at the end of the day.
Date | Task Name | Task_Count
24/01/2010 | How many cheque books issued today | 12
24/01/2010 | How many ATM Issued today | 7
Now I want a matrix report showing all tasks suppose 28 tasks in vertical row and on given month it should show all the dates of the particular month horizontal direction like from 1 to 31 days or 30 or 28 as per month days with the task_count using PIVOT in query. i am failed to produce the result as i dont know to make it work. please help.
thanks
You'll need to use a dynamic query since the columns returned by the pivot changes each month.
With some time this could probably be made more elegant, but here's the basic idea:
declare #StartOfMonth datetime = '11/1/2010';
declare #counter datetime = #StartOfMonth;
declare #sql varchar(MAX) = '';
declare #columnnames varchar(MAX);
declare #columnfilter varchar(MAX);
declare #fieldname varchar(12);
--First, create a string of dynamic columns, one for each day of the month.
WHILE (MONTH(#counter) = MONTH(#StartOfMonth))
BEGIN
SET #fieldname = '[' + CONVERT(varchar(10), #counter, 101) + ']';
--Wrap the columns in ISNULL(#,0) to avoid having null values for days without tasks.
SET #columnnames = ISNULL(#columnnames + ',', '') + 'ISNULL(' + #fieldname + ',0) AS ' + #fieldname;
--Also create a dynamic list of the Task_Date values to include in the pivot.
SET #columnfilter = ISNULL(#columnfilter + ',', '') + #fieldname;
SET #counter = DATEADD(DAY,1,#counter);
END
--Put it all together into a pivot query.
set #sql = 'SELECT Task_Name, ' + #columnnames + ' FROM (';
set #sql = #sql + 'SELECT M.Task_Name, D.Task_Date, D.Task_Count '
set #sql = #sql + 'FROM Task_Detail D JOIN Task_Master M ON D.Task_ID = M.Task_ID) as SourceTable ';
set #sql = #sql + 'PIVOT (SUM(Task_Count) FOR Task_Date IN (' + #columnfilter + ')) AS PivotTable';
exec (#sql)