How get rows with oldest date per year - excel

I have task in excel. I think I show you it on example. Let say we have table as:
ID date
1 2015-03-11
1 2015-05-13
2 2013-01-10
2 2010-05-11
1 2014-09-19
2 2013-04-01
I have to make some operations to get rows with oldest date per every year. So I should have:
ID date
1 2015-03-11
1 2014-09-19
2 2013-01-10
2 2010-05-11
I will grateful for any help. Thanks in advance!

This is but one option. I like using SQL for this type of work and since Excel can connect to itself as an ODBC data source, that's just what I did here...
Create a Named range in excel (I called mine SomeTable) I do this by selecting the range in question and clicking in the drop down field to the left of the formula space that usually lists the selected cell (B11 in image below)
I then select data, from external sources and select the option for Microsoft Query (ODBC). Select new data source give it a name (Excel File name) Select microsoft excel driver. click connect. browse to where the file is containing the named range (Some table) Select ok and then in the 4th option select the named range (SomeTable)... select a place to put the table on a worksheet.
Now click in the "table" data it creates and go to the data menu properties. and enter the following in the definition tab under command text
.
Select ID, Date
FROM SomeTable ST
INNER JOIN
(Select MIN(date) as mDate, year(date) as mYear
FROM someTable
Group by year(date)) A on
ST.Date = A.mDate
If all done correctly you should get results like this:
Column EF is the source table named "SomeTable"
A10 is where I chose to put the table
B20 is where the SQL used to get the max per year
was put.

Related

Excel Power Pivot aggrating data through a many to 1 then 1 to many relationsips

I have 2 large tables in power pivot and I am trying to reconcile stockpile build grades to crushed stockpile grades. Please see example. I can create pivot table that contains the crushed grades but I am unable to find the right way to bring the stockpile grades though for the reconciliation high lighted in green in the attached example.
Thanks for any help or direction on where to look
In Power Query, create your lookup tables.
1) unique crushers, ID
2) Dates, ID
Here is a function to create a dates table, if you need one. After you invoke the function to get the column of dates, add another column for the ID.
/*--------------------------------------------------------------------------------------------------------------------
PQ Create a Dates Table, returning a single column of dates.
Inputs:
Start Date | Enter the year as yyyy, month as mm, day as dd
End Date | Enter the year as yyyy, month as mm, day as dd
Increments | One row will be returned per increment.
Author: Jenn Ratten
Edits:
07/16/18 | Modified query copied from the internet.
10/01/19 | Converted to a function.
--------------------------------------------------------------------------------------------------------------------*/
let
fDatesTable = (StartYear as number, StartMonth as number, StartDay as number, EndYear as number, EndMonth as number, EndDay as number, IncrementDays as number, IncrementHours as number, IncrementMin as number, IncrementSec as number) as table =>
let
StartDate = #date(StartYear,StartMonth,StartDay),
EndDate = #date(EndYear,EndMonth,EndDay),
Increments = #duration(IncrementDays,IncrementHours,IncrementMin,IncrementSec),
DatesTable = Table.FromColumns({List.Dates(StartDate, Number.From(EndDate) - Number.From(StartDate), Increments)}, type table[Date]),
ChangeType = Table.TransformColumnTypes(DatesTable,{{"Date", type date}})
in
ChangeType
in
fDatesTable
Load all of the tables to the data model.
Go to Power Pivot, diagram view, and create your relationships.
Lookup Crusher to data tables 1 and 2
Lookup Date to data tables 1 and 2
Go to Data View on data tables 1 and 2, add 2 new columns for the lookup IDs. You can specify the column header and the formula at one time by clicking in first cell and using this syntax, then either press enter or click the check mark in the formula bar.
Dates Lookup ID:=RELATED(lookup_dates[ID])
Crusher Lookup ID:=RELATED(lookup_crusher[ID])
Optional, but a good practice....
Right-click the new fields you just created and select "hide from client tools". Also hide the date and crusher fields on both data tables, and the ID field on both lookup tables. When you are creating pivots to summarize data from more than one table, the text fields that you place on your pivot table should be the fields that are shared (aka the lookup tables). This helps to minimize pivots in which the grand totals don't match the sum that you actually see on the table. If you hide the fields, it reminds you of that. There are exceptions of course, but this is a good rule of thumb.
Now create measures to sum the tons and any other math calculations you'd like. With the measures, start simple and let the pivot do the slicing. Put the measures in the values section of the pivot table.
Sum of Source Tons:=sum(Table1[Tons])
Sum of Destination Tons:=sum(Table2[Tons])

