Within Where Clause, Nested Case When Statement to return Result with 'OR' - tsql

Good afternoon everyone,
I am trying to combine 2 separate function to create a semi-dynamic where clause. Currently I have 3 identical view in my SQL database which are pretty much the same except for the following line pending on what the user state are.
For WA User.
(dbo.JunctionT.ProcessState = 'CDS' )
For VIC User.
(dbo.JunctionT.ProcessState = 'VIC' OR dbo.JunctionT.ProcessState = 'WA')
For NSW User.
(dbo.JunctionT.ProcessState = 'NSW')
Therefore, if the user is from NSW, return results from their user state.. and if the user is from WA then return result where ProcessState is CDS and if the user is from VIC then return result where ProcessState is either VIC or WA.
I have written the following nested case when statement to try and combine these 3 views into 1:
`dbo.JunctionT.ProcessState =
(CASE
WHEN dbo.fnGetReviewState(CURRENT_USER) = 'NSW' THEN 'NSW'
WHEN dbo.fnGetReviewState(CURRENT_USER) = 'WA' THEN 'CDS'
WHEN dbo.fnGetReviewState(CURRENT_USER) = 'VIC' THEN 'VIC OR WA'
END)`
This seems to be working perfectly fine for both NSW and WA users but when I trial it as a VIC user, it returns nothing. I suspect it could be a syntax issue but i have tried the following without much success:
Have tried to use:('VIC OR WA'), ('VIC' OR 'WA'), ['VIC' OR 'WA'], <'VIC' OR 'WA'>
Hoping that someone more knowledgeable is able to show me what it is I am missing or even suggest a better way to complete this dynamic statement. Many many thanks in advance!!
SeanY

Brien is close. This should do the trick:
case
when dbo.JunctionT.ProcessState = 'NSW' and
dbo.fnGetReviewState(CURRENT_USER) = 'NSW' then 1
when dbo.JunctionT.ProcessState = 'CDS' and
dbo.fnGetReviewState(CURRENT_USER) = 'WA' then 1
when dbo.JunctionT.ProcessState in ( 'VIC', 'WA' ) and
dbo.fnGetReviewState(CURRENT_USER) = 'VIC' then 1
else 0
end = 1

'VIC OR WA' is literally "VIC OR WA", that is why there are no rows returning.
dbo.JunctionT.ProcessState would have to equal "VIC OR WA" (this exact/literal string) to return rows.
What you want instead dbo.JunctionT.ProcessState IN ('VIC','WA')
So there is an element of dynamic SQL involved in order to have your CASE statement return exactly what you need.

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

Spark, Scala, Databricks, combine and add columns

Using Spark/Scala to attempt a "simple" query. I have a file which, after line 1 below runs, looks like this
EmpReg,EmpOT,RegPay,OTPay
Alice,Alice,400,20
Bob,Bob,300,0
Carol,Carol,450,120
Dan,Dan,400,200
Ellen,Ellen,360,40
The first and third columns (EmpReg, RegPay) come from one source and the second and third columns (EmpOT, OTPay) come from a second source. My objective is output that looks like this.
Emp,Pay
Alice,420
Bob,300
Carol,570
Dan,600
Ellen,400
Here is the code that I have been trying, at least what I have saved.
var q2 = q.join(q1, q("EmpReg") === q1("EmpOT"), "fullouter")
//q2 = q2.select("EmpReg", ($"RegPay" + $"OTPay"))
//q2 = q2.groupBy($"EmpReg".sum($"RegPay" + $"OTPay"))
var add = q2.select(($"RegPay" + $"OTPay"))
//q2 = q2.sum("RegPay", "OTPay")
//q2 = q2.groupBy("EmpReg", "EmpOT")
//var q2 = q.join(q1).where("EmpReg") === "EmpOT"))
//q2 = q2.select("EmpReg").sum("RegPay", "OTPay")
//q2.show
add.show
[q] is the first file which represents regular pay. [q1] is the second file which represents overtime pay. [q2] is the combination shown in the first example above. Primary keys are [EmpReg] and [EmpOT]. don't really need to combine [EmpReg] and [EmpOT] since they are the same, and it doesn't make any difference which I use.
I really need to add [RegPay] and [OTPay] to get [Pay], but for the life of me I can't get it to work. The lines commented out return various errors. I can add the two pay columns, and select an appropriate employee column, but can't seem to do it in one query. I am constrained to use Scala on Databricks. Othewise, I might do something like this.
select q.EmpReg as Emp, (q.RegPay + q1.OTPay) as Pay
from q join q1 on q.EmpReg = q1.EmpOT
(Why can't things ever be simple?)
You can use a similar approach as in your SQL query:
val q2 = q.join(q1, q("EmpReg") === q1("EmpOT"), "fullouter")
val add = q2.select(q("EmpReg").as("Emp"), (q("RegPay") + q1("OTPay")).as("Pay"))
Your code has this line
q2.select("EmpReg", ($"RegPay" + $"OTPay"))
which should work if you add $ before "EmpReg". You can't have both strings and columns in the select statement. This works in Python but not Scala.

Magento 2 - Category List Sort by Position with Sub Category Not Working

A little background, I'm trying to do a custom Category listing, but at the moment it seems the Category not being sort as I seen on Admin.
Here's the code that I've done so far
$current_store = $this->_storeManager->getStore();
$root_category_id = $this->_storeManager->getStore()->getRootCategoryId();
$collection = $this->_categoryCollectionFactory->create()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active', 1)
->setStore($current_store);
return $collection->addAttributeToFilter('entity_id', array('nin' => $root_category_id))
->setOrder('position','ASC');
And the result, when I tried to echo its ID is like below
3
10
4
11
5
7
12
8
15
9
13
14
16
6
But, from the Admin, it doesn't reflect the order correctly, below is the figure
The problem that I realize is, that, I have sub category, I tried to echo the query from above code, and then copy-paste it into sql GUI, and I realize, the position is kinda weird but, it does make-sense, because it's a sub category.
Here's the result when I execute the query on sql GUI
So, what I tried to achieve is to sort above result, to reflecting what I set on Admin.
Is there anything that I missed? I'm not sure where to look, since I've been stuck around 1-2 days, not sure what's the proper keyword, almost all keyword I did will arrive to product sort or kind of that, not category sort
Thanks in Advance!
For those who still needs some answer relating to this question, here's the answer
...
$store_categories = $this->_categoryFactory->create();
$store_categories = $store_categories->load($this->_root_category_id)->getChildrenCategories();
foreach ($store_categories as $category) {
//get id
$category_id = $category->getId();
//get category model
$category = $this->getCategoryModel($category_id);
$sub_children = $this->getActiveChildCategories($category);
if (count($sub_children) > 0) {
$sub_categories = $this->getSubCategory($sub_children);
$categories = array_merge($categories, $sub_categories);
} else {
$categories[] = $category;
}
}
...
The _categoryFactory comes from Magento\Catalog\Model\CategoryFactory.
It's pretty much covering what I want, but not really as I expected before, because I think it's not really efficient.
PS - I'm still new on Magento 2, so, if someone else has other answer that might be pretty much like I expect, then, I'm happily change it as Accepted Answer. :)
Goodluck!

