count(timestamp) to return 0 DB2 - count

i have been trying to find an answer but the things i found and tried does not seem to work, or i am doing something wrong.
As an example we have 2 tables:
Table Messages:
Int: id
Date: create_timestamp
String: join_number
Table Map:
String: entity_name
String: join_number
I am trying to count create_timestamps and group them by Entity_name, so the query is:
select count(create_timestamp) as count , entity_name from Messages left join Map on Messages.join_number = Map.join_number group by entity_name
The query is working fine except of one problem it does not return entity with result 0 if no timestamps were found. I need it to return the entity_name and result 0 if it found nothing.
I tried query with COALESCE like this:
select COALESCE(count(create_timestamp), 0) as count , entity_name from Messages left join Map on Messages.join_number = Map.join_number group by entity_name
But it still does not return 0 values. Please keep in mind this is a DB2 Database, any comments, questions, or answers are really welcome here.

It turns out answer by Mark is correct. I did a mistake on query as i also included the condition "where timestamp > timestamp (xxxx)" which caused the query not to include those 0 results. In case someone can find it helpful, the correct query if you want to choose the timestamp is:
select count(timestamp) as count, entity_name from Map left join Messages on timestamp > timestamp('2020-01-01') and Messages.join_number = Map.join_number group by entity_name
Thanks a lot again!

Related

SQLite How to Include Records Where NULL in Objective C?

I’m attempting to count records that match specific criteria, including one field being null, but including the null clause results in no records being found.
If I output the contents of the field, it comes back as “(null)”. I’ve tried IS NULL and ISNULL, both of which appear that they should work when looking at other sources, but they both fail for me.
SELECT calls.contact_number, calls.contact_name, COUNT(notes.id) AS note_count
FROM calls LEFT JOIN notes on calls.id = notes.call_id
WHERE calls.contact_number = "123" AND notes.group_id ISNULL
GROUP BY calls.contact_number
This returns no records, whereas I’m expecting it to return one.
Move the condition in the ON clause:
SELECT calls.contact_number, calls.contact_name, COUNT(notes.id) AS note_count
FROM calls LEFT JOIN notes
ON calls.id = notes.call_id AND notes.group_id IS NULL
WHERE calls.contact_number = "123"
GROUP BY calls.contact_number, calls.contact_name
After grabbing a copy of the database, the notes.group_id field was determined to be an integer type, and the record in question actually contained a 0.
The successful query ended up being
SELECT calls.contact_number, calls.contact_name, COUNT(notes.id) as note_count
FROM calls LEFT JOIN notes
ON calls.id = notes.call_id
WHERE calls.contact_number = “123” AND (notes.group_id IS NULL OR notes.group_id = 0)
GROUP BY calls.contact_number
Not sure why the NSLog output of the returned value for group_id was ‘(null)’, some weird conversion?

Aggregation Queries

