How to create a Dynamic measure that only calculate filtered rows - dynamic

I want to create a measure that return distinctcount(ordernumbers) where every row is "Sant" Divided by the distinctcount(ordernumbers).
The measure should adapt the calculation by chosen filter.
This is my temporary solution which doesn't adapt when I am applying filters.
Availability =
VAR __CountSIRowsPerOrder =
COUNTROWS(
FILTER(
ALL(Sheet1);
[Ordernumber] = EARLIER([Ordernumber]) &&
[Available] = True))
VAR __CountRowsPerOrder =
COUNTROWS(
FILTER(
ALL(Sheet1);
[Ordernumber] = EARLIER([Ordernumber])))
RETURN
IF(__CountRowsPerOrder = __CountSIRowsPerOrder; True; False)
FilterAvailability (measure) =
CALCULATE(
DISTINCTCOUNT(Sheet1[Ordernumber]);
FILTER(Sheet1;[Availability] = True))
/
DISTINCTCOUNT(Blad2[Ordernumber])

Related

How to compare two values in different columns and different rows, related to an ID

I'm starting to learn Power BI and metrics with DAX and some help will be apreciated, please. I would need to know how, in a sorted table (by ID, Modification and Date), of data already defined by fields ([ID, Modification, Fecha(=Date), V_INICIAL, V_FINAL, RESULT]), I can compare values ​​of different rows and columns, regardless of the number of iterations. My objective is to calculate a measure that returns the Number of different IDs per type of Modification, which meet the "OK" Result. This result compares, for each value of the Modification field, the value of the V_INITIAL of the first iteration, with the value of the V_FINAL of the last iteration, of the Modification. And if both values ​​are different, the Result is "OK", since the modification has been made. Otherwise it is "NOT_OK" because there is no modification. Thank you very much for help! ;)Table
This calculated column works with your example data (where [Mod] is the [Modificación]-column):
N.B. This is by no means an optimised code. I tried to keep it as simple and easy to understand as possible.
Resultado =
var current_ID = [ID]
var current_mod = [Mod]
var maxDate =
CALCULATE(
MAX('DataTable'[Fecha]);
FILTER(
ALL('DataTable');
'DataTable'[ID] = current_ID && 'DataTable'[Mod] = current_mod
)
)
var minDate =
CALCULATE(
MIN('DataTable'[Fecha]);
FILTER(
ALL('DataTable');
'DataTable'[ID] = current_ID && 'DataTable'[Mod] = current_mod
)
)
var initialState =
CALCULATE(
MAX('DataTable'[v_inicial]);
FILTER(
ALL('DataTable');
'DataTable'[Fecha] = minDate && 'DataTable'[ID] = current_ID && 'DataTable'[Mod] = current_mod
)
)
var finalState =
CALCULATE(
MAX('DataTable'[v_final]);
FILTER(
ALL('DataTable');
'DataTable'[Fecha] = maxDate && 'DataTable'[ID] = current_ID && 'DataTable'[Mod] = current_mod
)
)
return
SWITCH(
TRUE();
[Fecha] = maxDate && initialState <> finalState; "OK";
[Fecha] = maxDate; "Not_OK";
BLANK()
)

GL-Category Sequence in adempiere

I want to make a GL-Category Sequence like document sequence for every cash journal.
I added a field in cash journal window called journal number.
I want to generate a number for every cash journal and increment it by 1?
The document sequence is managed by the PO.java class in ADempiere. To use it, you need to add a column with the column name "DocumentNo" to your table. You will need to add the entry in the Sequence table to keep track of the numbers.
Here is the code from PO.java which is run when the record is first saved.
// Set new DocumentNo
String columnName = "DocumentNo";
int index = p_info.getColumnIndex(columnName);
if (index != -1 && p_info.getColumn(index).ColumnSQL == null)
{
String value = (String)get_Value(index);
if (value != null && value.startsWith("<") && value.endsWith(">"))
value = null;
if (value == null || value.length() == 0)
{
int dt = p_info.getColumnIndex("C_DocTypeTarget_ID");
if (dt == -1)
dt = p_info.getColumnIndex("C_DocType_ID");
if (dt != -1) // get based on Doc Type (might return null)
value = DB.getDocumentNo(get_ValueAsInt(dt), m_trxName, false, this);
if (value == null) // not overwritten by DocType and not manually entered
value = DB.getDocumentNo(getAD_Client_ID(), p_info.getTableName(), m_trxName, this);
set_ValueNoCheck(columnName, value);
}
}

D3 Table Filter in R Shiny update SQL server

