SQL - Select data on a period with a default value - javascript

I want to select data from a table, get the result in JavaScript and print it in a graph (x = date, y = numbers)
I have the following DATA table (note: I tried to put it in markdown so it appears as an HTML table, but it doesn't seems to work):
| date | number |
|---------|--------|
| 2015-01 | 12 |
| 2015-02 | 7 |
| 2015-04 | 4 |
and the following SQL select:
SELECT date_format(date, '%Y-%m') AS date, number
FROM DATA
WHERE date >= '2015-01' AND date <= '2015-05'
GROUP BY date
ORDER BY date;
which gives me exactly the same table as output. However, what I'd want is a row per each months with 0 if the month is not recorded. For instance, March is not recorded in the database, so the result that I want:
| date | number |
|---------|--------|
| 2015-01 | 12 |
| 2015-02 | 7 |
| 2015-03 | 0 |
| 2015-04 | 4 |
| 2015-05 | 0 |
the table goes to May, because in the SELECT I want every months between January and May.
The question is: is there a way to do it in SQL, or do I have to post-process the results in JavaScript to add the empty months in my final table?
thanks for your help
edit: the begin and end dates are variable and can cover several years. So, I guess it is possible to do something with a special table containing the months but I have no idea how...
If the answer is to post-process, it's OK (disappointing but OK ^^)
edit2: the problem is "gap filling" as stated #mauro. It looks quite complex in MySQL, so I'm going to post-process my request.
see How to fill date gaps in MySQL?

I would create a second table DATA2 with one row per month and number=zero. Then, instead of selecting:
FROM DATA
I would select from:
FROM ( SELECT * FROM DATA UNION ALL SELECT * FROM DATA2 ) D
This way... if DATA contains values for a given month, you will get totals from DATA, if not... you will get zero from DATA2

Here is a sample with no temp table. it use the sequence ENGINE. The only difference is you must fill the start date an the count of month (seq_0_to_4).
SELECT `DATE`, SUM(number) as number
FROM (
SELECT
date_format( IF(d.`DATE` IS NULL, init.`DATE`, d.`DATE`) ,'%Y-%m') AS `DATE`
, IF(d.number IS NULL,0,d.number) as number
FROM (
SELECT '2015-01-01' + INTERVAL seq MONTH AS `DATE`, 0 AS number
FROM seq_0_to_4
) AS INIT
LEFT JOIN DATA d ON date_format(d.`DATE`,'%Y-%m') = date_format( init.`DATE` ,'%Y-%m')
) AS result
GROUP BY `DATE`
ORDER BY `DATE`;
Result
+---------+--------+
| DATE | number |
+---------+--------+
| 2015-01 | 7 |
| 2015-02 | 0 |
| 2015-03 | 7 |
| 2015-04 | 0 |
| 2015-05 | 0 |
+---------+--------+
5 rows in set (0.00 sec)
Table
MariaDB > select * from data;
+------------+--------+
| date | number |
+------------+--------+
| 2015-01-01 | 4 |
| 2015-01-02 | 3 |
| 2015-03-05 | 7 |
+------------+--------+
3 rows in set (0.00 sec)
MariaDB >

Related

Update multiple rows with different keys in MySQL

I have this table
inventory
id | name | location | quantity
1 | test | loc1 | 0
2 | test | loc2 | 0
3 | test2 | loc1 | 0
4 | test2 | loc2 | 0
I want to update
test loc 1 with quantity 50
and
test2 loc2 with quantity 100
how do I it?
I have tried using INSERT ON DUPLICATE KEY UPDATE but it doesn't work it just creates new rows
here's the guide I used ITS ON #3
I'm using javascript (nodejs)

MySQL select AND on multiple rows and multiple fields

I have a table:
+ --------------------------+---------------------------+--------------+--------+
| ID | SKU_ID | DKEY | DVAL |
+ --------------------------+---------------------------+--------------+--------+
| cjamtti7z00aivmv4ffc9ttuw | cjamtti7z00afvmv4ai5i0ffy | Part | A2030 |
| cjamtti7z00ajvmv4gztx7hq8 | cjamtti7z00afvmv4ai5i0ffy | Description | Single |
| cjamtti7z00akvmv4zvrvtazj | cjamtti7z00afvmv4ai5i0ffy | Length mm | 50 |
| cjamtti7z00alvmv4jxnryckh | cjamtti7z00afvmv4ai5i0ffy | Line Dia. mm | 6 - 10 |
+ --------------------------+---------------------------+--------------+--------+
I want to create a query that searches for SKUs that match a provided object:
{
'Fixing Hole Depth(mm)': '13 Min - 18 Max',
'Inside Dia. (mm)' : '11',
'Weight (g)' : '3'
}
I can't seem to find a way to combine AND and OR clauses that gives me the desired result.
To summarise, I need the SKU_IDs that match ALL the criteria in the object.
In basic SQL it can be achieved with GROUP BY + COUNT.
SELECT SKU_ID
FROM your_table
WHERE (DKEY = 'Fixing Hole Depth(mm)' AND DVAL = '13 Min - 18 Max,') OR
(DKEY = 'Inside Dia. (mm)' AND DVAL = '11,') OR
(DKEY = 'Weight (g)' AND DVAL = '3')
GROUP BY SKU_ID
HAVING count(*) = 3
It's required to have each SKU_ID + DKEY to be unique(otherwise you may have 3 values for DKEY = 'Weight(g)' for the same SKU_ID and query will not work as expected)
Maybe there is some less verbose way but it should be RDBMS-dependant
Your where clause can combine AND and OR easily, if you nest them correctly in brackets (). Try that.

JavaScript Locale Number Manipulation

On my site I have a table with numerous numbers, and I'm doing simple math on them to find the best method for the user. The table looks something like this:
US locale
+-------+-------+------------+---------+----------------------------------------+
| Gain | Price | Price/Gain | Amount | Outcome (round(Price * Amount)) |
+-------+-------+------------+---------+----------------------------------------+
| 15.75 | 47 | 2.98 | 827,583 | 38,896,401 |
| 52.5 | 240 | 4.57 | 248,275 | 59,586,000 |
| 297.5 | 4,106 | 13.80 | 43,814 | 179,900,284 |
+-------+-------+------------+---------+----------------------------------------+
Here's how the table SHOULD look with the de-DE locale (notice the switching of the . and , characters)
+-------+-------+------------+---------+----------------------------------------+
| Gain | Price | Price/Gain | Amount | Outcome (round(Price * Amount)) |
+-------+-------+------------+---------+----------------------------------------+
| 15,75 | 47 | 2,98 | 827.583 | 38.896.401 |
| 52,5 | 240 | 4,57 | 248.275 | 59.586.000 |
| 297,5 | 4.106 | 13,80 | 43.814 | 179.900.284 |
+-------+-------+------------+---------+----------------------------------------+
The way my code works, each column is populated separately. So first, the Gain column is populated for all rows, formatted, and using jQuery, I changed the value of row n to the Gain. Then Price is calculated, and again the values are populated.
The issue arises when Price/Gain is calculated. For the US locale, everything is fine. But with the de-DE locale, the table actually ends up looking like this:
+-------+-------+------------+---------+----------------------------------------+
| Gain | Price | Price/Gain | Amount | Outcome (round(Price * Amount)) |
+-------+-------+------------+---------+----------------------------------------+
| 15,75 | 47 | 0,03 | 827.583 | 38.896.401 |
| 52,5 | 240 | 0,46 | 248.275 | 59.586.000 |
| 297,5 | 4.106 | 0,00 | 43.814 | 179.900 |
+-------+-------+------------+---------+----------------------------------------+
When the Price/Gain is being calculated, the , and . are being ignored from the Gain and Price columns. As you can see in the third row,
4.106 / 2975 = 0.0014 (rounded to 0.00, or 0,00)
This is also causing an issue with the Outcome, as the Price, again, is being parsed literally, rather than converted from de-DE to US first. So in the third row, again, we can see
4.106 * 43814 (this is parsed correctly for some reason) = 179,900 or 179.900
Here's how my code is publishing these values and reading them in when needed:
// This code populates the Gain field
var gain = grabPresetGain(); // grabs a hardcoded value from a JSON object
gain = addCommasToNumber(new Intl.NumberFormat("de-DE", {}).format(gain .toFixed(2)));
row += "<div class='col-lg-1 col-md-1 col-sm-1 col-xs-1 row-gain text-center'>" + gain + "</div>";
// This code populates the price field
outcome = addCommasToNumber(new Intl.NumberFormat("de-DE", {}).format(outcome));
$(this).children(".row-price").text(outcome);
// And finally this code populates the Price/Gain field
// for loop going through each row of the table
var gain = convertToNumber($(this).children(".row-gain").text());
var price = convertToNumber($(this).children(".row-price").text());
var pricePerGain = (price / gain);
pricePerGain = addCommasToNumber(new Intl.NumberFormat("de-DE", {minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(pricePerGain .toFixed(2)));
$(this).children(".row-pricegain").text(pricePerGain );
And here's two of the helper functions being used:
function convertToNumber(x) {
if (typeof x == "string") {
x = x.replace(/\,/g,'');
}
return Number(x);
}
function addCommasToNumber(n) {
return n.toLocaleString();
}
All in all - is there a consistent way to parse, manipulate, and output numbers of different locales?
Any insight would be great as I'm pretty stuck as to what to do at the moment.
Thanks
Give formatJS a try. From the site:
FormatJS is a modular collection of JavaScript libraries for internationalization that are focused on formatting numbers, dates, and strings for displaying to people.
If you're just dealing with numbers, you might even be able to get away without using a library at all, and just directly accessing the window.Intl object.
See some examples here, on MDN.

Javascript add all values with similar fileld name

I have a table as below
------------------------------------
| Date | Price |
------------------------------------
| 09-13-2017 | $15.00 |
| 09-13-2017 | $6.00 |
| 09-15-2017 | $8.00 |
| 09-15-2017 | $14.50 |
|__________________________________|
I want to sum the total values of each Date so the output would be
Total value for 09-13-2017 is $21.00
Total value for 09-15-2017 is $22.50
How do i do this in JavaScript. Kindly guide.
var dat = jQuery("#date").map(function()
{
totpri = 0;
var pri = jQuery("#price").map(function()
{
var totpri = document.getElementByID("price").value();
totpri += totpri;
}
alert('The Total is: ' totpri)
}).get();
I can give you a technique you can use but not the code ( since I don't see your effort )
Step 1: create an empty associative array (say arrDates)
Step 2: Iterate through each row and check if the array contains a key with the keyname as 1st column(date)
If NOT => create a new entry in the format: {'date' => amount}
If YES => get the old amount for that date, and add the current amount to it, update the amount in the array
That's it
Now you can iterate this array and display the dates and amount sum in whatever format you want

Vertical grid/table layout Javascript

I need to display some JSON data vertically instead of horizontally:
Column1: Value1
Column2: Value2
and so on.
These values are coming from a database and I'll need the ability to scroll through the records being returned from the database.
This is for an MVC3 application using C#, and I'm open to whatever possible solutions are out there.
UPDATE:
While the below wasn't exactly what I needed, it put me on the right path to using a pivot table which I hadn't thought about previously.
If you want to use linq, You convert like this:
var pivotTable = from m in db.table
select new
{
Column1 = (from t1 in m
where t1.Field == "column1"
select t1.Value,
Column2 = (from t2 in m
where t2.Field == "column2"
select t2.Value
};
Json(pivotTable, JsonRequestBehavior.AllowGet)
First Look:
-----------------
Field | Value |
-----------------
column1 | 14 |
column2 | 34 |
column1 | 14 |
column2 | 36 |
column1 | 18 |
column2 | 34 |
After linq query
Column1 | Column2 |
-------------------
14 | 34 |
14 | 36 |
18 | 34 |

Categories