HierarchyId and Alphabetical order of new record - sql-server

I am playing with the HierarchyId columns in SQL Server in order to decide whether to use them in a new project.
I read some articles, watched some tutorials, I did some tests and the basic concepts are clear to me.
However, I have a problem inserting new records into the table.
Let's say I have such a structure:
- Metallica (/1/)
- Kill em all (/1/1/)
- Hit the lights (/1/1/1/)
- Whiplash (/1/1/3/)
- Iron Maiden (/2/)
- Killers (/2/1/)
- Megadeth (/3/)
Imagine I want to insert a new song (Motorbreath) under Kill'em all, but I want to sort the list in alphabetical order.
So, my final list should be like this:
- Metallica (/1/)
- Kill em all (/1/1/)
- Hit the lights (/1/1/1/)
- Motorbreath (/1/1/2/)
- Whiplash (/1/1/3/)
- Iron Maiden (/2/)
- Killers (/2/1/)
- Megadeth (/3/)
How can I achieve this?

Related

Find and combine results from two columns based on same search criteria

I am setting up a staff database and some of the staff have split roles across two teams in the same department. I am using the QUERY function on the Dashboard tab to bring up details for various teams, searching via manager or team. The problem I have is when trying to factor in the split roles into the searches.
For example, an employee who works part-time in one team and part-time in another will be listed under two managers and two teams in the main database. See image below:
What I want it to come up with is as follows when you search for either Manager or Team:
Staff Member - Hours - Role
Person 1 - - - - 37 - - A
Person 2 - - - - 37 - - A
Person 4 - - - - 10 - - B
So all the people who work for a certain manager, whether the role is 1 or role 2 would be shown.
I have tried the following to combine the two column results:
={query(StaffData2,"select B,AT where K = '"&Dashboard!O8 &"' and AT is not null",1);query(StaffData2,"select B,AU where AO = '"&Dashboard!O8&"' and AU is not null",0)}
It seems to half work when the employee in a team does have a split role but it adds them as another entry on to the bottom of the results eg:
Person 1
Person 2
Person 1
Alternatively, if there are no split roles then the result comes back with an ARRAY LATERAL error.
Any help would be great.
the proper way would be:
=QUERY({B3:E13; B3:B13, F3:H13},
"select Col1,Col2,Col4 where Col3 = '"&C16&"'", 1)

Trouble Excluding Nodes from Graph