I am working on a project to update a SQL database with a Shiny app using D3 Table Filter.
I am able to query the server with different text inputs and the table will render with only those rows. The next step is to edit the table in the shiny app, and have that send a query back to the server to update it.
I have enabled editing in specific columns. How could I make an edit and have it send a query?
Thank you very much in advance.
Here is my code so far:
#install.packages("devtools")
#devtools::install_github("ThomasSiegmund/D3TableFilter")
library(shiny)
library(htmlwidgets)
library(D3TableFilter)
library(RSQLite)
library(RODBCext)
library(sqldf)
dbhandle = odbcDriverConnect(connection = "driver={SQL Server};server= ... ;database= ... ;trusted_connection=true")
fulldata = sqlExecute(dbhandle, "SELECT * FROM ...", fetch = TRUE, stringsAsFactors = FALSE)
ui <- fluidPage(
# Application title
titlePanel("Patient Search"),
sidebarLayout(
sidebarPanel(
textInput(inputId = "Id", label = "Search by Account Number, Date of Birth (YYYY-MM-DD) or Last Name"),
textInput(inputId = "NextAppt", label = "Search by Next Appointment (YYYY-MM-DD)"),
submitButton(text = "Go!")
),
mainPanel(
title = 'Patient Search with D3 Table Filter in Shiny',
fluidRow(
column(width = 12, d3tfOutput('data'))
)
)
)
)
# server.R
# --------------------------------------------------------
server <- shinyServer(function(input, output, session) {
#this reactive will return the row numbers that will need to be returned in our table.
#this could depend on any of our inputs: last name, DoB, account number, or next appointment
search.criteria <- reactive({
out <- c()
outAppt <- c()
if(grepl("\\d{4}\\-\\d{2}\\-\\d{2}", input$Id)==TRUE){
out <- which(fulldata$PatientDOB==input$Id)
print(out)
} else if(grepl("\\d{5}", input$Id)==TRUE){
out <- which(fulldata$AccountNo==input$Id)
} else{
out <- which(fulldata$PatientLastName==toupper(input$Id))
}
# filter for appointment
if(grepl("\\d{4}\\-\\d{2}\\-\\d{2}", input$NextAppt)==TRUE){
outAppt <- which(fulldata$NextAppt==input$NextAppt)
if(length(out)){
out <- intersect(out, outAppt)
}else{
out <- outAppt
}
}
out
})
#make the output table
output$data <- renderD3tf({
# Define table properties
tableProps <- list(
btn_reset = TRUE,
# alphabetic sorting for the row names column, numeric for all other columns
col_types = c("string", rep("number", ncol(fulldata)))
);
d3tf(fulldata[search.criteria(),],
tableProps = tableProps,
extensions = list(
list(name = "sort")
),
showRowNames = TRUE,
tableStyle = "table table-bordered",
#this optional argument enables editing on these specific columns
edit = c("col_49", "col_50", "col_51", "col_52", "col_53"));
})
#NEED TO ADD SOMETHING HERE TO SEND QUERY TO SERVER WHEN USER EDITS
})
runApp(list(ui=ui,server=server))
I used rhandsontable. It works better as you can convert the output using hot_to_r. But because of it's simple excel like formatting, it's difficult to render images like DT
If only data, go ahead and use rhandsontable.
Eg.
rhandsontable(df) %>%
hot_cols(colWidths = c(80,150,80,80,80,80,200,200,80,80,300,80,80), manualColumnResize = TRUE) %>%
hot_col(2:13, renderer = "html") %>%
hot_col(2:13, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
hot_col(1, renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
var escaped = Handsontable.helper.stringify(value),
img;
if (escaped.indexOf('http') === 0) {
img = document.createElement('IMG');
img.src = value;
Handsontable.dom.addEvent(img, 'mousedown', function (e){
e.preventDefault(); // prevent selection quirk
});
Handsontable.dom.empty(td);
td.appendChild(img);
}
else {
// render as text
Handsontable.renderers.TextRenderer.apply(this, arguments);
}
return td;
}")
})
observeEvent(input$submitComments, {
a = hot_to_r(input$upcomingAuctionsTable)
# sqlSave(myConnUpcom, a, tablename = "test", rownames = FALSE, varTypes = c(date = "varchar(255)"))
sqlUpdate(myConnUpcom, a, tablename = "temp", index = "item_id")
})

SQL Server Stored Procedure Multiple Condtions

