MySql case statement error - mysql

When I use this code in a create view construct it returns empty result set.
I have tried using a column name after the case and removing the column name in the when lines...no change... any ideas. I have determined the issue is at the case statement by commenting it out and running it and it works fine then....
CREATE or REPLACE VIEW orderMSTRview
AS
SELECT SB.name "Brand", O.orderID "Order ID", O.orderRecID "Record ID", O.orderDate "Date Created",
O.salesRepName "Sales Rep Name", O.salesRepEmail "Sales Rep Email",
O.orderNumer "Order Number", O.orderType "Order Type",
CASE
when fulfillStatus = 0 then 'open'
when fulfillStatus = 1 then 'processing'
when fulfillStatus = 2 then 'complete'
when fulfillStatus = 5 then 'Shipped'
when fulfillStatus = 9 then 'void'
END as "Order Status" ,
IF(O.payStatus=0,'unpaid','paid') "Payment Status",
O.totalOrderQuantity "Total Order Quantity",
O.subtotalOrderValue "Subtotal Order Value",
O.totalOrderValue "Total Order Value", O.credit "Order Credit",
O.taxAmount "Tax Amount", O.shippingCost "Shipping Cost",
O.finalInvoiceValue "Invoice Amount", O.currency "Currency",
O.shipDate "Ship Date", O.cancelAfter "Cancel Date", O.terms "Terms",
O.buyerName "Buyer Name", O.buyerEmail "Buyer Email", O.buyerPhone "Buyer Phone", O.custCode1 "Customer Code1", O.custCode2 "Customer Code2",
O.custERP "Customer ERP", O.customerPO "Customer PO", O.custVat "VAT number",
O.billToName "Bill To Name", O.billToStreet1 "Bill To Address1" ,
O.billToStreet2 "Bill To Address2", O.billToCity "Bill To City",
O.billToState "Bill To State", O.billToZip "Bill To Zip code",
O.shipToName "Ship To Name", O.shipToStreet1 "Ship To Address1",
O.shipToStreet2 "Ship To Address2",
O.shipToCity "Ship To City", O.shipToState "Ship To State",
O.shipToZip "Ship To Zip code",
O.tagname1 "Tag 1", O.tagname2 "Tag 2", O.tagname3 "Tag 3"
FROM orders as O left join showroom_brand as SB on O.showroomID = SB.sid
WHERE O.orderDate >= '2015-01-01' and SB.name IS NOT NULL;

Do it like this example:
try to run this
set #fulfillStatus = 1;
select
CASE
when #fulfillStatus = 0 then 'open'
when #fulfillStatus = 1 then 'processing'
when #fulfillStatus = 2 then 'complete'
when #fulfillStatus = 5 then 'Shipped'
when #fulfillStatus = 9 then 'void'
else "None"
END as "Order Status"

Related

Implement function call (grouped running totals) in query

