I'm puzzled as to why I keep receiving unexpected months despite utilizing the BETWEEN method in my query

It just dawned on me that I mistakenly posted the wrong code for my question earlier

Despite setting the BETWEEN method in my statement, I am still getting random months when trying to run it in my nodejs with mysql2. Why is that happening?

SELECT
    u.department,
    YEAR(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y')) AS year,
    DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%b') AS month,
    COUNT(*) AS event_count
FROM
    userlibrary tlc
LEFT JOIN
    users u ON tlc.userfullname = u.fullname
WHERE
    u.type = 'STUDENTS'
    AND YEAR(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y')) BETWEEN ? AND ?
GROUP BY
    u.department,
    year,
    month
ORDER BY
    u.department,
    year,
    month;
    `;

const [results, fields] = await connection.query(sql, [
  type,
  `${startYear}-${from}`,
  `${endYear}-${end}`,
]);

*http://localhost:5000/api/result/table?from=01&startYear=2023&end=02&endYear=2023&type=students

This is my code.

To make the query call dynamic, I used the following configuration:

  • from: 01
  • end: 02
  • startYear: 2022
  • endYear: 2023

Upon running the code, I observed that the results I obtained include months that fall outside the specified dates, as illustrated in the server-side output below:

{
    "results": [
        {
            "department": "College 1",
            "year": 2023,
            "month: "Apr",
            "event_count: 25
        },
        {
            "department": 2023,
            "month: "Jan",
            "event_count: 19
        },
        ...
   ]

It is evident from the results that there are months other than Jan and Feb that have been included in the output.

Answer №1

The issue you're facing seems to be related to how you're filtering dates in your SQL query. It appears that the BETWEEN clause in your query is only filtering based on the year part of the dates, and not taking into account the months within those years. This means that while you're able to filter by year, the results are not accurately restricted by month. To filter by both year and month, you'll need to modify your query to include explicit month filtering. Since your date values are stored as strings in a specific format (%d/%m/%y), you'll need to convert these strings into dates that MySQL can interpret and then apply filtering based on both year and month.

SELECT
    u.department,
    YEAR(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y')) AS year,
    DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y'), '%b') AS month,
    COUNT(*) AS event_count
FROM
    userlibrary tlc
LEFT JOIN
    users u ON tlc.userfullname = u.fullname
WHERE
    u.type = 'STUDENTS'
    AND STR_TO_DATE(SUBSTRING_INDEX(tlc.time, ',', 1), '%d/%m/%y') 
    BETWEEN STR_TO_DATE(CONCAT(?,'/',?, '/', ?), '%d/%m/%Y') 
    AND STR_TO_DATE(CONCAT(?,'/',?, '/', ?), '%d/%m/%Y')
GROUP BY
    u.department,
    year,
    month
ORDER BY
    u.department,
    year,
    month;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Blend two columns within the 'middle' clause

Looking for a way to retrieve data from Dec 2014 - Feb 2015 with two columns in the between clause: between (month = 12 and year = 2014) and (month = 1 and year = 2015) My current table setup: I'm starting to think it might not be achievable. Are th ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

Comparing PHP and AJAX for Dynamic Select Loading

Currently, I am working on a form with numerous select fields that fetch data from different tables in MySQL. I am contemplating whether it would be better to load this data using PHP/MySQL when the page loads or to let the page render first and then use A ...

Can HTML text areas be designed to adjust their width automatically, as well as their height?

Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here: <textarea oninput="auto_grow(this)"></textarea> textarea { resize: none; overflow: hidden; min-heig ...

Top method for designing a user activity 'chronicle' in the database

I am currently in the process of developing a web-based social networking platform. Similar to Facebook, each user will have their own timeline where recent activities are displayed. These activities include status updates, posts on pages, adding new frien ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

Is there still a need to preload dynamic images in the background?

Imagine you have HTML code that includes an image with a placeholder: <img class="lazy-load" src="http://via.placeholder.com/150/?text=placeholder" data-src="http://via.placeholder.com/150/?text=real%20image"/> At some stage, you want to implem ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Issue with triggering the .click event

Just starting out with jQuery and Javascript, and I'm having trouble getting this to work smoothly without repeating myself. I have multiple div IDs on a page that I want to display or hide based on the step number in the sequence when a user clicks ...

Submitting a file using Ajax XMLHttpRequest

Currently, I am facing an issue while attempting to send a file using the following XMLHttpRequest code. var url= "http://localhost:80/...."; $(document).ready(function(){ document.getElementById('upload').addEventListener('cha ...

What is the process of transforming a basic JavaScript function into a TypeScript function?

As a Java developer diving into TypeScript for frontend development, I've encountered a simple JavaScript code snippet that I'd like to convert to TypeScript. The original JavaScript code is: let numbers = [123, 234, 345, 456, 567]; let names = ...

Error: Attempting to access 'forEach' property on an undefined variable at line 10 in the script file

I'm completely new to Javascript and I apologize for my messy code. I've been struggling with this error for a while now, both on Replit and Visual Studio, but I can't seem to figure it out. Any help would be greatly appreciated! Every time ...

Unlocking the invitable_friends permission dialog on Facebook API: A step-by-step guide

During the installation process of an app, users are given the choice to revoke the invitable_friends permission. If this happens, I would like to request the invitable_friends permission again. Some apps seem to be able to open a dialog requesting this pe ...

Unable to assign a value to a property within a JavaScript object

I'm attempting to configure settings for a JavaScript object (my assumption is that it's not a plain JS Object, but possibly an instance of a specific class, though I haven't been able to identify the class). https://i.sstatic.net/xsUiJ.png ...

How can I use Node.js Express to send a response in a file format like JavaScript or another type?

Currently, I have a piece of code that successfully reads the 'example.js' file and sends it to the client as requested. app.get('/mods/example.js', function(req, res) { fs.readFile('./mods/example.js', {encod ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...