I have GPS coordinates in my column (latitude and longitude separated by ,) and I am trying to get them into two separate columns.
I am using the below formula but it is not working.
= PATHITEM ( SUBSTITUTE ( Fault[lastgps], “,”, “|” ), 1 )
1 represents position.
Your quotes look weird to me. Does this work?
= PATHITEM ( SUBSTITUTE ( Fault[lastgps], ",", "|" ), 1 )
Try this to handle different lat long sizes and separators:
EVALUATE
VAR V_Str = "-23.1232630, -46.68211551"
VAR V_Sep = ", "
VAR V_Pos = FIND(V_Sep,V_Str)
RETURN
ROW(
"Lat",LEFT(V_Str,V_Pos-1),
"Long",RIGHT(V_Str,LEN(V_Str)-LEN(V_Sep)-V_Pos+1)
)
Related
I have about 20 columns in one row and not all columns are required to be filled in when row created also i dont want to cardcode name of every column in SQL query and on http.post request on frontend. All values are from form. My code:
var colNames, values []string
for k, v := range formData {
colNames = append(colNames, k)
values = append(values, v)
}
Now i have 2 arrays: one with column names and second with values to be inserted. I want to do something like this:
db.Query("insert into views (?,?,?,?,?,?) values (?,?,?,?,?,?)", colNames..., values...)
or like this:
db.Query("insert into views " + colNames + " values" + values)
Any suggestions?
Thanks!
I assume your code examples are just pseudo code but I'll state the obvious just in case.
db.Query("insert into views (?,?,?,?,?,?) values (?,?,?,?,?,?)", colNames..., values...)
This is invalid Go since you can only "unpack" the last argument to a function, and also invalid MySQL since you cannot use placeholders (?) for column names.
db.Query("insert into views " + colNames + " values" + values)
This is also invalid Go since you cannot concatenate strings with slices.
You could fromat the slices into strings that look like this:
colNamesString := "(col1, col2, col3)"
valuesString := "(val1, val2, val3)"
and now your second code example becomes valid Go and would compile but don't do this. If you do this your app becomes vulnerable to SQL injection and that's something you definitely don't want.
Instead do something like this:
// this can be a package level global and you'll need
// one for each table. Keep in mind that Go maps that
// are only read from are safe for concurrent use.
var validColNames = map[string]bool{
"col1": true,
"col2": true,
"col3": true,
// ...
}
// ...
var colNames, values []string
var phs string // placeholders for values
for k, v := range formData {
// check that column is valid
if !validColNames[k] {
return ErrBadColName
}
colNames = append(colNames, k)
values = append(values, v)
phs += "?,"
}
if len(phs) > 0 {
phs = phs[:len(phs)-1] // drop the last comma
}
phs = "(" + phs + ")"
colNamesString := "(" + strings.Join(colNames, ",") + ")"
query := "insert into views " + colNamesString + phs
db.Query(query, values...)
I have the following dataframe which contains the AxiomaID.
x<-c(0123, 234, 2348, 345, 3454)
And trying to run the following SQL Query within R.
SQL6<-data.frame(sqlQuery(myConn, "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID = x"))
How can I paste all the x values which contain the AxiomaID's into the SQL Query?
Try the following query:
SQL6<-data.frame(sqlQuery(myConn, paste("SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN (", paste(x, collapse = ", "), ")")))
Hope it helps!
You would try a function like
InsertListInQuery <- function(querySentence, InList) {
InValues <- ""
for (i in 1:length(InList)){
if (i < length(InList)) {
InValues <- paste(InValues,InList[[i]],",")}
else {
InValues <- paste(InValues,InList[[i]],sep = "")
}
}
LocOpenParenthesis <- gregexpr('[(]', querySentence)[[1]][[1]]
LocCloseParenthesis <- gregexpr('[)]', querySentence)[[1]][[1]]
if (LocCloseParenthesis-LocOpenParenthesis==1) {
querySentence<- gsub("[(]", paste("(",InValues,sep = ""), querySentence)
}
return (querySentence )
}
Function InsertListInQuery requires you to change your original query to one that use constraint IN () in WHERE clausule. What function does is to conform a string with vector elements separated by comma, and replace "(" string with the one composed. Finally, return a character variable.
Hence, you can define your vector of constraints list of elements, your query and call the function as shown:
x<-c(0123, 234, 2348, 345, 3454)
query <- "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN ()"
finalQuery <- InsertListInQuery(query, x)
Value of finalQuery is:
finalQuery
[1] "SELECT top 10 [AxiomaDate] \n ,[RiskModelID]\n,[AxiomaID]\n,[Factor1]\nFROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]\nWhere AxiomaID IN ( 123 , 234 , 2348 , 345 ,3454)"
Note the line return with special character \n.
I hope it may help.
alright... not sure if these could be done.
i'm in google spreadsheets with cell A1 = time.. the range is A1:C4.
i have a simple table as follows:
time sit stand
1 bob mike
2 fred pat
3 chris mike
This my query:
=query($A$1:$C$4,"select A,B,C where C='mike'",0)
... pretty straight forward. however, I want the column reference to be dynamic. So i need to be able to query using the header. how do i do it? I've already tried the following:
=query($A$1:$C$4,"select 'sit ', 'stand' where 'stand' = 'mike' ",0)
=query($A$1:$C$4,"select sit, stand where stand = 'mike' ",0)
and per this page's suggestion:
Google spreadsheet Query Error - column doesn't exist
I've also tried the following:
=query($A$1:$C$4,"select Col2, Col3 where Col3 = 'mike' ",0)
=query($A$1:$C$4,"select Col2, Col3 where (Col3) = 'mike' ",0)
=query($A$1:$C$4,"select (Col2), (Col3) where (Col3) = 'mike' ",0)
=query($A$1:$C$4,"select 'Col2', 'Col3' where 'Col3' = 'mike' ",0)
None of them work... does anybody know how to do it or know if it is possible?
https://developers.google.com/chart/interactive/docs/querylanguage
the examples here seems like you can do it, but is that for app script only? and not in the spreadsheet function?
Unfortunately there is no native way of referencing columns by their headers in the QUERY spreadsheet function select clause.
You can use the Colx notation if the first argument of the QUERY is anything other than an explicitly referenced range. One way to achieve this is wrap the range in parentheses, and invoking ArrayFormula:
=ArrayFormula(QUERY(($A$1:$C$4),"select Col2, Col3 where Col3 = 'mike'",0))
And it is rather ugly, but you can use the MATCH function to bolt in header references:
=ArrayFormula(QUERY(($A$1:$C$4),"select Col"&MATCH("sit";$A$1:$C$1;0)&", Col"&MATCH("stand";$A$1:$C$1;0)&" where Col"&MATCH("stand";$A$1:$C$1;0)&" = 'mike'",1))
I have also came across this problem without a solution, so I've have written a script which will allow column references within a query.
To use:
1. Create a separate sheet and set "[SHEET NAME]" to the name of the data sheet
2. Create a Name Range (from tools menu) which is the row which the columns ids are stored eg A1:K1
3. change[COLUMNIDs ROW REFERENCE] in the code to the named range.
Now while querying simple prefix a $ character before the column id example:
=QUERY([SHEET_NAME]!A4:F, _Select(" * WHERE $[COLUMNID] < $[COLUMNID2]")
function _Select(squery){
var sheetName = "[SHEET NAME]";
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var colIndex = sheet.getDataRange().getColumn();
var colIndex2 = sheet.getDataRange().getLastColumn();
var rangeString = sheetName+"!"+sheet.getRange(3, colIndex, 1, colIndex2).getA1Notation();
return "SELECT "+yq(rangeString, squery);
}
function yq(range, sQuery) {
var sheetName = SpreadsheetApp.getActiveSheet().getSheetName();
if( (typeof range == "object") && (range !== null) ){
sheetName = range.getSheet().getName();
range = range.getA1Notation();
}else{
var tRange = range.split("!");
if(tRange.length > 1){
sheetName = tRange[0]
range = tRange[1];
}
}
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(range);
var qInput = sQuery.split(" ");
var outQuery = [];
for(var i = 0; i < qInput.length; i++){
if(qInput[i].charAt(0) == "$"){
var colIndex = getHeaderValues(sheet, qInput[i].slice(1), range, "[COLUMNIDs ROW REFERENCE]");
outQuery.push(colIndex.toString());
}else{
outQuery.push(qInput[i]);
}
}
return outQuery.join(" ");
}
function getHeaderValues(sheet, columnName, range, columnHeaderRow){
var columnHeaderRowIndex = range.getRowIndex() - 1;
if(!isNaN(parseFloat(columnHeaderRow)) && isFinite(columnHeaderRow)){
columnHeaderRowIndex = range.getRowIndex() + columnHeaderRow;
}else if(typeof columnHeaderRow == "string"){
columnHeaderRowIndex = SpreadsheetApp.getActive().getRangeByName(columnHeaderRow).getRowIndex();
}
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeaderRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
var hIndex = null;
for(var i = 0; i < headers.length; i++){
if(headers[i] == columnName){
hIndex = headersRange.getColumn() + i;
hIndex = sheet.getRange(headersRange.getRow(), hIndex).getA1Notation();
return hIndex.charAt(0);
}
}
return null;
}
Hi I have another solution. I broke Lines that the hole thing can be read.
=query($A$1:$C$4,"select "
&CHAR(MATCH("time";1:1;0)+64)
&","
&CHAR(MATCH("sit";1:1;0)+64)
&","
&CHAR(MATCH("stand";1:1;0)+64)
&"where C='mike'",0)
Still not nice, and you are limmited to 24 Columns. Since after that you need to split. Dont like it at all :(
There are two things I've found you can do to improve Query column references:
Place column references searches in another cell (legend) and use
=query(A:C,"select "&D2&" where "&E2&" starts with '"&E3&"' ")
where for example D2 = A, E2 = C, E3 = foo
This has the benefit of allowing you to change the Query terms by editing cells rather than formulas and also doesn't break when you add/move columns around. You can take it further and name the ranges to make it look like
=query(A:C,"select "&cats&" where "&name&" starts with '"&search&"' ")
Switch it to Col[n] reference mode by messing with the range
=query({A:C},"select Col1 where Col3 matches 'foo' ")
This gives you the ability to move the dataset around without breaking it, but will break down if you insert more columns into the range.
I have found a workaround that is useful, you can name columns as named ranges and then you query those specific columns, some caveats is that you can't do that with large databases
=QUERY({employee,score},"select Col1,avg(Col2) group by Col1")
Given the following table:
Length | Width | Color | ID
===========================
18 | 18 | blue | 1
---------------------------
12 | 12 | red | 1
---------------------------
I want to produce a single column/row:
SIZES
=================
18 x 18, 12 x 12,
I can do this in SQL as follows:
DECLARE #SIZES VARCHAR(8000)
SELECT #SIZES = COALESCE(#SIZES, '') + Convert(varchar(80), [Length]) + ' x ' +
Convert(varchar(80), [Width]) + ', '
FROM table
where ID = 1
GROUP BY [Length], [Width]
ORDER BY [Length], [Width]
SELECT SIZES = #SIZES
But I cannot figure out how to do this in LINQ.
The closest I got was:
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
}
Which produces one column and two rows:
SIZES
========
18 x 18,
12 X 12,
The converts are unimportant to the problem. The columns are defined as floats though all are integers. The key is the COALESCE function I cannot figure out how to do that in LINQ.
Try ?? (null coalesce operator) like:
t.Length ?? 0
I don't think LINQ to SQL supports this T-SQL trick. The COALESCE isn't really the issue (as Mehrdad points out the equivalent in C# is ??) -- it's the fact that SQL Server aggregates each result via string concatenation into the variable #SIZES. AFAIK LINQ to SQL can't construct this type of query.
This will yield your desired result, but the string concatenation is performed on your side, not on the SQL server side. That probably doesn't matter.
var query =
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
};
var result = string.Join(string.Empty, query.Select(r => r.SIZES).ToArray());
I would just return the int sizes from SQL and do the string building client-side:
var query =
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select g.Key;
var sizeStrings = from s in query.AsEnumerable()
select string.Format("{0} x {1}", s.Length, s.Width);
var result = string.Join(", ", sizeStrings.ToArray());
You could use the .Aggregate function, like so:
(from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
}).Aggregate((x,y) => x + y)
This should kick out a single string, like you want.
Aggregate just internally maintains the exact same variable you had defined in the SQL, just implicitly.
I want to remove a particular character while retrieving a varchar from a table. The query looks like this:
SELECT ServiceName,
case isNumeric(Ramusage)
when 1 then
cast ( ltrim ( rtrim ( ramusage )) as int )
else
0
end as test,
priority
FROM ProcessInfo
Here the problem is ramusage is a varchar and it stores values like 12,500K, 4,321K.
Here I want to remove the "K" from the entry and display the number alone.
You want to use the REPLACE function:
REPLACE(ramusage, 'k', '')
Reference:
SQL Server
Oracle
MySQL
Use REPLACE
DECLARE #ProcessInfo TABLE(
ServiceName VARCHAR(MAX),
Ramusage VARCHAR(MAX),
priority INT
)
INSERT INTO #ProcessInfo (ServiceName,Ramusage,priority)
SELECT 'TEST','12,123K',1
SELECT ServiceName,
case isNumeric(REPLACE(REPLACE(Ramusage,'K',''),',',''))
when 1 then
cast ( ltrim ( rtrim ( REPLACE(REPLACE(Ramusage,'K',''),',',''))) as int )
else
0
end as test,
priority
FROM #ProcessInfo
what we have done is to create a CLR function to take a string amd remove all non numeric items
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString RemoveNonNumeric(SqlString strValue)
{
string strNew = strValue.ToString();
char[] chrArray = strNew.ToCharArray();
strNew = null;
for (int iChar = 0; iChar < chrArray.Length; iChar++)
{
if (Char.IsNumber(chrArray[iChar]))
strNew += chrArray[iChar];
}
// Put your code here
return new SqlString(strNew);
}
substr( ltrim( rtrim( ramusage ) ), length( ramusage ) - 1)
edit: replace, as mentioned in the other answers, is probably better.