Choose a pair of outcomes when utilizing Group By in a sqlite query

Let's dive into a complex scenario with an illustration:

Consider a sqlite table with various fields (id, language, title, etc.)

Each title can have multiple languages associated with it.

id --  language  --    title          --   publication  --  etc.
----------------------------------------------------------------------
1  --    Eng     --  Les misérables   --      1968      --  ...
2  --    Fr      --  Les misérables   --      1985      --  ...
3  --    Fr      --  Les misérables   --      2001      --  ...
4  --    Eng     --  Brave new world  --      1975      --  ...
5  --    Eng     --  Brave new world  --      1999      --  ...
6  --    Fr      --  Brave new world  --      1999      --  ...

The Challenge:

I want to retrieve the first English and French results in a single SELECT statement.

SELECT (id WHERE language='Eng') AS id1, (id WHERE language='Fr') AS id2 FROM myTable GROUP BY title

In this example, the query would output:

// The following is pseudo-JavaScript code with the SQL challenge
results.rows.item(1).id1 = 1
results.rows.item(1).id2 = 2

results.rows.item(2).id1 = 4
results.rows.item(2).id2 = 6

and so on...

Although the provided syntax is incorrect, can this be achieved through SQL?

Answer №1

Let's kick things off with an illustration of correct syntax:

SELECT title
FROM myTable
GROUP BY title

Here, you'll find all the rows from Table myTable organized by Title, for example:

| title | id      | language            | ...
| 'Foo' | [1,4,6] | ['en', 'ger', 'fr'] | ...
| 'Bar' | [2,5]   | ['en', 'it']        | ...
...

The values in [] represent the groups generated by GROUP BY.

If you're only interested in the ids, you can use the group_concat operation on the id column

SELECT title, group_concat(id)
FROM myTable
GROUP BY title

This will provide you with a comma-separated list of ids for each title (refer to ) Alternatively, you could

SELECT ... group_concat(language)
and then combine id and language on the client side if you require both sets of information.

Answer №2

Experiment with:

SELECT
     (SELECT id FROM myTable WHERE language='Eng') AS engId, 
     (SELECT id FROM myTable WHERE language='Fr') AS frId,
     title
     FROM myTable GROUP BY title

This can be done if the Subquery returns exactly 1 value; otherwise, it will result in an error.

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

MapBox notifies when all map tiles have finished loading

Currently, I am utilizing the Mapbox GL JS API to manipulate a Mapbox map. Prior to sending my result (which is a canvas.toDataURL) to the server via HTTP, I must resize my map to a larger resolution and then use fitbounds to return to the original points. ...

Rankings - Sorting MySQL Results by Each Player's Total

In my database table, I have the following columns: +----+--------+-----+------+-------+-------+-------+ | Id | Member | End | Done | Right | Wrong | Score | +----+--------+-----+------+-------+-------+-------+ Each member has multiple entries. I want t ...

Is there a way to prevent a bootstrap modal from opening?

Recently, I encountered an issue with a button on my webpage: <a data-toggle="modal" href="#influencerModal" class="btn btn-primary influencer-card">Influencer Profile</a> I wanted to prevent the modal from opening when the button was clicked ...

Utilizing a combination of count functions and various where conditions

I'm currently working on a SQL query to count the occurrences of Q1, Q2, Q3, and Q4 in the Quarter column. I've searched for solutions to similar questions, but they didn't provide enough clarity. Here's the code I have so far: SELECT ...

Node.js process.exec() function allows you to asynchronously spawn a subprocess

After writing the code, I ran it and found that the terminal was unresponsive with no output, causing the program to be stuck. var util=require('util') var exec=require('child_process').exec; exec('iostat 5',function(err,stdo ...

Is it possible to modify the color of a span element within a select dropdown?

Is there a way to change the color of a span to red within a select option in js fiddle? I am trying to modify the color of <span class="myError">This is a required field.</span> to red https://i.sstatic.net/nRF2c.png select{ color: green; ...

The callback function in WordPress is executed twice

I've been working on a custom WordPress plugin that includes a form for sending data to a database. However, I've encountered an issue where every time I click the submit button, the callback function runs twice, resulting in duplicate entries in ...

What is the best way to adjust the size of a div element so that it is

I am facing an issue with a table that contains a TreeView within a cell. The code snippet is shown below: <style> #leftPanel { width:60px; height:'100%'; border:1px solid red; ...

What methods can I use to generate unique paths within a URL for a website, and how can I assign a distinct status to each path?

I have developed a JavaScript program that allows you to draw using canvas. I have now set up a web server with Node.js in order to enable drawing on the website. Each specific drawing will be saved as a unique URL path so that you can resume where you lef ...

Please reset the form fields after the most recent edit

I've created a form that includes multiple select elements. When an option is selected, it activates the next select element and updates it with values using Ajax and PHP. However, I'm facing an issue where changing a previous option only resets ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Escaping a tight spot in JavaScript: tips and tricks

I'm facing a challenge with coding a callback registration for an array of buttons. I am struggling to figure out how to bind the necessary strings in the callback function. Any tips or suggestions would be greatly helpful! for (var i = 0; i < thi ...

An error occurred while attempting to retrieve data from a JSONArray

I have been working on creating a phonegap plugin for Android where I am returning a JSONArray using callBackContext.sendPluginResult(result);. Below is the code snippet demonstrating how I am constructing the JSONArray: private JSONArray makeJsonObject(S ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Accessing and playing audio files from Amazon S3 within Python code

I am attempting to directly read an audio file from S3 using Python. Initially, I record the audio with the following blob settings: blob = new Blob(audioChunks,{type: 'audio/wav'}); Then, I upload this file to S3 using Django: req=request.POST ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

A guide on resolving the TypeError 'download property of undefined' issue when using Puppeteer with browser.downloads.download

Using puppeteer, I am automating the login process to access my account on a content provider's site and download multiple zip files. After obtaining an array of links to download, I go through each link in a loop and utilize the browser.downloads.dow ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call. Take a look at the example code here. myObj = {}; var output = ...