How to aggregate data in a sequence using T-SQL - sql-server

I have this table:
and would like to query it to achieve this result:
I'm completely lost how to even start such query. Was looking at UNPIVOT but not even sure how I would apply it here for that purpose.
Any help would be greatly appreciated.
Thanks.

This isn't aggregation. This uses the next/previous value in an ordered result set. You can use the Lead or Lag analytic functions for this.
You can use LEAD(Start) Over (ORDER BY Start) to get Stop, LEAD(Coordinates) Over (ORDER BY Start) to get the previous coordinate and concatenate it to the current one, eg :
SELECT
Start,
LEAD(Coordinates) Over (ORDER BY Start) As STOP,
CONCAT_WS(',',LEAD(Coordinates) Over (ORDER BY Start),Coordinates)
AS COORDINATES
From ThatTable
LEAD will return NULL if there's no value to display, unless a default is specified. This means the last STOP value will be NULL. The question doesn't specify what should be displayed in the last row.
PS
If you provided the actual CREATE TABLE statement and sample data, it would be possible to create a query that actually reproduces what you want. Images can't be copied and queried

Related

How to match a substring exactly in a string in SQL server?

I have a column workId in my table which has values like :
W1/2009/12345, G2/2018/2345
Now a user want to get this particular id G2/2018/2345. I am using like operator in my query as below:
select * from u_table as s where s.workId like '%2345%' .
It is giving me both above mentioned workids. I tried following query:
select * from u_table as s where s.workId like '%2345%' and s.workId not like '_2345'
This query also giving me same result.
If anyone please provide me with the correct query. Thanks!
Why not use the existing delimiters to match with your criteria?
select *
from u_table
where concat('/', workId, '/') like concat('%/', '2345', '/%');
Ideally of course your 3 separate values would be 3 separate columns; delimiting multiple values in a single column goes against first-normal form and prevents the optimizer from performing an efficient index seek, forcing a scan of all rows every time, hurting performance and concurrency.

Cannot extract year from createdDate in SOQL query

SELECT House__r.Name, House__r.House_Owner__r.person__r.Email__c, (SELECT Name, Total_Balance__c, Total_Expense__c FROM Expenses__r Where Type__c='Yearly' AND AND CALENDAR_YEAR(CreatedDate) = CALENDAR_YEAR(System.today() ) FROM Member__c
Error=> Unknown parsing error.
Kindly suggest what else can I do.
You have two 'AND' in a row. Also, if you are using query editor, you can't use System.today().
(on mobile, formatting will be poor, sorry)
SOQL supports only "field - operator - value_or_function” style for conditions. You try to make it "function - operator - another function", won't work.
For your particular scenario try with WHERE Created date = THIS_YEAR. It's a special literal, see https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm
More generic way would be to write what you need as a formula field, you could compare to YEAR(TODAY()). (that could be poor performance to filter by formula, often it results in full table scan, you would have to test, maybe add more filters using indexed columns...).
Or write it as WHERE CreatedDate >= :start AND CreatedDate <= :stop, put right bind variables for your range.

Merging two columns into one in sql

I have a table with two columns hora_entrada and hora_saida and when running this select statement:
select hora_entrada, hora_saida
from Controlo_de_Entrada_saidas
it shows this result:
What I want to do is to combine these two columns into one that if Hora_saida = "Não saiu", it shows the data in hora_entrada but if hora_saída has an actual hour in there, it shows the data in hora_saida instead.
So basically this should be my result:
I don't know if I'm making myself clear, I actually don't even know where to start or if its even possible but any help would be appreciated.
Try using a CASE expression:
SELECT
hora_entrada,
hora_saida,
CASE WHEN hora_saida = 'Não saiu'
THEN hora_entrada ELSE hora_saida END AS new_column
FROM yourTable;
This logic assumes that any value in the hora_saida column which is not Não saiu is a valid timestamp. If not, then we could add additional logic to check for this as well.
If you are open/able to changing your data model, you might want to consider just storing NULL values for the missing data. SQL Server (and most other databases as well) has a built-in function COALESCE, which can be used to replace NULL with a backup value. This would avoid needing to use a lengthy CASE expression as you see above.

TSQL - Geography: Which polygon?

Using SQL Server, when I get a result of 1 for the expression #multipolygon.STIntersects(#points), indicating that the point is within one of the polygons comprising the multi-polygon
is there a way of finding out which polygon inside the many within the multi-polygon actually contains the point?
I've used something like this before:
select *
from dbo.Numbers as n
where #point.STIntersects(#multipolygon.STGeometryN(n.Number)) = 1
and n.Number <= #multipolygon.STNumGeometries();
Where dbo.Numbers is a tally table. This query will return a 1-based index of which polygon(s) matched. If you want the polygons themselves as well, add STGeometry(n.Number) to the select list.
Try splitting the single multi-polygon row into many, single-polygon rows in a query and then doing the intersect, that will return only matching rows.
I haven't done anything like that myself, but this link might help https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d99cef8e-d345-44ee-87e1-f9d4df851c35/multipolygon-results-split-into-polygons?forum=sqlspatial

Using calculated member as parameter in MDX function

I'm new to MDX but want to keep my code as clean as possible.
I have a query that looks at todays sales and compares them against LY and LY-1 using the ParallelPeriod function. It looks something like this..
With Member [Date].[SalesCalendar].[DateToday] as [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]
SELECT
{[Date].[SalesCalendar].[DateToday],
ParallelPeriod([Date].[SalesCalendar].[Year],1,[Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]),
ParallelPeriod([Date].[SalesCalendar].[Year],2,[Date].[SalesCalendar].[DateToday]}
*
{[Measures].[Total Sales],[Measures].[Units],[Measures].[Sales Target]}
ON Columns,
[Locations].[Location PK].[Location PK]
on Rows
From MyCube
I start by defining a member that points to today's date. I want to define it once and use it throughout this query (and other queries I write), the theory being I can change it in once place and the underlying query reacts.
The problem I have is that if I try and use this calculated member within the ParallelPeriod function I get no results. With the query above I get results for the first column and the first call to ParallelPeriod (for LY) works but the second call for LY-1, which uses the declared member, fails.
I'm guessing this is down to my lack of knowledge with MDX and so I guess I am missing something fundamental. However, banging my head against the wall isn't working so I need some help!
Any ideas what I am doing wrong?
Thanks
This cannot work because when your query is evaluated [Date].[SalesCalendar].[DateToday] is not replaced with [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00].
You created a member that will give the same numeric values than [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00] in the pivot table cells.
You can try this query:
With Member [Date].[SalesCalendar].[DateToday] as [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]
Member [Measures].[name] as [Date].[SalesCalendar].CurrentMember.Name
SELECT
{[Measures].[name], [Measures].[Total Sales]} ON Columns,
{[Date].[SalesCalendar].[DateToday], [Date].[SalesCalendar].[Date].&[2012-10-26T00:00:00]} on Rows
From MyCube
The Total Sales will be the same but not [Measures].[name].

Resources