Excel Sum by Month

Hi have the following scenario:
Items in Column A, Total Time in Column B, then I have 365 dates in columns.
I want to summarise the column dates by month.
I want, for example, for Item A, in March, total Times taken.
How to do it?
Thanks
So, somewhat overkill but was interested in how to do it with power query and was interested in building a custom function for the MonthNumber.
Powerquery is free add-in for pre 2016 and is inbuilt for 2016
STEPS:
1) Data tab (2016) or powerquery tab (2010 to 2016) => Select query from table and ensure your source data is selected and appears in pop-up
2) Select the first date column, hold shift down and select last date, then select unpivot columns
3) Make sure column Attribute (your pivoted dates) is formatted as a date column
4) Open the advanced query editor window
and paste the following between let and source
fnMonthNum = (input) => let
values = {
{"January", "1"},
{"February", "2"},
{"March", "3"},
{"April","4"},
{"May", "5"},
{"June", "6"},
{"July", "7"},
{"August", "8"},
{"September", "9"},
{"October", "10"},
{"November", "11"},
{"December", "12"},
{input, "Undefined"}
},
Result = List.First(List.Select(values, each _{0}=input)){1}
in
Result,
This is M code for creating a custom function that returns month numbers from month names.
5) Add column tab => Add custom column, rename it MonthName and insert the following text
=Date.ToText([Attribute],"MMMM")
6) Add another custom column, rename it MonthNum and use our new function here:
= fnMonthNum([MonthName])
7) Remove the now unnecessary Attribute column; select column => right click => remove
8) Transform tab => Group by and enter the following:
9) Make sure MonthNum column is numeric.
10) Close and load to => Only create connection,
Tick checkbox for Add to data model, and then Load
11) As per instructions here: CREATE A PIVOT TABLE USING EXCEL’S INTERNAL DATA MODEL
Choose Insert→PivotTable from the Ribbon. The Create PivotTable dialog box opens.
Select the Use an External Data Source option, as shown, and then click the Choose Connection button. You see the Existing Connections dialog box, as shown.
Select the query you just created for Table1 and a destination for the pivottable
12) Arrange the fields as required and sort ascending on the MonthNum rowfield
13) Insert slicer
Note: You could introduce a custom sort to avoid having to use the MonthNum column for sorting.

Convert SAP BI hierarchy to flat table

