TSQL divide one count by another to give a proportion - tsql

I would like to calculate the proportion of animals in column BreedTypeID with a value of 1. I think the easiest way is to count the n BreedTypeID = 1 / total BreedTypeID. (I also wnat them to have the same YearDOB and substring in their ID as shown) I tried the following:
(COUNT([dbo].[tblBreed].[BreedTypeID])=1 OVER (PARTITION BY Substring([AnimalNo],6,6), YEAR([DOB]))/ COUNT([dbo].[tblBreed].[BreedTypeID]) OVER (PARTITION BY Substring([AnimalNo],6,6), YEAR([DOB]))) As Proportion
But it bugged with the COUNT([dbo].[tblBreed].[BreedTypeID])=1
How can I specify to only count [BreedTypeID] when =1?
Many thanks

This will fix your problem, although I would suggest you use table aliases instead of schema.table.column. Much easier to read:
Just replace:
COUNT([dbo].[tblBreed].[BreedTypeID])=1
WITH
SUM( CASE WHEN [dbo].[tblBreed].[BreedTypeID] = 1 THEN 1 ELSE 0 END)

Related

How to create a functional or where clause from a list of where clauses in kdb?

I have the following where clauses :
q)).tst.wc
(max$["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")))
(like;`Col2;,"B0000000999")
I want to crate the following query:
,(|;(max$["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")));(like;`Col2;,"B0000000999"))
I tried
(or;.tst.wc) //doesn't work
(or; first each .tst.wc) // doesn't work
(or;.tst.wc 0;.tst.wc 1) // works
however I cannot use the last one because I don't know how many where clauses will be there. Any suggestions?
You can just append them to or as follows:
q)(or),.tst.wc
|
($["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")))
(like;`Col2;,"B0000000999")
q)(or;.tst.wc 0;.tst.wc 1)~(or),.tst.wc
1b
EDIT: if you have an unknown number of where clauses and they all need an "or" between them all then you can use:
(or;;)/[.tst.wc]
however this where clause will fast become inefficient as nested "or"s are not optimal query filtering - each clause needs to be applied to the entire length of the table
so the best I could find so far was :
{[x;y]$[x~();(or;y);x,enlist y]}/[();.tst.wc]
... ready to accept and upvote a better answer ...
What about using any? If I understand you correctly you are creating any number of or conditions.
t:([]a:til 10;b:`a`b`c`d`e`f`g`h`i`j;c:10*til 10);
.tst.wc:((=;`a;0);(=;`b;enlist `d);(=;`c;90));
?[t;enlist ((any),enlist (enlist),.tst.wc);0b;()!()]
a b c
------
0 a 0
3 d 30
9 j 90
// also works with one
.tst.wc2:enlist (=;`a;0);
?[t;enlist ((any),enlist (enlist),.tst.wc2);0b;()!()]
a b c
-----
0 a 0

Manipulating last two rows if there's data based on a Cut date

This question is a slightly varied version of this one...
Now I'm using Measures instead of Calculated columns and the date is static instead of having it based on a dropdown list.
Here's the Power BI test .pbix file:
https://drive.google.com/open?id=1OG7keqhdvDUDYkFQFMHyxcpi9Zi6Pn3d
This printscreen describes what I'm trying to accomplish:
Basically the date in P6 Update table is used as a cut date and will be fixed\static. It's imported from an Excel sheet where the user can customize it however they want.
Here's what should happen when a matching row in Test data table is found for P6 Update date:
column Earned Daily - must have its value summed with the next row if there's one;
column Earned Cum - must grab the next row's value;
all the previous rows should remain intact, that is, their values won't change;
all subsequent rows must have their values assigned 0.
So for example:
If P6 Update is 1-May-2018, this is the expected result:
1-May 7,498 52,106
2-May 0 0
If P6 Update is 30-Apr-2018, this is the expected result:
30-Apr 13,173 50,699
1-May 0 0
2-May 0 0
If P6 Update is 29-Apr-2018, this is the expected result:
29-Apr 11,906 44,608
30-Apr 0 0
1-May 0 0
2-May 0 0
and so on...
Hope this makes sense.
This is easier in Excel, but trying to do this in Power BI is making me go nuts.
I will ignore previously asked related questions and start from scratch.
First, create a measure:
Current Earn =
CALCULATE (
SUM( 'Test data'[Value]),
'Test data'[Act Rem] = "Actual Units",
'Test data'[Type] = "Current"
)
This measure will be used in other measures, to save you from typing all these conditions ("Actual Units" and "Current") again and again. It's a great practice to re-use measures in other measures - saves work, makes code cleaner and easier to refactor.
Create another measure:
Cut Date = SELECTEDVALUE('P6 Update'[Date])
We will use this measure whenever we need a cut off date. Please note that it does not have to be hard-coded - if P6 table contains a list of dates, you can create a pull-down slicer from the dates, and can choose the cut-off date dynamically. The formula will work properly.
Create third measure:
Next Earn =
VAR Cut_Date = [Cut Date]
VAR Current_Date = MAX ( 'Test data'[Date] )
VAR Next_Date = Current_Date + 1
VAR Current_Earn = [Current Earn]
VAR Next_Earn = CALCULATE ( [Current Earn], 'Test data'[Date] = Next_Date )
RETURN
SWITCH (
TRUE,
Current_Date < Cut_Date, Current_Earn,
Current_Date = Cut_Date, Current_Earn + Next_Earn,
BLANK ()
)
I am not sure if "Next Earn" is a good name for it, hopefully you will find a more intuitive name. The way it works: we save all necessary inputs into variables, and then use SWITCH function to define the results. Hopefully it's self-explanatory. (Note: if you need 0 above Cut Date, replace BLANK() with 0).
Finally, we define a measure for cumulative earn. It does not require any special logic, because previous measure takes care of it properly:
Cum Earn =
VAR Current_Date = MAX('Test data'[Date])
RETURN
CALCULATE(
[Next Earn],
FILTER(ALL('Test data'[Date]), 'Test data'[Date] <= Current_Date))
Result:

