How to avoid this empty row using QUERY() in Google Sheets? - if-statement

I've tried applying some criteria, but the row is still there.
This first empty row shouldn't be there.
Here is the formula, in case you'd like to help me correct it:
=if(I4<>"", { IFERROR(query(Datasets!X3:AU,"select AS, AT, AJ, AR where AS matches date '"&TEXT(DATEVALUE(I4),"yyyy-mm-dd")&"'",0),{"","","",""}); IFERROR(query(Datasets!BC3:BT,"select BC, BD, BS, BQ where BC matches date '"&TEXT(DATEVALUE(I4),"yyyy-mm-dd")&"'",0),{"","","",""}) }, UNIQUE({query(Datasets!X3:AU,"select AS, AT, ' ', SUM(AR) where AS is not null group by AS, AT, ' ' label ' '' ', SUM(AR) ' '",0); query(Datasets!BC3:BT,"select BC, BD, ' ', SUM(BQ) where BC is not null group by BC, BD, ' ' label ' '' ', SUM(BQ) ' '",0) }))

try:
=IF(I4<>"", {IFERROR(QUERY(Datasets!X3:AU,
"select AS,AT,AJ,AR
where AS matches date '"&TEXT(DATEVALUE(I4), "yyyy-mm-dd")&"'", ), {"","","",""});
IFERROR(QUERY(Datasets!BC3:BT,
"select BC,BD,BS,BQ
where BC matches date '"&TEXT(DATEVALUE(I4), "yyyy-mm-dd")&"'", ), {"","","",""})},
UNIQUE({QUERY(Datasets!X3:AU,
"select AS,AT,' ',SUM(AR)
where AS is not null
group by AS,AT,' '
label' ''',SUM(AR)''", );
QUERY(Datasets!BC3:BT,
"select BC,BD,' ',SUM(BQ)
where BC is not null
group by BC,BD,' '
label' ''',SUM(BQ)''", )}))

Related

Microsoft Access: Group By Function and list out variances [duplicate]

I have a table that contains run numbers. This is then linked to a second table that contains the serial numbers of the panels that go through each run. I was wondering is it possible to design a query that will give for each run number the serial numbers.
I would like it in a table like:
Run Number1, First Serial Number for 1, Second Serial Number for 1, etc..
Run Number2, First Serial Number for 2, Second Serial Number for 2, etc..
I can get in in the form:
Run Number1, First Serial Number for 1
Run Number1, Second Serial Number for 1
Run Number2, First Serial Number for 2
Run Number2, Second Serial Number for 2
Is there a way to set this up?
You can use my DJoin function as this will accept SQL as the source, thus you won't need additional saved queries:
' Returns the joined (concatenated) values from a field of records having the same key.
' The joined values are stored in a collection which speeds up browsing a query or form
' as all joined values will be retrieved once only from the table or query.
' Null values and zero-length strings are ignored.
'
' If no values are found, Null is returned.
'
' The default separator of the joined values is a space.
' Optionally, any other separator can be specified.
'
' Syntax is held close to that of the native domain functions, DLookup, DCount, etc.
'
' Typical usage in a select query using a table (or query) as source:
'
' Select
' KeyField,
' DJoin("[ValueField]", "[Table]", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' The source can also be an SQL Select string:
'
' Select
' KeyField,
' DJoin("[ValueField]", "Select ValueField From SomeTable Order By SomeField", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' To clear the collection (cache), call DJoin with no arguments:
'
' DJoin
'
' Requires:
' CollectValues
'
' 2019-06-24, Cactus Data ApS, Gustav Brock
'
Public Function DJoin( _
Optional ByVal Expression As String, _
Optional ByVal Domain As String, _
Optional ByVal Criteria As String, _
Optional ByVal Delimiter As String = " ") _
As Variant
' Expected error codes to accept.
Const CannotAddKey As Long = 457
Const CannotReadKey As Long = 5
' SQL.
Const SqlMask As String = "Select {0} From {1} {2}"
Const SqlLead As String = "Select "
Const SubMask As String = "({0}) As T"
Const FilterMask As String = "Where {0}"
Static Values As New Collection
Dim Records As DAO.Recordset
Dim Sql As String
Dim SqlSub As String
Dim Filter As String
Dim Result As Variant
On Error GoTo Err_DJoin
If Expression = "" Then
' Erase the collection of keys.
Set Values = Nothing
Result = Null
Else
' Get the values.
' This will fail if the current criteria hasn't been added
' leaving Result empty.
Result = Values.Item(Criteria)
'
If IsEmpty(Result) Then
' The current criteria hasn't been added to the collection.
' Build SQL to lookup values.
If InStr(1, LTrim(Domain), SqlLead, vbTextCompare) = 1 Then
' Domain is an SQL expression.
SqlSub = Replace(SubMask, "{0}", Domain)
Else
' Domain is a table or query name.
SqlSub = Domain
End If
If Trim(Criteria) <> "" Then
' Build Where clause.
Filter = Replace(FilterMask, "{0}", Criteria)
End If
' Build final SQL.
Sql = Replace(Replace(Replace(SqlMask, "{0}", Expression), "{1}", SqlSub), "{2}", Filter)
' Look up the values to join.
Set Records = CurrentDb.OpenRecordset(Sql, dbOpenSnapshot)
CollectValues Records, Delimiter, Result
' Add the key and its joined values to the collection.
Values.Add Result, Criteria
End If
End If
' Return the joined values (or Null if none was found).
DJoin = Result
Exit_DJoin:
Exit Function
Err_DJoin:
Select Case Err
Case CannotAddKey
' Key is present, thus cannot be added again.
Resume Next
Case CannotReadKey
' Key is not present, thus cannot be read.
Resume Next
Case Else
' Some other error. Ignore.
Resume Exit_DJoin
End Select
End Function
' To be called from DJoin.
'
' Joins the content of the first field of a recordset to one string
' with a space as delimiter or an optional delimiter, returned by
' reference in parameter Result.
'
' 2019-06-11, Cactus Data ApS, Gustav Brock
'
Private Sub CollectValues( _
ByRef Records As DAO.Recordset, _
ByVal Delimiter As String, _
ByRef Result As Variant)
Dim SubRecords As DAO.Recordset
Dim Value As Variant
If Records.RecordCount > 0 Then
While Not Records.EOF
Value = Records.Fields(0).Value
If Records.Fields(0).IsComplex Then
' Multi-value field (or attachment field).
Set SubRecords = Records.Fields(0).Value
CollectValues SubRecords, Delimiter, Result
ElseIf Nz(Value) = "" Then
' Ignore Null values and zero-length strings.
ElseIf IsEmpty(Result) Then
' First value found.
Result = Value
Else
' Join subsequent values.
Result = Result & Delimiter & Value
End If
Records.MoveNext
Wend
Else
' No records found with the current criteria.
Result = Null
End If
Records.Close
End Sub
Full documentation can be found in my article:
Join (concat) values from one field from a table or query
If you don't have an account, browse to the link: Read the full article.
Code is also on GitHub: VBA.DJoin

Oracle SQL - Replace space/alpanumeric/non-alphanumeric with space and replace with word?

Hi I want to replace following examples with the following:
(LTRIM) Replace any space at the beginning before first Alphanumerical character
(RTRIM) Replace any space at the end after last Alphanumerical character
Replace any non-alpha numerical with space
Replace any empty (not null) with word "UNKNOWN"
In case of only space replace all spaces with word "UNKNOWN"
' abc ' -> 'abc'
'abc ' -> 'abc'
' abc ' -> 'abc'
'!ab c ? ' -> 'ab c'
' a b c ' -> 'a b c'
'a!b?c $ ' -> 'a b c'
' ' -> 'UNKNOWN'
'' -> 'UNKNOWN'
null -> null
These are the queries I'm working on but I'm not getting anywhere:
select
'-|&#/,.‘“<>():;' as default1,
translate(SUBSTR(MAX ('-|&#/,.‘“<>():;'),1,70), '-|&#/,.‘“<>():;', ' ') as formatted1
from dual;
select trim(regexp_replace(regexp_replace(' a b cdefgh ' , '[[:space:]]*',''), '(.)', '\1 UNK' )) as formatted from dual;
SELECT LTRIM(RTRIM(' NEXT LEVEL EMPLOYEE ')) from dual;
Replace any empty (not null) with word "UNKNOWN"
This is impossible as, in Oracle, there are no empty strings as an empty string is stored as NULL.
Apart from that impossibility, you can use:
SELECT value,
CASE
WHEN value IS NULL
THEN NULL
ELSE COALESCE(
TRIM(
BOTH ' ' FROM
REGEXP_REPLACE(
value,
'[^A-Za-z0-9]',
' '
)
),
'UNKNOWN'
)
END AS updated_value
FROM table_name;
Which, for the sample data:
CREATE TABLE table_name (value) AS
SELECT ' abc ' FROM DUAL UNION ALL
SELECT 'abc ' FROM DUAL UNION ALL
SELECT ' abc ' FROM DUAL UNION ALL
SELECT '!ab c ? ' FROM DUAL UNION ALL
SELECT ' a b c ' FROM DUAL UNION ALL
SELECT 'a!b?c $ ' FROM DUAL UNION ALL
SELECT ' ' FROM DUAL UNION ALL
SELECT '' FROM DUAL UNION ALL
SELECT null FROM DUAL;
Outputs:
VALUE
UPDATED_VALUE
    abc
abc
abc
abc
  abc
abc
!ab c ?
ab c
 a b c
a b c
a!b?c $
a b c
         
UNKNOWN
null
null
null
null
fiddle

Error when requesting User.history.all ()

I have a model class User (AbstractUser), I would like to keep track of the User history, but I have an error while getting User.history.all (),
ERROR: table "core_user" is missing from the FROM clause
LINE 1: SELECT "core_user". "Id", "core_user". "Password", "core_user" ...
SELECT "core_user"."id", "core_user"."password", "core_user"."last_login", '
'"core_user"."is_superuser", "core_user"."username", '
'"core_user"."first_name", "core_user"."last_name", "core_user"."email", '
'"core_user"."is_staff", "core_user"."is_active", "core_user"."date_joined", '
'"core_user"."editor_config", "dib_page_historicaluser"."ip_address", '
'"dib_page_historicaluser"."history_id", '
'"dib_page_historicaluser"."history_date", '
'"dib_page_historicaluser"."history_change_reason", '
'"dib_page_historicaluser"."history_type", '
'"dib_page_historicaluser"."history_user_id" FROM "dib_page_historicaluser" '
'ORDER BY "dib_page_historicaluser"."history_date" DESC, '
'"dib_page_historicaluser"."history_id" DESC LIMIT 21')
core_user table is my base_model, and dib_page_historicaluser table is the history model.

Regular expression - Remove special characters except single white space

From stack overflow, I got the standard reg expression
to eliminate -
a) special characters
b) digits
c) more than 2 spaces to single space
to include -
d) - (hyphen)
e) ' (single quote)
SELECT ID, REGEXP_REPLACE(REGEXP_REPLACE(forenames, '[^A-Za-z-]', ' '),'\s{2,}',' ') , REGEXP_REPLACE(REGEXP_REPLACE(surname, '[^A-Za-z-]', ' '),'\s{2,}',' ') , forenames, surname from table1;
Instead of 2 functions how to get the result in single function?
to include '(single quote) \' is not working in regexp_replace.
Thanks.
Oracle Setup:
CREATE TABLE test_data ( id, value ) AS
SELECT 1, '123a45b£$- ''c45d#{e''' FROM DUAL
Query:
SELECT ID,
REGEXP_REPLACE(
value,
'[^a-zA-Z'' -]| +( )',
'\1'
)
FROM test_data
Output:
ID | REGEXP_REPLACE(VALUE,'[^A-ZA-Z''-]|+()','\1')
-: | :--------------------------------------------
1 | ab- 'cde'
db<>fiddle here

Issue with the update cluase

I am facing one issue in the update clause. I am trying to do the below:
update AM1 from DB.AM_7541 AM1,
(sel distinct TRIM(SB.LCDBDN) NEID, trim( leading '0' from sb.lcdmno) LCDMNO,
AM.Netw_equip
from
DB1.PLTL SB
inner join DB.AM_7541 AM
on trim( leading '0' from sb.lcdmno)=AM.accs_meth_num
where SB.LOAD_DATE in ( sel max(load_date),lcdmno,lcdbdn from DB1.PLTL where lcdmno not like ' ' and lcdmno is not null group by lcdmno, lcdbdn)
and SB.LCDBDN not like ''
) der
set Netw_equip=der.NEID
where AM1.accs_meth_num=der.lcdmno
I have to take the max(load_dt) grouped on lcdmno and lcdbdn.
I am getting error like too many expressions in the select clause.
Can you please help me on this.
Checked for dups:
sel NEID, LCDMNO, COUNT(*) from
(
sel distinct TRIM(SB.LCDBDN) NEID, trim( leading '0' from sb.lcdmno) LCDMNO,
AM.Netw_equip
from
DB1.PLTL SB
inner join DB.AM_7541 AM
on trim( leading '0' from sb.lcdmno)=AM.accs_meth_num
where SB.LOAD_DATE in ( sel max(load_date),lcdmno,lcdbdn from DB1.PLTL where lcdmno not like ' ' and lcdmno is not null group by lcdmno, lcdbdn)
and SB.LCDBDN not like '')
group by 1,2
having count(*)>1
--- 0 rows
Thanks,
Amit
The error is self-explaining, you return three columns in the Subquery but compare to a single row only.
Either rewrite using a Correlated Subquery or a multi-column Subquery:
update AM1 from DB.AM_7541 AM1,
( sel distinct TRIM(SB.LCDBDN) NEID,
trim( leading '0' from sb.lcdmno) LCDMNO,
AM.Netw_equip
from DB1.PLTL SB
inner join DB.AM_7541 AM
on trim( leading '0' from sb.lcdmno)=AM.accs_meth_num
where (SB.LOAD_DATE, sb.lcdmno, sb.lcdbdn) in
(
sel max(load_date),lcdmno,lcdbdn from DB1.PLTL
where lcdmno not like ' '
and lcdmno is not null
group by lcdmno, lcdbdn
)
and SB.LCDBDN not like ''
) der
set Netw_equip=der.NEID
where AM1.accs_meth_num=der.lcdmno
Btw, applying some formatting really simplifies reading/understanding a query.