I have this LINQ in C#, which I have to convert to a SQL query. And I am not sure how to do multiple filtering based on conditions:
var geofenceReport = companyContext.GeofenceSimpleReports.Where(x => x.EnterTime != null && x.ExitTime != null && x.MinutesInGeofence != null).AsQueryable();
if (model.GeofenceId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iGeofenceId == model.GeofenceId).AsQueryable();
}
if (model.AssetId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iAssetId == model.AssetId).AsQueryable();
}
if (model.CategoryId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iCategoryId == model.CategoryId).AsQueryable();
}
if (model.SiteId != -1)
{
geofenceReport = geofenceReport.Where(x => x.iSiteId == model.SiteId).AsQueryable();
}
geofenceReport = geofenceReport
.Where(x => x.EnterTime >= model.StartDateTime &&
x.EnterTime <= model.EndDateTime)
.AsQueryable();
So this is what I came up with in SQL:
I created a new type for AssetId:
USE myDatabase
GO
CREATE TYPE idTable AS TABLE (id INT)
And then in SQL:
USE myDatabase
GO
CREATE PROCEDURE [dbo].[xPT_GetGeofenceSummaryReport]
#iAssetIds idTable,
#iGeofenceId INT,
#iCategoryId INT,
#iSiteId INT,
#iAssetId INT
AS
IF #iAssetId != -1
SELECT * FROM GeofenceSimpleReport WHERE iAssetId in (#iAssetIds)
IF #iGeofenceId != -1
SELECT * FROM GeofenceSimpleReport where iGeofenceId = #iGeofenceId
IF #iCategoryId != -1
SELECT * FROM GeofenceSimpleReport where iCategoryId = #iCategoryId
IF #iSiteId != -1
SELECT * FROM GeofenceSimpleReport where iSiteId = #iSiteId
and this GeofenceSimpleReport is a database view.
But this will not work as it is logically wrong. This will 4 separate selects from the GeofenceSimpleReport.
I need to have one read from GeofenceSimpleReport with all filters applied.
And I don't want to read this data temporarily into a TABLE/LIST in memory as there is a lot of data.
Is there a way to write this query dynamically like I am doing in LINQ?
You're thinking about this procedurally, and going through a series of if-statements, rather than approaching your view as a set of data that you can filter all at once.
You can filter on the original criteria related to EntryTime, ExitTime, etc., and then for each parameter for which you provide a filterable value (not -1) then make sure the Id matches that record in the table. Anything where you gave a -1 for the value will automatically make that AND statement true.
I do this sort of thing all the time by passing in nullable parameters - if they're non-NULL then I filter on them - otherwise they just evaluate to true and pass through.
USE myDatabase
GO
CREATE PROCEDURE [dbo].[xPT_GetGeofenceSummaryReport]
#iAssetIds idTable,
#iGeofenceId INT,
#iCategoryId INT,
#iSiteId INT,
#iAssetId INT
AS
SELECT *
FROM GeofenceSimpleReport
WHERE EnterTime IS NOT NULL
AND ExitTime IS NOT NULL
AND MinutesInGeofence IS NOT NULL
AND (#iAssetId = -1 OR iAssetId IN (#iAssetIds))
AND (#iGeofenceId = -1 OR iGeofenceId = #iGeofenceId)
AND (#iCategoryId = -1 OR iCategoryId = #ICategoryId)
AND (#iSiteId = -1 OR iSiteId = #iSiteId)

Querying with nHibernate where todays date is between publishDate and Expiry date

I am trying to figure out how to best query in NHibernate so that the returned results are between for entries where todays time is >= PublishDateTime and <=ExpiryDateTime
The expiry date can be null so I need to allow for that. I found a couple of examples here and here but they seem to work in a different way and accept 2 values and compare to one DB field. I want the other way wrong really.
Query so far:
var query = _session.CreateCriteria<Message>()
.AddOrder(Order.Desc("PublishedDateTime"))
.List<Message>();
return query;
Any suggestions would be greatly received!
Easiest Linq query:
return _session.Query<Message>()
.Where(m => DateTime.Today >= m.PublishDateTime &&
(m.ExpiryDateTime == null ||
DateTime.Now <= m.ExpiryDateTime)
.OrderByDescending(m => m.PublishDateTime)
.ToList();
Criteria:
return _session.CreateCriteria<Message>()
.Add(Restrictions.Le("PublishedDateTime", DateTime.Today) &
(Restrictions.IsNull("ExpiryDateTime") |
Restrictions.Ge("ExpiryDateTime",
DateTime.Now)))
.AddOrder(Order.Desc("PublishedDateTime"))
.List<Message>();
In c# :
var formato = "dd/MM/yyyy h:mm:ss";
var sDesde = DateTime.Now.ToString("dd/MM/yyyy") + " 0:00:00";
var sHasta = DateTime.Now.ToString("dd/MM/yyyy h:mm:ss");
Viaje vDesde = new Viaje { Viajefecha = DateTime.ParseExact(sDesde, formato , null) };
Viaje vHasta = new Viaje { Viajefecha = DateTime.ParseExact(sHasta, formato, null) };
StringWriter strWriter = new StringWriter();
var resultado = cp.sesion.CreateCriteria<Viaje>().Add(Expression.Between("Viajefecha", vDesde.Viajefecha, vHasta.Viajefecha)).AddOrder(Order.Asc("Viajefecha")).List<Viaje>();