Currently my select will return multiple districts for each of the users. I would like to combine the multiple districts into one string field.
Current proc:
ADName
DistrictID
Glenn Stalions
9
Bob Smith
9
Pam Cassidy
-1
Shannon Sanchez
1234
Shannon Sanchez
1355
Change to:
ADName
DistrictID
Glenn Stalions
9
Bob Smith
9
Pam Cassidy
-1
Shannon Sanchez
1234, 1355
If the user is managing more than one district the proc would return a single feild with a csv string of all districts.
I have tried pivot's and it returns multiple columns which I don't want. In addition, I have to hard code 300+ district id's to get the pivot to work correctly.
Something like this will work but I want to call it each row and not for the entire proc:
declare @csv varchar(max)
(SELECT @csv = coalesce(@csv+', ','' ) +
cast(districtid as varchar) FROM #district)
select @csv
insert into @log(date, category, value1, value2) select '2008-01-01', 'ABC', 11,12 union all select '2008-01-02', 'ABC', 35,53 union all select '2008-01-03', 'ABC', 38,62 union all select '2008-01-05', 'ABC', 59,95 union all select '2008-01-02', 'XYZ', 42,21 union all select '2008-01-04', 'XYZ', 9,7 union all select '2008-01-05', 'XYZ', 89,45 union all select '2008-01-01', 'HHH', 70,52 union all select '2008-01-03', 'HHH', 3,83 union all select '2008-01-05', 'HHH', 26,77
where 1) date is always up to the day (no time variation) 2) date and category can be considered a composite unique key
Given a date range (let's say, from 2008-01-01 to 2008-01-05) I need to get the below:
Ideally, the results include - every day in the date range (even if there is no corresponding data for that date) - the columns values to be dependent on the categories found within the date range
I came up with this
-- to fulfill requirement "every day in the date range" declare @dt table (d smalldatetime) insert into @dt select '2008-01-01' union all select '2008-01-02' union all select '2008-01-03' union all select '2008-01-04' union all select '2008-01-05'
-- to fulfill display all the categories (manually determined) select convert(varchar(10),d,101) as date, abc.value1 as abc_value1, abc.value2 as abc_value2, xyz.value1 as xyz_value1, xyz.value2 as xyz_value2, hhh.value1 as hhh_value1, hhh.value2 as hhh_value2 from @dt dt left join @log abc on dt.d = abc.date and abc.category = 'ABC' left join @log xyz on dt.d = xyz.date and xyz.category = 'XYZ' left join @log hhh on dt.d = hhh.date and hhh.category = 'HHH'
just for the purpose of generating the end result example, but in a real life situation, both the date range and the categories that may fall within that date range... are dynamic. To make my head spin even more, I also suspect the issue of value2 AND value3 being pulled is making this one complicated statement.
From the above I wanted to create a pivot table, from there I want to pass the column values through to a UDF
XSection (Width, Height, Flange, Leg, LegCount)
I tried the following to get a pivot table but it does not give a single row but 5.
SELECT CASE sp.PropertyName WHEN 'Width' THEN tsp.PropertyValue ELSE 0 END AS Width, CASE sp.PropertyName WHEN 'Height' THEN tsp.PropertyValue ELSE 0 END AS Height, CASE sp.PropertyName WHEN 'Flange' THEN tsp.PropertyValue ELSE 0 END AS Flange, CASE sp.PropertyName WHEN 'Avg. Leg Width' THEN tsp.PropertyValue ELSE 0 END AS Leg, CASE sp.PropertyName WHEN 'Leg Count' THEN tsp.PropertyValue ELSE 0 END AS LegCount FROM tbTemplateShapeProperties AS tsp INNER JOIN tbShapeProperties AS sp ON tsp.fkProperty = sp.Property WHERE tsp.fkTemplate = 1
So, this leaves me with one question, even if I was to get this to work, is is possible to then extract the values and pass them through to the UDF within the same stored proc?
Code Snippet DECLARE @start_date datetime, @weeks int
SET @start_date = '1/1/2007'/*Set this to the date you want your analysis to begin on. Be mindful of the date you pick. For instance, in this case we want the beginning of the week to always be a Monday so we are OK picking 1/1/2007 because it is a Monday.*/ SET @weeks = 12
SELECT DATEADD(dd, (n.Num-1) * 7, @start_date) [Beginning of Week], /*This is creating the Beginning of each week. Looks at each record in the Number table, subtracts one off of the Num field and then multiplies by 7. Takes the resulting number and adds that many days to our start date variable.*/ DATEADD(dd,(n.Num * 7)-1,@start_date) [End of Week], /*This is creating the Ending of each week. Looks at each record in the Number table, muiltplies it by 7 and then subtracts one off of the result. Takes the resulting number and adds that many days to our start date varaible.*/ ( /*This is where we are counting the number of opportunities in each week. This returns a reasulting count for each combination that is generated in the outer query.*/ SELECT COUNT(*) FROM op_opportunity op_o WHERE op_o.open_date BETWEEN DATEADD(dd, (n.Num-1) * 7 , @start_date) AND DATEADD(dd, (n. Num * 7)-1, @start_date) /*Count if the open date is between what we've identified as the Beginning of Week and End of Week for each iteration.*/ ) AS [Opportunities Open] FROM Numbers n WHERE DATEADD(dd,n. Num * 7,@start_date) >= DATEADD(wk, -@weeks+1, GETDATE()) AND DATEADD(dd,n. Num * 7,@start_date) <= DATEADD(wk, 1, GETDATE()) /*We are just limiting our evaluation to anything less than todays date and within the number of weeks in our @week variable.*/
It returns a result set that looks like this:
Code Snippet Beginning of Week End of Week Opportunities Open 11/5/2007 12:00:00 AM 11/11/2007 12:00:00 AM 369 11/12/2007 12:00:00 AM 11/18/2007 12:00:00 AM 326 11/19/2007 12:00:00 AM 11/25/2007 12:00:00 AM 203 11/26/2007 12:00:00 AM 12/2/2007 12:00:00 AM 333 12/3/2007 12:00:00 AM 12/9/2007 12:00:00 AM 421 12/10/2007 12:00:00 AM 12/16/2007 12:00:00 AM 286 12/17/2007 12:00:00 AM 12/23/2007 12:00:00 AM 411 12/24/2007 12:00:00 AM 12/30/2007 12:00:00 AM 48 12/31/2007 12:00:00 AM 1/6/2008 12:00:00 AM 234 1/7/2008 12:00:00 AM 1/13/2008 12:00:00 AM 314 1/14/2008 12:00:00 AM 1/20/2008 12:00:00 AM 309 1/21/2008 12:00:00 AM 1/27/2008 12:00:00 AM 207
What I want to do is change this so that I can get a count of new opportunties by week but also by rep. In the op_opportunity table there is a field called sales_owner that I would use. Ideally, I also want to have it Pivoted so that the weeks are columns and the sales_owner are the rows. I tried using the PIVOT command but you have to explicitly indicate your columns. Because the number of weeks that are chosen could always be different I can't do that.
Ultimately, this will be presented through reporting services so I can probably use the Cross Tab tool to show it the way I want, so if I could just get the same result set but instead the rep added and the opportunities they created that would probably work. So if we had 12 weeks and 10 reps that would produce 120 rows.
I also hardcoded the @startdate to 1/1/07 because that is a Monday and it is back far enough in the past that I don't have to worry. As we get further away from that date will that cause any performance issues?
Hi All, The problem is about cross reference. 1. I have a third party cross reference store procedure SimpleXTab CREATE PROCEDURE [dbo].[SimpleXTab2] @XField varChar(50), @XTable varChar(100),@XWhereString varChar(250), @XFunction varChar(10), @XFunctionField varChar(50), @XRow varchar(300),@ResultTable varchar(100) ASDeclare @SqlStr nvarchar(4000)Declare @tempsql nvarchar(4000)Declare @SqlStrCur nvarchar(4000)Declare @col nvarchar(100) set @SqlStrCur = N'Select [' + @XField + '] into ##temptbl_Cursor from [' + @XTable + '] ' + @XWhereString + ' Group By [' + @XField + ']' /* select @sqlstrcur */exec sp_executesql @sqlstrcur
declare xcursor Cursor for Select * from ##temptbl_Cursor open xcursor Fetch next from xcursor into @Col While @@Fetch_Status = 0Begin set @Sqlstr = @Sqlstr + ", " set @tempsql = isnull(@sqlstr,'') + isnull(@XFunction + '( Case When ' + @XField + " = '" +@Col + "' then [" + @XFunctionField + "] Else 0 End) As [" + @Col + "]" ,'') set @Sqlstr = @tempsql Fetch next from xcursor into @Col End /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */ set @tempsql = 'Select ' + @XRow + ', ' + @Sqlstr + 'into ' +@ResultTable+' From ' + @XTable + @XWhereString + ' Group by ' + @XRowprint @tempsql set @Sqlstr = @tempsql Close xcursor Deallocate xcursor set @tempsql = N'Drop Table ##temptbl_Cursor' exec sp_executesql @tempsqlprint @tempsql /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */print @sqlstr exec sp_executesql @Sqlstr if @@rowcount = 0 select 'No Records found'GO 2. I've use this store procedure for many cross reference successfully. But this time my cross reference value (resultcode) is a varchar which cannot be convert to int or decimal in sql, Probably, you've noticed that the fourth parameter is a function. how can i modify SimpleXtab to avoid using math function but still can generate cross reference. exec simplextab2 'Sequence','##tbltempreport',' ','sum','resultcode','Parameter' ,'dbo.resultcodetable'
I have information on clothes in a table that I want to select out to a result set in a different structure - I suspect that this will include some kind of pivot (or cross-join?) but as I've never done this before I'd appreciate any kind of help possible.
Current structure is:
Colour Size Quantity ----------------------- Red 10 100 Red 12 200 Red 14 300 Blue 10 400 Blue 12 500 Blue 14 600 Green 10 700 Green 12 800 Green 14 900 Green 16 1000
I want to produce this result set:
Colour Size10 Size12 Size14 Size16 ------------------------------------- Red 100 200 300 0 Blue 400 500 600 0 Green 700 800 900 1000
There could be any number of sizes or colours.
Is this possible? Can anyone give me any pointers?
I am trying to convert the rows in a table to columns. I have found similar threads on the forum addressing this issue on a high level suggesting the use of cursors, PIVOT Transform, and other means. However, I would appreciate if someone can provide a concrete example in T-Sql for the following subset of my problem.
Consider that we have Product Category, Product and its monthly sales information retrieved as follows:
I have purposefully included QtySold here as I need to display both Quantity and Sales as measured column groups in my report. Can this be achieved in sql? I would appreciate any responses.
Note that the Store Number is selected, but the Store Region is not, it's just the result of cross-filtering. Regional Sales incorrectly matches National Sales. If I then select the Region, the measures work:
I'm actually using VBA to change the Store Number slicer, as the end users don't want to select the region, then scroll through a list of store numbers. They just want to enter a store number and hit enter. I've tried a few things in DAX and VBA, and failed.
See sample data below. I'm trying to count the number of occurrences of strings stored in table @word without a while loop.
DECLARE @t TABLE (Id INT IDENTITY(1,1), String VARCHAR(MAX))
INSERT INTO @t SELECT 'There are a lot of Multidimensional Expressions (MDX) resources available' AS String UNION ALL SELECT 'but most teaching aids out there are geared towards professionals with cube development experience' UNION ALL
I'm trying to come up with a formula that will calculate the number of lines where two conditions are true.First, SLA must be either breached or achieved.And the second condition must be that the "country" and SLO group must be the same (these two values are located in different tables. So far I have only accomplished the first....
I have tried adding FIND, EXACT or USERELATIONSHIP to the formula to no avail.... I keep running into the same error."The value for 'SLO Group' cannot be determined. Either 'SLO Group' doesn't exist, or there is no current row for a column named 'SLO Group'."
I have a single column returned from a select statement. How can I have this returned as a vertical string? I looked into using PIVOT but my scenario seems too simple to use Pivot. I'm not requiring any aggregate functions or anything.
I have a column that I'm trying to call into a calculated measure to determine an expected contract amount (Terms in Month). The problem is that some of the terms are defined as text strings (MTM, Coterminous, One-time) while others are numbers (12, 36, etc). The entire column is recognized as text. I have a numeric value that management has agreed would be an acceptable substitution (MTM=1, Coterminous=6) and so on. I can't however, figure out how to convert those texts to a number since they are different data types. I've tried a nested IF statement, as well as a LOOKUPVALUE..I'm doing this in Power Pivot, so am limited to DAX formulas
Trying to modify the workbook connection string but it is greyed out and unable to change the Provider= from SQLNCL10 to SQLOLEDB. I am able to change the PowerPivot Data Connections connection string but not the workbook connection string. On the forum only see where people have asked the question but it seems like the people who've asked ended up recreating the data models.
One of my excel 2013 power pivot report was migrated from old server to new server after migration i changed the excel power pivot connection string to connect with new server but the workbook connections is still taking the old connection string of old server and there is no option of changing workbook connection string .
I am able to edit the powerpivot connection but workbook connections are not getting updated they are still taking old server connection string.
How do you create a drop down box on the report so the users can chose a value and conduct their search according to that value, See I have a SP that when the users enter a parameter they get the results according to that paramter, I would like for the choose one rather then type it up. Can anyone help please
I follow sql coding for cascading combo boxes that populates them if the first one populates the cdname the second one should populate the cd group and the third one the composers with the songs or the samthing with music hymnals. I am trying the steps they aren't populating. Where are simple books on this?
Hi, i have created a database in VB05, i have a form and a few combo boxes. I am a total newbie to this so i only know the total basics.
two tables i have are Ratings and films.
Ratings: RatingID Rating
Films: filmID Title ratingID
above are the columns of my tables.
what i am trying to do is select a rating on the first combo box which will then only show the titles with that rating in the next combo box.
I have the whole database created, i have the relationships in place and the combo boxes are all connected to the datasources etc. The comboboxes are currently filled with data by the default sql query which is created. But it is showing the whole data for each when i only want to show the film titles for what rating is selected.
I have a Ms Access interface (which is connected to a sql Server database server),I create a new proc for one Access combo box and I used it in Access interface. It works fine if I log in as 'sa' but not other user. Other user can't see the combo box list at all.I grant the security for the user to execute the new proc.
I have a textbox, combo box, and a button on a form. I would like to perform a different query depending on the combo box selection. I thought I could do something such as: if (cboSearch.Text == "Selection1") { scCmd = "SELECT * FROM tblTable WHERE txtSearch = @Selection1"; } else if (cboSearch.Text == "Selection2") { scCmd = "SELECT * FROM tblTable WHERE txtSearch = @Selection2"; } else { scCmd = "SELECT * FROM tblTable WHERE txtSearch = @Selection3"; } However, this obviously does not operate as I would need it to. What is the proper method for conditional SqlCommand statements like this?
Hi folk.. can some body help me with this problem..???
I have a grid view on a form which has got colums which are set as data combo boxes. and a third column whish is set to a text box. all the 3 controls on the datagrid view are bound with sql server table. they are asociated with two saparate tables within 1 database... now what i want is that the user of the application can select either combo box 1 of teh 2nd combo box. and automatically the syncronize and also the text column asociates with related data..
for example
Country City Pincode India vasco 403802
now while flling the grid vew.. the user can select either country or city.. automatically both syncronize with related data and so does the text box.
I have a combo box where users select the customer name and can eithergo to the customer's info or open a list of the customer's orders.The RowSource for the combo box was a simple pass-through query:SELECT DISTINCT [Customer ID], [Company Name], [contact name],City,Region FROM Customers ORDER BY Customers.[Company Name];This was working fine until a couple of weeks ago. Now wheneversomeone has the form open, this statement locks the entire Customerstable.I thought a pass-through query was read-only, so how does this do atable lock?I changed the code to an unbound rowsource that asks for input of thefirst few characters first, then uses this SQL statement as therowsource:SELECT [Customer ID], [Company Name], [contact name],City, Region Fromdbo_Customers WHERE [Company Name] like '" & txtInput & "*' ORDER BY[Company Name];This helps, but if someone types only one letter, it could still bepulling a few thousand records and cause a table lock.What is the best way to populate a large combo box? I have too muchdata for the ADODB recordset to use the .AddItem methodI was trying to figure out how to use an ADODB connection, so that Ican make it read-only to eliminate the locking, but I'm striking outon my own.Any ideas would be appreciated.Roy(Using Access 2003 MDB with SQL Server 2000 back end)
1) Production data with column headers: Key, Facility, Line, Time, Output 2) Costs data with column headers: Key, Site, Cost Center, Time, Cost
The tables have a common key named obviously as Key. The data looks like this:
Key Facility Line Time Output Alpha
I would like to have two pivot tables which I can filter with ONE slicer based on the column Key. The first pivot table shows row labels Facility, Line and column labels Time. Value field is Output. The second pivot table shows row labels Site, Cost Center, and column lables Time. Value field is Cost.How can I do this with Power Pivot? I tried by linking both tables above to a table with unique Keys in PowerPivot and then creating a PivotTable where I would have used the Key from the Keys table.
Can I force the following measure to be visible for all rows in a pivot table?
Sales Special Visibility:=IF( Â Â HASONEVALUE(dimSalesCompanies[SalesCompany]) Â Â ;IF( Â Â Â Â VALUES(dimSalesCompanies[SalesCompany]) = "Sales" Â Â Â Â ;CALCULATE([Sales];ALL(dimSalesCompanies[SalesCompany])) Â Â Â Â ;[Sales] Â Â ) Â Â ;BLANK() )
FYI, I also have other measures as well in the pivot table that I don't want to affect.
I have a simple pivot table (screenshot below) that has two variables on it: one for entry year and another for 6 month time intervals. I have very simple DAX functions that count rows to determine the population N (denominator), the number of records in the time intervals (numerator) and the simple percent of those two numbers.
The problem that I am having is that the function for the population N is not overriding the time interval on the pivot table when I use an ALL function to do so. I use ALL in other very simple pivot tables to do the same thing and it works fine.
The formula for all three are below, but the one that is the issue is the population N formula. Why ALL would not work, any other way to override the time period variable on the pivot table.
Population N (denominator): =CALCULATE(COUNTROWS(analyticJudConsist),ALL(analyticJudConsist[CurrentTimeInCare1])) Records in time interval (numerator): =COUNTROWS(analyticJudConsist) Percent: =[countrows]/[denominatorCare]
How can I apply "Min" formula under a "new measure" (calculated field) within a pivot table under Power pivot 2010?Can see that neither does it allow me to apply "min" formula directly "formula box" nor could find any other option.Intent formula: "=Min(1,sum(a:b))" this isn't allowed so all I can do is "=sum(a:b)".
I have simple pivot table (below screenshot with info redacted) that displays a population number ("N" below), this is the denominator, a cumulative numerator number (below "#") and a simple cumulative percent that just divides the numerator by the denominator. It cumulates from top to bottom. The numerator and percent are cumulative using the below functions. There are two problems with the numerator and percent:
1. When there is not a number for the numerator, there is no value displayed for both the numerator and the percent..There should be a zero displayed for both values. 2. When there has been a prior number for the numerator and percent (for a prior month interval) but there is no number for the numerator in the current month interval, the prior month number and percent are not displayed in the current month interval--see the 3rd yellow line, this should display "3" and "16.7%" from the second yellow line.Here is the formula for the numerator:
=CALCULATE(count(s1Perm1[entity_id]),FILTER(ALL(s1Perm1[ExitMonthCategory]),s1Perm1[ExitMonthCategory] <= MAX(s1Perm1[ExitMonthCategory]))) Here is the formula for the percent: =(CALCULATE(countrows(s1Perm1),FILTER(ALL(s1Perm1[ExitMonthCategory]),s1Perm1[ExitMonthCategory] <= MAX(s1Perm1[ExitMonthCategory]))))/(CALCULATE(COUNTROWS(s1Perm1),ALL(s1Perm1[Exit],s1Perm1[ExitMonthCategory])))
I have data in my Powerpivot window which was generated by a sql query. This data includes a field named 'Cost' and every row shows a value for 'Cost' greater than zero. The problem is that when I display this data in the pivot table all entries for Cost display as $0. At first I thought that maybe Cost was set to a bogus data type (such as 'text) but it is set to ''Decimal Number' so that's not the problem.Â
What is happening and how do I fix it so that my pivot table reflects the values for 'Cost'?