I have a table:
Old table
Level 1 is top level. CC is the smallest unit inside our company.
What I want to do is convert this table into a flat table with additional column like level 1 / level 2 / Level 3, which show parent department of each node,
e.g. 100111 |CC |3 |IS// |IS/ |IS.
New Table
Using Excel I can do it easily by using some conditional formula and copy the cell above if current cell is CC.
My process is like this: SAP Application (export)-> .xls file (without Level and Parent Columns) -> creating new column for level and parent node with power query -> make new column (level 1 - 6) like example in the new table.
For Column Level 1 i use this formula:
If(B2=1;A2;D1)
and i fill it down for the rest. In my data, the first row is always level 1.
For Level 2:
=IF(B2=2(//because is Level 2),A2,IF(B2<2,"",E1))
And i repeat the same formula for other Column.
Can someone suggest me a solution for this problem?
I think the Power Query equivalent of your first formula would be to Add a Column with this formula:
if [Level] = 1 then [Department] else null
I would follow that with a "Fill / Down" step (from the Transform ribbon).
The subsequent formulas would look similar, e.g. for Level 2
if [Level] = 2 then [Department] else null
Follow each with a "Fill / Down" step and you should be done.

Excel 2010: Merge and Concatenate Rows

I need help.
It seems all macros I stumble upon on this website require me to write out all the rows I'm concatenating and merging. I was wondering if I could do this with a while or if statement. In the meantime,
I need to merge a table of over 21000 names (more than half of which are duplicates) but each name duplicate either has data that the original is missing, or vice versa or sometimes has different data under each column and I need to merge them. There are also like 34 (up to AF) columns.
Thanks,
Eddie
P.S. Apparently I need at least 10 reputation to post images, so message me via my account name if you want a screenshot of what I'm looking for.
P.S.S.
So after consulting with someone who helped through a comment I wrote this java-based pseudocode. Could someone help me translate it to VBA while I start to learn VBA myself? Also could they verify that it theoretically works? I'd like to have this done by the end of the day, which is why I'm asking for translation help, but I'm planning to be able to do this on my own in the near future.
//Create primary keys for comparison, using the last cell as PK for easy line finishing
//Create concatenation comparison keys (conKey) to compare cells and merge
//import new sheet and create cell location to write to new sheet.
Create PK1 = (cell) AF1
Create PK2 = (cell) AF2
Create conKey1 = (cell) A1
Create conKey2 = (cell) A2
Create newSheet = [a new sheet]
Create writeLine = A1
//Initialize while loop. This list lasts until it reaches the last person's name
While(conKey2 <= maxClient) {
//Initialize the if statement. It finds out whether merge is necessary
If(PK1.equals(PK2)) {
//Initialize while loop. This lasts until PK1 no longer equals PK2
while(PK1.equals(PK2)) {
//Initialize if loop. It checks to see if the values are not equal. if so, it concatenates into conKey1
if(!conKey1.equals(conKey2)) {
conKey1 = concatenate(conKey1,", ",conKey2)
}
//Export cell to writeLine of newSheet. Shift everything to the right. verify writeLine equals conKey1
//Clear the doubled cell for safe keeping and to assist us in closing the while loop.
exportTo(newSheet.writeLine, conKey1)
conKey1.shiftsRight
writeLine.coordinates(equals(conKey1))
conKey2 = ""
conKey2.shiftsRight
}
//After this while loop is finished, delete the blank row.
//coordinates of PK1 and PK2 should remain the same at this point
deleteRow(PK2)
//If the merge was not necessary it will skip all of that above and shift each variable down a row.
} else {
PK1.nextRow
PK2.nextRow
conKey1.nextRow
conKey2.nextRow
writeLine.nextRow
}
If SQL is a solution and MAX value of all values is an accepted value... then using an ODBC, a defined table and a self reference may work..
Select Formulas then define name
Define the range of existing data
Select where you want the combined results to display (for example Sheet 2 (A1) instead of sheet 1)
Save the workbook
Select data then from other sources.
select data connection wizard
Select ODBC DSN
Select Excel Files
Find the file saved
Now select the new table (the one defined in step 1)
and complete the wizard.
Go to data menu
Properties
click connection properties button
select definition tab.
modify command text to fit needs
It takes data from sheet 1 such as this:
And provided the wizard is completed (steps 5-11) and then the SQL updated in step 16 you'll get something like
.
This is the command text I used. since it's SQL it can be altered to fit your needs max, concat, whatever
Select firstName, MiddleName, LastName, max(attrib1), max(attrib2), max(attrib3), max(attrib4)
From `yourPath&FileName.xlsx`.`YourDefinedName`
GROUP BY firstName, MiddleName, LastName

Moving date period filter in Excel 2010 pivot-table

Is it possible to set some kind of filter for a moving date period?
For example one of the DB views I'm trying to replicate in my pivot-table has this filter :
DATEDIFF(day, dateColumn, GETDATE()) <= 90
So basically I always want to display the last 90 days of whataver data there is in the cube table.
Is this possible?
The answer to this question is here :
http://blogs.socha.com/2010/05/sliding-date-ranges-with-excel-2010.html
Example for a moving period of 30 days :
Select a cell inside a pivot table bound to the cube so that the PivotTable tools are available
Click the Options tab on the ribbon under the PivotTable Tools section:
Click the Fields, Items & Sets drop-down in the Calculations section of this ribbon tab
Click Manage Sets… in the drop-down
Click New… and then Create Set using MDX…
Enter a name for this set in the Set name text box
Enter the MDX expression that defines the date range
Click OK
Filter(
[Date].[Date].[Date],
[Date].[Date].CurrentMember.Member_Value < Now()
AND [Date].[Date].CurrentMember.Member_Value >= DateAdd("d", -30, VBA![Date]())
)

Resources