I have a function called fxGroupedRunningTotal (fxGRT) and a query (Totals). I want to call fxGRT within Totals, so that I get a column that shows the grouped running totals. I have only managed to test the fxGRT by importing the Totals query.
Query that uses Totals and calls fxGRT (built for testing the function):
let
Source = Totals,
BufferedValues = List.Buffer(Source[PD]),
BufferedMaterials = List.Buffer(Source[Material]),
RT = Table.FromColumns(
{
Source[Material], Source[Date], Source[PD],
fxGroupedRunningTotal(BufferedValues, BufferedMaterials)
},
{
"Material",
"Date",
"PD",
"Running Total"
})
in
RT
fxGroupedRunningTotals:
(values as list, grouping as list) as list =>
let
GRTList = List.Generate
(
()=> [ GRT = values{0}, i = 0 ],
each [i] < List.Count(values),
each try if grouping{[i]} = grouping{[i] + 1}
then [GRT = [GRT] + values {[i] + 1}, i = [i] + 1]
else [GRT = values{[i] + 1}, i = [i] + 1]
otherwise [i = [i] + 1]
,
each [GRT]
)
in
GRTList
Totals:
let
Källa = Table.NestedJoin(Cohv,{"Prod MDate"},Resb,{"Del Mdate"},"Resb",JoinKind.FullOuter),
#"Expanderad Resb" = Table.ExpandTableColumn(Källa, "Resb", {"Del Material", "Del Date", "Del Qty", "Del Mdate"}, {"Del Material", "Del Date", "Del Qty", "Del Mdate"}),
#"PD Date" = Table.AddColumn(#"Expanderad Resb", "PD Date", each if [Prod Date] = null then [Del Date] else [Prod Date]),
#"PD Material" = Table.AddColumn(#"PD Date", "PD Material", each if [Material Number] = null then [Del Material] else [Material Number]),
#"PD Mdate" = Table.AddColumn(#"PD Material", "PD Mdate", each [PD Material] & "." & Date.ToText([PD Date])),
#"Borttagna kolumner" = Table.RemoveColumns(#"PD Mdate",{"Prod Date", "Prod MDate", "Del Date", "Del Mdate"}),
#"Ändrad typ1" = Table.TransformColumnTypes(#"Borttagna kolumner",{{"PD Date", type date}}),
#"Ihopslagna frågor" = Table.NestedJoin(#"Ändrad typ1",{"PD Material"},Matmas,{"Material"},"Matmas",JoinKind.FullOuter),
#"Expanderad Matmas" = Table.ExpandTableColumn(#"Ihopslagna frågor", "Matmas", {"Material", "Material Description", "MRP Controller", "Safety stock", "Minimum Lot Size", "In Stock"}, {"Material", "Material Description", "MRP Controller", "Safety stock", "Minimum Lot Size", "In Stock"}),
#"Omdöpta kolumner" = Table.RenameColumns(#"Expanderad Matmas",{{"Material", "M Material"}}),
#"Lägg till egen" = Table.AddColumn(#"Omdöpta kolumner", "Material", each if [PD Material] = null then [M Material]else [PD Material]),
#"Borttagna kolumner1" = Table.RemoveColumns(#"Lägg till egen",{"Material Number", "Del Material", "PD Material", "M Material"}),
#"Lägg till egen1" = Table.AddColumn(#"Borttagna kolumner1", "Date", each if [PD Date] = null then DateTime.LocalNow() else [PD Date]),
#"Borttagna kolumner2" = Table.RemoveColumns(#"Lägg till egen1",{"PD Date"}),
#"Lägg till egen2" = Table.AddColumn(#"Borttagna kolumner2", "Date in stock", each if [Date] = DateTime.Date(DateTime.LocalNow()) then [In Stock] else null),
#"Borttagna kolumner3" = Table.RemoveColumns(#"Lägg till egen2",{"Date in stock"}),
#"Ändrad typ" = Table.TransformColumnTypes(#"Borttagna kolumner3",{{"Date", type date}}),
#"Ersatt värde" = Table.ReplaceValue(#"Ändrad typ",null,0,Replacer.ReplaceValue,{"Prod Qty"}),
#"Ersatt värde1" = Table.ReplaceValue(#"Ersatt värde",null,0,Replacer.ReplaceValue,{"Del Qty"}),
#"Ihopslagna frågor1" = Table.NestedJoin(#"Ersatt värde1",{"Date"},Dates,{"Date"},"Dates",JoinKind.RightOuter),
#"Expanderad Dates" = Table.ExpandTableColumn(#"Ihopslagna frågor1", "Dates", {"Current Date"}, {"Current Date"}),
#"Omdöpta kolumner1" = Table.RenameColumns(#"Expanderad Dates",{{"Date", "D Date"}}),
Date = Table.AddColumn(#"Omdöpta kolumner1", "Date", each if [D Date] is null then DateTime.Date(DateTime.LocalNow()) else [D Date]),
PD = Table.AddColumn(Date, "PD", each if [Current Date] = "Yes" then [In Stock]+[Prod Qty]-[Del Qty] else [Prod Qty]-[Del Qty])
in
PD
So how do I implement this function into a new column in my Totals? My attempts keep failing. Do I have to make a reference to Totals in order to make this work? It feels so wrong, since that would double the work load (?) with the data. I would like it to be as quick as possible.
You can reference the previous step as a table. Thus your query can be written
let
[...all your previous steps...]
PD = Table.AddColumn(Date, "PD", each if [Current Date] = "Yes" then [In Stock]+[Prod Qty]-[Del Qty] else [Prod Qty]-[Del Qty]),
RT =
Table.FromColumns(
List.Combine({Table.ToColumns(PD), {fxGroupedRunningTotals(PD[Material], PD[PD])}}),
List.Combine({Table.ColumnNames(PD), {"Running Total"}})
)
in
RT
This converts the table to a list of columns, adds on the new running total column (calling the function you've defined on specific columns of the table from the previous step PD), and then glues those columns back together with a similar method to preserve the column names and add a new one.

Mysql order by regex varchar not working correctly

I`m trying to do simple order by (varchar field) query
My current implementation is:
SELECT id,name
FROM customer
ORDER BY IF(name RLIKE '^[a-z]', 1, 2), name
CREATE TABLE `customer` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
When i order them DESC i expect the list to be the same (reversed) but actually it`s not. For example this "555555555" name is at the bottom of ASC and again almost at the bottom on DESC
If i order it ASC the results are :
"id" "name"
"147" "AAAAAAA 55555"
"86" "BBB"
"71" "Building"
"148" "Building 2"
"150" "Corporation build"
"142" "Customer 10.03.17"
"116" "Customer new"
"131" "Customer without templates"
"104" "CustomerTEST"
"117" "Customer_55 at moment"
"33" "Ex_Name1414 project Support"
"139" "FFF"
"126" "GEARY Project"
"133" "MMMMM1-1"
"127" "NEW 14"
"134" "NIKOI"
"135" "nnn"
"144" "NNN"
"138" "NNNmmm111"
"91" "Project 1818"
"105" "Project GO"
"124" "Project ZIP"
"128" "SAN FRANCISCO Project"
"182" "test"
"181" "test"
"149" "TEST 9/6"
"115" "TEST Customer"
"178" "test2"
"180" "testing"
"120" "TESTOVI"
"145" "vvv"
"121" "VVVV dnes22"
"132" "VVVVV Project"
"130" "Without Template"
"152" " CATEST CONST "
"156" " MOUNT CONST"
"154" " RUDOH CONST "
"153" " TEST CONST "
"146" "555555555"
And when i try to order it DESC the result is not the same (reversed)
Actually the result is:
"id" "name"
"130" "Without Template"
"132" "VVVVV Project"
"121" "VVVV dnes22"
"145" "vvv"
"120" "TESTOVI"
"180" "testing"
"178" "test2"
"115" "TEST Customer"
"149" "TEST 9/6"
"182" "test"
"181" "test"
"128" "SAN FRANCISCO Project"
"124" "Project ZIP"
"105" "Project GO"
"91" "Project 1818"
"138" "NNNmmm111"
"144" "NNN"
"135" "nnn"
"134" "NIKOI"
"127" "NEW 14"
"133" "MMMMM1-1"
"126" "GEARY Project"
"139" "FFF"
"33" "Ex_Name1414 project Support"
"117" "Customer_55 at moment"
"104" "CustomerTEST"
"131" "Customer without templates"
"116" "Customer new"
"142" "Customer 10.03.17"
"150" "Corporation build"
"148" "Building 2"
"71" "Building"
"86" "BBB"
"147" "AAAAAAA 55555"
"146" "555555555"
"153" " TEST CONST "
"154" " RUDOH CONST "
"156" " MOUNT CONST"
"152" " CATEST CONST "
It looks like you only changed the order of the name values but not of the groups (1 or 2). in case you want to flip the list completely you have to use the following query using DESC on both order parts (condition and column name):
SELECT id, name
FROM customer
ORDER BY IF(name RLIKE '^[a-z]', 1, 2) DESC, name DESC
It looks like you are using the following query at the moment:
SELECT id, name
FROM customer
ORDER BY IF(name RLIKE '^[a-z]', 1, 2), name DESC
-- same as
SELECT id, name
FROM customer
ORDER BY IF(name RLIKE '^[a-z]', 1, 2) ASC, name DESC
In this case the groups are ordered ASC while the names are ordered DESC.

How to add a coulmn with seqeunce number

I am trying to add a column to a query that will put a line number for each line with in a transaction.
STORE CODE TRANS NUMBER LINE NUMBER
12 1234 1
12 1234 2
12 1234 3
12 2345 1
12 2345 2
This is my query any idea how to do this?
select sal_snum as "Store Code",sal_trn as "Transaction Number",
sal_trm as "Register",sal_dt as "TrasactionDate",sal_tm as "TranactionTime",
sum(sal_tax) as "TotalTaxAmount","" as "CustomerCode",
"" As "CustomerCardType","" as "CustomerCardNumber",
"" as "TotalPointsOnTransaction","" as "Note1","" as "Note2",
sal_emp as "Staff 1 Code", "" as "Staff 2 Code","" as "Global Tax Code",
"" as "Shipping Address Line 1","" as "Shipping Address Line 2",
"" as "Shipping Contatc Name","" as "Shipping Contact Phone",
"" as "Shipping Note","" as "Shipping Latitude",
"" as "Shippong Longitude","" as "Layaway/Order Number","" as "Layaway Status"
from sales
group by sal_snum,sal_trn,sal_trm ,sal_dt ,sal_tm,sal_emp
You can use this. You can put your hole query in like this.
SELECT #nr := (#nr+1) AS nr,p.*
group by sal_snum,sal_trn,sal_trm ,sal_dt ,sal_tm,sal_emp
FROM (
select sal_snum as "Store Code",sal_trn as "Transaction Number",
sal_trm as "Register",sal_dt as "TrasactionDate",sal_tm as "TranactionTime",
sum(sal_tax) as "TotalTaxAmount","" as "CustomerCode",
"" As "CustomerCardType","" as "CustomerCardNumber",
"" as "TotalPointsOnTransaction","" as "Note1","" as "Note2",
sal_emp as "Staff 1 Code", "" as "Staff 2 Code","" as "Global Tax Code",
"" as "Shipping Address Line 1","" as "Shipping Address Line 2",
"" as "Shipping Contatc Name","" as "Shipping Contact Phone",
"" as "Shipping Note","" as "Shipping Latitude",
"" as "Shippong Longitude","" as "Layaway/Order Number","" as "Layaway Status"
from sales
) p
CROSS JOIN ( SELECT #nr := 0) AS parameter
ORDER BY nr;

MySql combining update with an inner join and limit

I'm trying to update a row in table amga with just one row from table amgb joined by their itemTempId.
My problem is that, there may be upto 6 rows in table amgb for that itemTempIdand I need to use only one from it for the update.
I'm familiar with doing updates with joins, but when I added a Limit (so as to get just one row) I get the error message Incorrect usage of update and limit. I read that this is not possible, but would there be another way to do this?
amga
"id" "itemId" "itemTempId" "itemImageName" "itemName" "itemCountry" "userId"
"1" "US1" "T001" \N "Samsung Galaxy Note 5" "US" "1"
"2" "CA2" "T002" \N "Samsung Galaxy Note 6" "CA" "2"
"3" "UK3" "T003" \N "Samsung Galaxy Note 7" "UK" "3"
amgb
"id" "itemId" "itemTempId" "itemImageName" "userId"
"1" "US1" "T001" "front.jpg" "1"
"2" "US1" "T001" "side-left.jpg" "1"
"3" "US1" "T001" "side-right.jpg" "1"
"4" "US1" "T001" "back.jpg" "1"
"5" "CA2" "T002" "front.jpg" "2"
"6" "CA2" "T002" "side-left.jpg" "2"
"7" "CA2" "T002" "side-right.jpg" "2"
"8" "CA2" "T002" "back.jpg" "2"
"9" "UK3" "T003" "front.jpg" "3"
Sql I used
update amga a inner join amgb b on a.itemTempId = b.itemTempId
set a.itemImageName = b.itemImageName where a.itemTempId = 'T001' limit 1;
Expected results: Table amga after update
"id" "itemId" "itemTempId" "itemImageName" "itemName" "itemCountry" "userId"
"1" "US1" "T001" front.jpg "Samsung Galaxy Note 5" "US" "1"
"2" "CA2" "T002" \N "Samsung Galaxy Note 6" "CA" "2"
"3" "UK3" "T003" \N "Samsung Galaxy Note 7" "UK" "3"
Note: itemTempId is updated with front.jpg, which is the first row for itemTempId = T001 in amgb
Any help appreciated.
Update
I noticed it works if I remove the limit, and that it updates too. But is it the right way to do it? What does MySql do with the other rows in the select?
update amga a inner join amgb b on a.itemTempId = b.itemTempId
set a.itemImageName = b.itemImageName where a.itemTempId = 'T001';
Maybe you can use a subquery:
UPDATE amga a
SET a.itemImageName =
(SELECT b.itemImageName
FROM amgb b
WHERE b.itemTempId = 'T001'
ORDER BY b.id LIMIT 1)
WHERE a.itemTempId = 'T001'

IIF expression missing the bracket

Im using the iff expression in the query. trying to run it but it says this missing a closing parenthesis, bracket. but i checked in the expression. not sure about which one is missing. thanks!
=IIf([Project status]="Project request", "1", IIf([Project status]="Project charter", "2", IIf([Project status]="Started project", "3", IIf([Project status]="Technically closed", "4", IIf([Project status]="Closed", "5", IIf([Project status]="Cancelled", "6", IIf([Project status]="Rejected ", "7","null")))
Try this IIF,
=IIf([Project status] = "Project request", "1", IIf([Project status] = "Project charter", "2", IIf([Project status] = "Started project", "3", IIf([Project status] = "Technically closed", "4", IIf([Project status]="Closed", "5", IIf([Project status] = "Cancelled", "6", IIf([Project status]= "Rejected ", "7", "null")))))))
You could solve your problem much simply by creating a new table.
tbl_projStatus
==============
projStatus | projectCode
--------------------+---------------
Project request | 1
Project charter | 2
Started project | 3
Technically closed | 4
Closed | 5
Cancelled | 6
Rejected | 7
Then you could use a DLookup, like
= DLookup("projectCode", "tbl_projStatus", "projStatus = " & [Project status])