Summary Percentage Yes vs No

Basically I'm looking for a formula to see how many times Yes was used vs. No.
I have something like this:
(({Command.result} ="Yes") / {Command.result})*100
Which makes sense in my head, but I keep getting:
A number, or currency amount is required.
Your current formula attempts to divide a boolean type through by a string. You can only perform division with numbers.
Instead, create two formulas as individual counts of Yes or No:
#YesCount:
If ({Command.result} = "Yes") Then 1 Else 0
#NoCount:
If ({Command.result} = "No") Then 1 Else 0
For the percentage, create two more formulas:
#YesPercent:
100 / Count ({Command.result}) * Sum ({#YesCount})
#NoPercent:
100 / Count ({Command.result}) * Sum ({#NoCount})

MDX Calculated member filter by dimension attribute and member value

I have MDX (similar to one questioned and answered here):
(
[PX Market].[PX MARKET NAME].&[Elbas],
[Measures].[PX QUANTITY]
)
It works for me (it filters measures to value "Elbas" only). But I need another filtering - to have only values which are < or > than 0. There shoud be some condition similar to "[Measures].[PX QUANTITY] < 0". But I do not know how to implement it.
Thank for any of your advice.
Ondra
Table looks similar like this:
PX_MARKET_NAME; PX_QUANTITY
Elbas; 5
Elbas; -3
Elspot; 4
In result I need only 2nd value (-3). Which belongs to Elbas and is smaller then 0.
So far I tried this, but it is now working :(
FILTER
(
[PX Market].[PX MARKET NAME].&[Elbas],
[Measures].[PX PURCHASE]
) < 0
Try that:
IIF(
([PX Market].[PX MARKET NAME].&[Elbas],[Measures].[PX QUANTITY]) < 0,
([PX Market].[PX MARKET NAME].&[Elbas],[Measures].[PX QUANTITY]),
NULL
)

T-SQL: How to make a positive value turn into the equivalent negative value (e.g "10.00" to "-10.00"

Ok so i have a DECIMAL field called "Score". (e.g 10.00)
Now, in my SP, i want to increment/decrement the value of this field in update transactions.
So i might want to do this:
SET #NewScore = #CurrentScore + #Points
Where #Points is the value im going to increment/decrement.
Now lets say #Points = 10.00.
In a certain scenario, i want 10.00 to become -10.00
So the statement would be translated to:
SET #NewScore = #CurrentScore + -10.00
How can i do that?
I know its a strange question, but basically i want that statement to be dynamic, in that i dont want to have a different statement for incrementing/decrementing the value.
I just want something like this:
SET #Points = 10.00
IF #ActivityBeingPerformedIsFoo
BEGIN
-- SET #Points to be equivalent negative value, (e.g -10.00)
END
SET #NewScore = #CurrentScore + #Points
Can't you just multiply it by -1?
I always do 0 - #Points. It was this way in some code I inherited. "A foolish consistency..."
Multiply #Points by -1 in that certain scenario.
I thought of subtracting it with a multiple of 2, i.e. x - 2x