Set-Up
I'm very new to graph databases and neo4j/cypher and I'm having a hard time understanding how to exclude various pieces from my results. Below is an image of my graph. Every node and every relationship has an activeFrom and activeTo property to allow me to view the graph as it existed at any given point in history.
MATCH (:Collective:Company)<-[tree *0..4]-(downline:Collective) RETURN downline
(Any relationship with a date indicates it's already, or scheduled (future date) to expire. No date or future date means it's active.).
Question
My ultimate goal here is to view this same graph, minus all expired nodes and relationships. Right now, I'm trying to build the query that will let me see that and am failing :(
What I'm not understanding is why:
Region5's relationship to Company1 is still active... why isn't company showing up? (shouldn't the 0-length path bring the company back like in the first image?)
Both Office5 and Office27 have expired relationships, so why are they still in the result?
Offices 1, 2, 6, 9, and 11 are active nodes, but have no active relationships, so why are they being returned? (my GUESS here is that my 2nd WHERE clause (branch filter) is filtering out the relationships, but not the nodes they associate, but I'm not sure how to do it differently)
.
MATCH (:Collective:Company)<-[tree *0..4]-(downline:Collective)
WHERE
// -- node(s) are active
downline.activeFrom <= '2015-08-31 23:59:59'
AND (downline.activeTo IS NULL OR downline.activeTo > '2015-08-31 23:59:59')
UNWIND tree AS branch
WITH branch, downline
WHERE
// -- branch is active
branch.activeFrom <= '2015-08-31 23:59:59'
AND (branch.activeTo IS NULL OR branch.activeTo > '2015-08-31 23:59:59')
RETURN downline
Bonus
I've set up a neo4j sandbox with this data for you guys to play with if needed. Please be mature with this, as I don't know how to make it read only. Please don't go deleting data and messing things up for other people. I'm also personally paying for this cloud instance, so please don't abuse the VM/resources :)
You can access it here: (sorry, removed for security purposes now that question has been answered).
Based on your questions, I'm trying to piece together what you require and I understand that you want to return paths that contain all active nodes and relationships. This is because you've asked about Office 27 and Office 5 which are both active nodes, but their single relationship to region 5 is inactive, so you do not want the paths between Office 27->Region 5 and Office 5->Region 5.
Office 2 however, is active, and it has an active relationship to region 4(also active). Region 4 has an inactive relationship to Company 1, so since you don't expect Office 2 in the results, I'm assuming it's because it has the inactive relationship in the entire path?
If this is the case, here's a query that hopefully does what you want-
MATCH p=(:Collective:Company)<-[tree*0..4]-(downline:Collective)
WHERE
ALL(x in relationships(p) WHERE x.activeFrom <= '2015-08-31 23:59:59'
AND (x.activeTo IS NULL OR x.activeTo > '2015-08-31 23:59:59'))
AND ALL(x in nodes(p) WHERE x.activeFrom <= '2015-08-31 23:59:59'
AND (x.activeTo IS NULL OR x.activeTo > '2015-08-31 23:59:59'))
RETURN p
This makes sure that every relationship and every node in a path is active. To bring back Office 2,1, change ALL to ANY and you'll see those back in the results because the path is now partially active.
BTW, you could also set up your graph at http://console.neo4j.org/?init=0 and share it

database for robot in labyrinth

I need help with constructing a database for my project - robot in a labyrinth.
I have 4 tables:
table concept (concepts like labyrinth, robot, field, sensor_ultrasound, sensor_colour, forward,rotate_right,rotate_left,wall,hole,finish,empty_space etc.)
table sensor_values (it contains all sensor values that robot detects in the labyrinth)
table labyrinth_rules (it contains all sensor values that robot detects in the labyrinth in a specific moment with attribute concept, eg: in moment 1, sensor_ultrasound has value 28, sensor_colour has value 3 -> it is a wall (id_concept)) and
table robot_state(it contains robots coordinates and heading, id:concept and decision...example: in a moment 1, robot is in position x=1, y=2, heading 90°, concept:wall, decision:rotate left or right). Here is the picture of my database now...
http://imgur.com/5bScGri
As you can see I have everything connected to my concept table because all my concepts are in there.
I need help with this: as you can see in table sensor_values I have hard coded the table because I have two sensors...but I have to make another table SENSOR that will have all sorts of sensors (so that user can in anytime insert new sensor) but I dont know how to adjust tables sensor_values and labyrinth_rules with it.
Thanks in advance!
It sounds like you want to be able to add an arbitrary number of sensors. I also see some duplication of data here. You might find this schema to be simpler.
* Concept
- id
- name
* SensorRules
- sensor_id
- concept_id
- sensor_value
* SensorValues
- id
- TimeStep
- Value
* RobotState
- TimeStep
- Position
- Concept
- Decision
You can query the database for which rules correspond to the set of sensor values you have.

SPSS :Loop through the values of variable

I have a dataset that has patient data according to the site they visited our mobile clinic. I have now written up a series of commands such as freqs and crosstabs to produce the analyses I need, however I would like this to be done for patients at each site, rather than the dataset as whole.
If I had only one site, a mere filter command with the variable that specifies a patient's site would suffice, but alas I have 19 sites, so I would like to find a way to loop through my code to produce these outputs for each site. That is to say for i in 1 to 19:
1. Take the i th site
2. Compute a filter for this i th site
3. Run the tables using this filtered data of patients at ith site
Here is my first attempt using DO REPEA. I also tried using LOOP earler.
However it does not work I keep getting an error even though these are closed loops.
Is there a way to do this in SPSS syntax? Bear in mind I do not know Python well enough to do this using that plugin.
*LOOP #ind= 1 TO 19 BY 1.
DO REPEAT #ind= 1 TO 20.
****8888888888888888888888888888888888888888888888888888888 Select the Site here.
COMPUTE filter_site=(RCDSITE=#ind).
USE ALL.
FILTER BY filter_site.
**********************Step 3: Apply the necessary code for tables
*********Participation in the wellness screening, we actually do not care about those who did FP as we are not reporting it.
COUNT BIO= CheckB (1).
* COUNT FPS=CheckF(1).
* COUNT BnF= CheckB CheckF(1).
VAL LABEL BIO
1 ' Has the Wellness screening'
0 'Does not have the wellness screening'.
*VAL LABEL FPS
1 'Has the First patient survey'.
* VAL LABEL BnF
1 'Has either Wellness or FPS'
2 'Has both surveys done'.
FREQ BIO.
*************************Use simple math to calcuate those who only did the Wellness/First Patient survey FUB= F+B -FnB.
*******************************************************Executive Summary.
***********Blood Pressure.
FREQ BP.
*******************BMI.
FREQ BMI.
******************Waist Circumference.
FREQ OBESITY.
******************Glucose.
FREQ GLUCOSE.
*******************Cholesterol.
FREQ TC.
************************ Heamoglobin.
FREQ HAEMOGLOBIN.
*********************HIV.
FREQ HIV.
******************************************************************************I Lifestyle and General Health.
MISSING VALUES Gender GroupDep B8 to B13 ('').
******************Graphs 3.1
Is this just Frequencies you are producing? Try the SPLIT procedure by the variable RCDSITE. Should be enough.
SPLIT FILES allows you to partition your data by up to eight variables. Then each procedure will automatically iterate over each group.
If you need to group the results at a higher level than the procedure, that is, to run a bunch of procedures for each group before moving on to the next one so that all the output for a group will be together, you can use the SPSSINC SPLIT DATASET and SPSSINC PROCESS files extension commands to do this.
These commands require the Python Essentials. That and the commands can be downloaded from the SPSS Community website (www.ibm.com/developerworks/spssdevcentral) if you have at least version 18.
HTH,
Jon Peck
A simple but perhaps not very elegant way is to select from the menu: Data/Select Cases/If condition, there you enter the filter for site 1 and press Paste, not OK.
This will give the used filter as syntax code.
So with some copy/paste/replace/repeat you can get the freqs and all other results based on the different sites.

How to keep track changing items in a stock portfolio?

I have a system where people can pick some stocks and it values their portfolios but I'm having trouble doing this in a efficient way on a daily basis because I'm creating entries for days that don't have any changes(think of it like I'm measuring the values and having version control so I can track changes to the way the portfolio is designed).
Here's a example(each day's portfolio with stock name and weight):
Day1:
ibm = 10%
microsoft = 50%
google = 40%
day5:
ibm = 20%
microsoft = 20%
google = 40%
cisco = 20%
I can measure the value of the portfolio on day1 and understand I need to measure it again on day5(when it changed) but how do I measure day2-4 without recreating day1's entry in the database?
My approach right now(which I don't like) is to create a temp entry in my database for when someone changes the portfolio and then at the end of the day when I calculate the values if there is a temp entry I use that otherwise I create a new entry(for day2-4) using the last days data. The issue is as data often doesn't change I'm creating entries that are basically duplicates. The catch is: my stock data is all daily. I also thought of taking the portfolio and if it hasn't been updated in 3 days to find the returns of the last 3 days for each stock but I wasn't sure if there was a better solution.
Any ideas? I think this is a straight forward problem but I just can't see a efficient way of doing it.
note: in finance terms, its called creating a NAV and most firms do it the inefficient way I'm doing it but its because the process was created like 50 years ago and hasn't changed. I think this problem is very similar to version control but I can't seem to make a solution.
In storage terms is makes most sense to just store:
UserId - StockId1 - 23% - 2012-06-25
UserId - StockId2 - 11% - 2012-06-26
UserId - StockId1 - 20% - 2012-06-30
So you see that stock 1 went down at 30th. Now if you want to know the StockId1 percentage at the 28th you just select:
SELECT *
FROM stocks
WHERE datecolumn<=DATE(2012-06-28)
ORDER BY datecolumn DESC LIMIT 0,1
If it gives nothing back you did not have it, otherwise you get the last position back.
BTW. if you need for example a graph of stock 1 you could left join against a table full of dates. Then you can fill in the gaps easily.
Found this post here for example:
UPDATE mytable
SET number = (#n := COALESCE(number, #n))
ORDER BY date;
SQL QUERY replace NULL value in a row with a value from the previous known value

Resources