How do i exclude some elements of a list from further calculations

So I have a list of stars and their respective distances. My assignment is to find which stars are in a certain distance (+- 10parsec). I want to exclude some of them from further calculations in the program. The thing is I don't want to remove them completely so remove, pop etc isn't helping me. I still want those stars on the list to be present in my output csv. I just want a line saying something like those stars which don't support the if statement, don't use them in this calculation. So i guess the output would be blank for those.
I suppose it is an if or for statement, to mark those bad stars as False and then down the line use calculation that excludes those faulty stars.
I'm a physics student and this is my first python program ever! Please be cool about my ignorance...
Edit: forgive me if i include useless stuff i don't really know what's important. I also use uncertainties library if its of any use
column_names = ['id','pi','s_pi','v_r' ,'s_v', 'dis', 'X',
'ra_h', 'ra_m', 'ra_s','dec_d', 'dec_m',
'dec_s', 'ma', 's_ma', 'md', 's_md']
data = pd.read_csv("hyades_data.dat", skiprows=2, sep='\s+',
names=column_names)
calculations with all
v_r = unumpy.uarray(data['v_r'], data['s_v'])
ma = unumpy.uarray(data['ma'], data['s_ma'])
md = unumpy.uarray(data['md'], data['s_md'])
mi = unumpy.sqrt(ma**2+md**2)
r_m = v_r*unumpy.tan(th)/(4.74*mi/1000)
diff = np.abs(r_pc - r_m)
'''
if np.abs(dist-46.43) <=10:
r_m=True
else r_m=False
at this point i want to make the distiction
'''
mean_diff = diff.mean()
print("Mean : ")
print(mean_diff)
print(a_ref,d_ref)
df_va=pd.DataFrame(v_r)
df_mi = pd.DataFrame(mi)
df_rm = pd.DataFrame(r_m)
df_rpc = pd.DataFrame(r_pc)
df_diff = pd.DataFrame(diff)
#df_mean_diff = pd.DataFrame(mean_diff)
ve = v_r*np.tan(th)
output = pd.concat([data['id'], ra, dec, th_d, df_mi, df_rm, df_rpc,
df_diff,df_va], axis=1)
output.columns = ['id','ra', 'dec', 'th_d','mi', 'r_m', 'r_pc',
'dist_diff','va']
output.to_csv('results.csv', index=False)

In Linq to EF 4.0, I want to return rows matching a list or all rows if the list is empty. How do I do this in an elegant way?

This sort of thing:
Dim MatchingValues() As Integer = {5, 6, 7}
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
...works great. However, in my case, the values in MatchingValues are provided by the user. If none are provided, all rows ought to be returned. It would be wonderful if I could do this:
Return From e in context.entity
Where (MatchingValues.Length = 0) OrElse (MatchingValues.Contains(e.Id))
Alas, the array length test cannot be converted to SQL. I could, of course, code this:
If MatchingValues.Length = 0 Then
Return From e in context.entity
Else
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
End If
This solution doesn't scale well. My application needs to work with 5 such lists, which means I'd need to code 32 queries, one for every situation.
I could also fill MatchingValues with every existing value when the user doesn't want to use the filter. However, there could be thousands of values in each of the five lists. Again, that's not optimal.
There must be a better way. Ideas?
Give this a try: (Sorry for the C# code, but you get the idea)
IQueryable<T> query = context.Entity;
if (matchingValues.Length < 0) {
query = query.Where(e => matchingValues.Contains(e.Id));
}
You could do this with the other lists aswell.