How to add a coulmn with seqeunce number - mysql

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;

Related

correctly reading data from a text file with json format in it

Imagine I have a text file with the following two observations:
liame#ziggo.nl:horse22| homeAddress = {
"city": "AMSTERDAM",
"houseNumber": "5",
"houseNumberAddition": null,
"postalCode": "1111 AN",
"street": "Walker",
"__typename": "ShopperAddress"
}
johndoe#live.nl:pizzalover1 | homeAddress = {
"city": "NEW YOK",
"houseNumber": "23",
"houseNumberAddition": null,
"postalCode": "9999 HV",
"street": "Marie Curie",
"__typename": "ShopperAddress"
}
Is there a way to read in this text file in such a way that the data frame looks like this:
username1 username2 city housenumber housenumber_addition postalcode street typename
liam#ziggo.nl horse22 AMSTERDAM 5 null 1111 AN Walker ShopperAddress
johndoe#live.nl pizzalover1 NEW YORK 23 null 9999 HV Marie Curie ShopperAddress
Thx
Your text file shows that there is a pattern to how the data is encoded:
<username1>:<username2> | homeAddress = {
<json_data>
}
We are going to parse the file in 2 passes: first pass to separate one record
from another and second pass to pick out the fields within a record:
A record ends on a line containing a single "}" character
Use regex to separate the fields inside a record
import json, re
import pandas as pd
data = []
pattern = re.compile(r"(.+?):(.+?)\s*\|\s*homeAddress = (.+)", re.DOTALL)
with open('data.txt') as fp:
record = ""
for line in fp:
record += line
if line == "}\n":
m = pattern.match(record)
if m:
username1 = m.group(1)
username2 = m.group(2)
home_address = json.loads(m.group(3))
data.append({
"username1": username1,
"username2": username2,
**home_address
})
record = ""
df = pd.DataFrame(data).rename(columns={"__typename": "typename"})
You can rework a bit your original text to make it a valid dictionary/JSON and feed it to pandas.read_json:
(pd.read_json('[%s]'%re.sub(r'([^:\n]+):([^\|:]+)\s*\|\s*homeAddress = {',
r',{\n "username1":"\1",\n "username2":"\2",',
text)[1:])
.rename(columns={'houseNumber': 'housenumber',
'houseNumberAddition': 'housenumber_addition',
'postalCode': 'postalcode',
'__typename': 'typename'})
)
output:
username1 username2 city housenumber housenumber_addition postalcode street typename
0 liame#ziggo.nl horse22 AMSTERDAM 5 NaN 1111 AN Walker ShopperAddress
1 johndoe#live.nl pizzalover1 NEW YOK 23 NaN 9999 HV Marie Curie ShopperAddress
intermediate reworked data:
[{
"username1":"liame#ziggo.nl",
"username2":"horse22",
"city": "AMSTERDAM",
"houseNumber": "5",
"houseNumberAddition": null,
"postalCode": "1111 AN",
"street": "Walker",
"__typename": "ShopperAddress"
}
,{
"username1":"johndoe#live.nl",
"username2":"pizzalover1 ",
"city": "NEW YOK",
"houseNumber": "23",
"houseNumberAddition": null,
"postalCode": "9999 HV",
"street": "Marie Curie",
"__typename": "ShopperAddress"
}]

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.

MySql case statement error

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"

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])

Mysql stuck with order by desc and limit

I have a table like this:
"id" "UserName" "score"
"1" "User 1" "2"
"2" "User 2" "5"
"3" "User 3" "3"
"4" "User 4" "7"
"5" "User 5" "1"
and run an sql like this:
select userName from stack where id >= 0 order by score DESC LIMIT 3
That gives me the result
"userName"
"User 4"
"User 2"
"User 3"
Which means its arranged like this this;
"id" "UserName" "score"
"4" "User 4" "7"
"2" "User 2" "5"
"3" "User 3" "3"
"1" "User 1" "2"
"5" "User 5" "1"
How can I start at id 1 and get results as below. Because no matter what I do, I keep getting incorrect results:
Expected results:
select userName from stack where id >= 1 order by score DESC LIMIT 3
"1" "User 1" "2" /*These are my expected results and not what the above query outputs*/
"5" "User 5" "1"
This whole thing comes from a pagination system where we use to display users based on their scores.
You can use an offset in the LIMIT:
select userName from stack where id >= 1 order by score DESC LIMIT 3,3
For your pagination you have to increase your offset for every page.