Is it possible to do the following query in SQLite.Swift without resorting to arbitrary SQL (which I do have working but would prefer to avoid)?
select table1.id, sum(table1.col1*table2.col2)
from table1, table2
where table1.id=table2.id
group by table1.id
I've attempted the following: the SQL (through asSQL()) appears to be correct, but I can't find a way to reference the aggregate column from the returned row.
let query = table1.select(id, (table1[column1]*table2[column2]).sum
.join(table2, on: table1[id] == table2[id])
.group(id)
Can you alias columns somehow?
OK, I've found the solution, and it only took me 2 days!
The way to alias a column in SQLite.swift is to use an expression.
The name of the expression becomes the column alias.
So instead of
let query = table1.select(id, (table1[column1]*table2[column2]).sum)
.join(table2, on: table1[id] == table2[id])
.group(id)
Use:
let aggrColumn = (table1[column1]*table2[column2]).sum
let query = table1.select(id, aggrColumn)
.join(table2, on: table1[id] == table2[id])
.group(id)
let results = try db.prepare(query)
for row in results {
myAggrColumn = try row.get(aggrColumn)
}
Using
select id, sum(table1.col1*table2.col2)
from table1, table2
were table1.id=table2.id
group by id
Will result (see below for corrections) in 2 columns, namely id and sum(table1,col*table2.col2)
However both uses of id would be ambiguous as coded as there are two such source columns.
As such the query should be changed (see following code whihc assumes you want the id from table1 (shouldn't matter if table2 were used due to the join))
Additionally were is not a keyword, it should be WHERE
An alias would likely make things easier you make an alias using the AS keyword. The folloiwng also includes AS mysumcolumn thus the resultant columns will be id and mysumcolumn
select table1.id, sum(table1.col1*table2.col2) AS mysumcolumn
from table1, table2
where table1.id=table2.id
group by table1.id
Running this with no data results in :-

MS Acess: max(Date/Time field) on query when field may contain 00:00:00

I am trying to build a Query in MS Access that returns the last date/time for a given entity ID. Research shows that using the MAX() function on the corresponding field and using GROUP BY on the remaining fields appears to be the way to go.
However, this doesn't seem to work in the presence of values that hold 0 hours, 0 minutes and 0 seconds, as it shows those values as well. The query's SQL is as follows:
SELECT Int(Historico_Classificacoes.ID_Entidade) AS ID_Entidade, Max(Historico_Classificacoes.Timestamp_Classificacao) AS [Data da última classificação], Historico_Classificacoes.US_Indicia_Pais_Constituicao, Historico_Classificacoes.US_Indicia_Responsabilidades_Fiscais, Historico_Classificacoes.US_Indicia_Morada_Coletiva, Historico_Classificacoes.US_Indicia_Telefone, Historico_Classificacoes.US_Indicia_Proveniencia_Capital, Historico_Classificacoes.US_Indicia_Beneficiários, Historico_Classificacoes.US_Indicia_Naturalidade, Historico_Classificacoes.US_Indicia_Nacionalidade, Historico_Classificacoes.US_Indicia_Morada_Singular, Historico_Classificacoes.US_Indicia_Laboral
FROM Historico_Classificacoes
GROUP BY Int(Historico_Classificacoes.ID_Entidade), Historico_Classificacoes.US_Indicia_Pais_Constituicao, Historico_Classificacoes.US_Indicia_Responsabilidades_Fiscais, Historico_Classificacoes.US_Indicia_Morada_Coletiva, Historico_Classificacoes.US_Indicia_Telefone, Historico_Classificacoes.US_Indicia_Proveniencia_Capital, Historico_Classificacoes.US_Indicia_Beneficiários, Historico_Classificacoes.US_Indicia_Naturalidade, Historico_Classificacoes.US_Indicia_Nacionalidade, Historico_Classificacoes.US_Indicia_Morada_Singular, Historico_Classificacoes.US_Indicia_Laboral
ORDER BY Int(Historico_Classificacoes.ID_Entidade);
The Historico_Classificacoes table currently holds the following data:
"ID_Entidade";"Timestamp_Classificacao";"Classificacao_DMIF";"Notacao_Risco_BCFT";"US_Indicia_Pais_Constituicao";"US_Indicia_Responsabilidades_Fiscais";"US_Indicia_Morada_Coletiva";"US_Indicia_Telefone";"US_Indicia_Proveniencia_Capital";"US_Indicia_Beneficiários";"US_Indicia_Naturalidade";"US_Indicia_Nacionalidade";"US_Indicia_Morada_Singular";"US_Indicia_Laboral"
"62";20/9/2015 00:00:00;1;30;1;1;1;1;1;1;1;1;1;0
"62";28/9/2015 10:43:38;1;30;1;1;1;1;1;1;1;1;1;1
"62";29/9/2015 17:52:24;1;30;1;1;1;1;1;1;1;1;1;1
"62";29/9/2015 17:52:40;1;30;1;1;1;1;1;1;1;1;1;1
"98";20/9/2015 00:00:00;2;15;1;1;1;1;1;1;0;0;0;0
"98";20/9/2015 00:00:01;0;0;0;0;0;0;0;0;0;0;0;0
The query, when executed in Datasheet View, outputs the following:
"ID_Entidade";"Data da última classificação";"US_Indicia_Pais_Constituicao";"US_Indicia_Responsabilidades_Fiscais";"US_Indicia_Morada_Coletiva";"US_Indicia_Telefone";"US_Indicia_Proveniencia_Capital";"US_Indicia_Beneficiários";"US_Indicia_Naturalidade";"US_Indicia_Nacionalidade";"US_Indicia_Morada_Singular";"US_Indicia_Laboral"
62;29/9/2015 17:52:40;1;1;1;1;1;1;1;1;1;1
62;20/9/2015 00:00:00;1;1;1;1;1;1;1;1;1;0
98;20/9/2015 00:00:00;1;1;1;1;1;1;0;0;0;0
98;20/9/2015 00:00:01;0;0;0;0;0;0;0;0;0;0
There are duplicated records for entities 62 and 98, when only one record for each was expected. Am I missing something here? Why are the entries whose values hold 00:00:00 present?
You may want to consider using an additional query as an intermediate step that identifies the MAX Date/Time combination for each group ID first, then a follow up query that pulls the entire record where that Group ID, Date and Time match, this will ensure you won't have to use First or Min on the rest of your fields, and you will always get the correct data
You use Group By for the last fields like US_Indicia_Morada_Singular and US_Indicia_Laboral. You'll have to use First, Last, Min, or Max on these as well.
Here is your attempt (without the repeated alias)
SELECT INT(ID_Entidade) AS ID_Entidade
, MAX(Timestamp_Classificacao) AS [Data da última classificação]
, US_Indicia_Pais_Constituicao
, US_Indicia_Responsabilidades_Fiscais
, US_Indicia_Morada_Coletiva
, US_Indicia_Telefone
, US_Indicia_Proveniencia_Capital
, US_Indicia_Beneficiários
, US_Indicia_Naturalidade
, US_Indicia_Nacionalidade
, US_Indicia_Morada_Singular
, US_Indicia_Laboral
FROM Historico_Classificacoes
GROUP BY INT(ID_Entidade)
, US_Indicia_Pais_Constituicao
, US_Indicia_Responsabilidades_Fiscais
, US_Indicia_Morada_Coletiva
, US_Indicia_Telefone
, US_Indicia_Proveniencia_Capital
, US_Indicia_Beneficiários
, US_Indicia_Naturalidade
, US_Indicia_Nacionalidade
, US_Indicia_Morada_Singular
, US_Indicia_Laboral
ORDER BY INT(ID_Entidade);
From you comments, here is SQL that is close to what you need. I have added the field "AnotherField" for you as you may or may not need to add field here.
This currently selects the whole record from the table, but only the single "most recent" record for each value found in the AnotherField is listed.
It may be that you need more that one field where AnotherField appears in the SQL. Think of the field you use instead of AnotherField as being the fields that need to be used to find the maximum date record.
SELECT Main.*
FROM Historico_Classificacoes AS Main
INNER JOIN ( SELECT AnotherField
, MAX(Timestamp_Classificacao) AS [MaxDate]
FROM Historico_Classificacoes
GROUP BY AnotherField
)
AS MostRecent
ON ( Main.AnotherField = MostRecent.AnotherField
AND
Main.Timestamp_Classificacao = MostRecent.MaxDate
)

Distinct Count expression ssas

I want to create a new calculated member in OLAP Cube to count the number of distinct clients, I'm trying to write this expression, but i don't know how to make it in MDX:
Distinct count ([DIM.Clients].[CuNumber], where Sum([Measures].[QQT - FACT Ventes] >=1)
Any help please !
Thanks!
Hi thank you for replies,
I spent couple of days trying to make the query work, but without big progress.
First, I ran an SQL query on my datawarehouse to know what result should I get on my OLAP Cube,
this is my SQL query:
use [Warehouse]
select count(*) as count_row
From
(Select F.FaCunumberX
from [dbo].[Dim_FaClients] F
inner join [dbo].[FACT_Ventes] V on F.[SK_FAClients] = V.SK_FaClients
inner join [dbo].[Dim_Date] D on D.SK_Date = V.SK_Date
where
D.Year = '2014'
Group by F.FaCunumberX
having SUM(V.QQT) >= 1) test
the result I got is : 26026
On my OLAP Cube I tried several queries, but I didn't get the same result
this is some of the expressions that I tried :
WITH SET MySet AS
(Filter({[DIM FA Clients].[FaCuNumberX].[FaCuNumberX]}*{([Dim Date].[Year].&[2014],[Measures].[QQT - Fact Ventes])},[Measures].[QQT - Fact Ventes]>1 or [Measures].[QQT - Fact Ventes]=1)
MEMBER MEASURES.SETDISTINCTCOUNT AS
DISTINCTCOUNT(MySet)
SELECT {MEASURES.SETDISTINCTCOUNT} ON 0
FROM [CubeAll]
the result I got with this one is : 31575
I tried also this expression :
DistinctCount(Filter([DIM.Clients].[CuNumber].[CuNumber].Members,
[Measures].[QQT - FACT Ventes] >= 1
)
)
the same result : 31575
sincerely, I don't see what I'm missing on my expressions.
Thank's for your help !
This would be something like
DistinctCount(Filter([DIM.Clients].[CuNumber].[CuNumber].Members,
[Measures].[QQT - FACT Ventes] >= 1
)
)
See the documentation of Filter and DistinctCount for details.

Ora-00904 - Error with creating a View

I'm stuck with creating a view in Oracle, but before I create the view, I always test it first and I always got this error: Ora-00904.
This is the situation. I have this one Set of Query let say Query A that I need to combined using UNION ALL with the Query A itself with only few modifications applied to create another bigger Set of Query - Query B. The main constraint that keeps me on doing this is the Database Design, and I'm not in the position in the company to change it, so I have to adapt to it. Query A unions Query A for 6 times creating Query B. The additional Major constraint is Query B is from 1 database user only, but there are 54 database users with the same structures that I need to fetch the same query. Query B (db user1) unions Query B (db user2) unions Query B (db user3) and so on until 54 then finally creating Query C --- the final output. My scrip has already reached 6048 lines, then I got this problem that I don't get when I test Query A and Query B. All my table names, owner names, and column names are all correct but I got that error.
This is the code (that needs to be repeated for 54x6 times) - the Query A. Query B applies some similar modification only.:
Select
'2013' "YEAR",
Upper(a.text_month) "MONTH",
Upper('Budget') "VERSION",
case
when length(b.level1_name) > 5 then 'Parent'
else 'SUBSIDIARIES'
end "COMPANY_GROUP",
case
when length(b.level1_name) < 6 and b.level1_name <> '1000' then 'Subsidiaries'
else '1000 Parent'
end "COMPANY",
case
when length(b.level1_name) < 6 and b.level1_name <> '1000' then 'SUBS'
else '1000'
end "COMPANY_CODE",
case
when length(b.level1_name) > 5 then 'Parent'
else 'SUBSIDIARIES'
end "COMPANY_NAME",
b.level1_displayname "DIVISION",
b.level1_name "DIVISION_CODE",
case
when length(b.level1_name) > 5 then ltrim(upper(substr(b.level1_displayname, 8)))
else upper(ltrim(substr(b.level1_displayname, 10)))
end "DIVISION_NAME",
upper(a.text_nature_of_trip) "NATURE_OF_TRAVEL",
upper(a.text_placeeventstraining) "TRAVEL_DETAILS",
upper(a.text_country) "COUNTRY",
a.text_name_of_employee "EMPLOYEE_NAME", a.float_no_of_attendees "NO_OF_ATTENDEES",
a.text_sponsored "SPONSORED",
a.text_remarks "REMARKS",
'OTHER TRAVEL EXPENSES' "COST_ELEMENT",
a.FLOAT_702120005_OTHER_TRAVEL_E "AMOUNT"
From PUBLISH_PNL_AAAA_2013.et_travel_transaction a,
PUBLISH_PNL_AAAA_2013.cy_2elist b
Where a.elist = b.level3_iid
ORA-00904 is "invalid column name" -- either you've spelled the column name wrongly, or prefixed it with the wrong table alias, omitted quotes from a string literal, or any number of other issues.
Check the point in the code that the error message mentions for mistakes like that.

Resources