Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Say that I define:
```
USE tempdb;
GO
CREATE TABLE [dbo].[Test1]
(
[ID] [INT] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[DateString] [VARCHAR](max)
)
GO
INSERT INTO [dbo].[Test1](DateString) VALUES ('2014-10-20'),('BadDate');
GO
CREATE VIEW [dbo].[vw_Test1]
AS
SELECT
Id,
CONVERT(DATE,DateString)... | one way for these type of situations is using **CASE** statement, I think your view
with should work.
```
CREATE VIEW [dbo].[vw_Test1]
AS
SELECT
Id,
case ISDATE(DateString) when 1 then CONVERT(DATE,DateString) else 0 --oranything
end ConvertedDate
FROM dbo.Tes... | This depends on the version of SQL Server that you are using. SQL Server 2012+ has `try_convert()`:
```
CREATE VIEW [dbo].[vw_Test1] as
SELECT Id, TRY_CONVERT(DATE, DateString) as ConvertedDate
FROM dbo.Test1
WHERE isdate(DateString) = 1;
```
This will return `NULL` if the conversion fails, rather than an... | How to force "where" precedence when expanding views | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Can someone help me about this problem.
I have 2 tables:
```
TASKS:(id,once)
SAVED_tasks (id, task_id)
```
* table where i save tasks..
I need to show all tasks but NOT if the task have value is 1 and if is already inserted in SAVED\_tasks table..
EXAMPLE:
tasks:
```
id, name, once
1, task1, 0
2, task2, 1
3, tas... | Try this:
```
SELECT t.id, t.once
FROM TASKS t
LEFT JOIN SAVED_tasks st ON t.id = st.task_id
WHERE (t.once != 1 OR (t.once = 1 AND st.id IS NULL));
```
**OR**
```
SELECT t.id, t.once
FROM TASKS t
LEFT JOIN SAVED_tasks st ON t.id = st.task_id
WHERE NOT(t.once = 1 AND st.id IS NULL);
``` | ```
SELECT TASK.id, SAVED_tasks.task_id FROM TASKS Inner join SAVED_tasks ON TASK.id = SAVED_tasks.id
AND TASK.once > 1
``` | Select rows with show flag but based on another table | [
"",
"mysql",
"sql",
"select",
"join",
""
] |
I have a table like the one given below.
```
View : Cat : Name
abcView
abcView abcCategory2
abcView abcCategory2 abcFilter
abcView2
abcView2 abcCategory
abcView2
abcView3
```
View is the parent of Cat and Cat is the parent of Name. View can never be empty if Cat exists... | you could select all entries, where a name exists by
```
SELECT View, Cat, Name
FROM yourTable
WHERE Name NOT NULL
```
then union it with all entries, where just a cat exists (and no name)
```
SELECT View, Cat, Name
FROM yourTable
WHERE Name IS NOT NULL
UNION
SELECT View, Cat, NULL
FROM yourTable
WHERE Cat IS NOT NU... | Try this:
```
SELECT a.View, MAX(a.Cat) Cat, MAX(a.Name) AS `name`
FROM tableA a
GROUP BY a.View
``` | Problems while selecting data from the table? | [
"",
"mysql",
"sql",
"python-2.7",
"select",
"group-by",
""
] |
I'm trying to create a SQL statement, which calculates how many days a delivery of undelivered products are delayed relative to the current date. The result should show the order number, order date, product number and the number of delay days for the order lines where the number of days of delay exceeds 10 days.
Here ... | Add this to your where clause:
```
AND DATEDIFF(day, orderdatum, getdate()) > 10
``` | If the condition that you want is:
```
WHERE (getdate()-orderdatum) > 10
```
Simply rewrite this as:
```
WHERE orderdatum < getdate() - 10
```
Or:
```
WHERE orderdatum < dateadd(day, -10, getdate())
```
These are also "sargable" meaning than an index on `orderdatum` can be used for the query. | Trying to show datediff greater than ten days | [
"",
"sql",
"sql-server",
""
] |
Sorry if the title isn't really understandable, feel free to edit it.
I have a table named CLIENT, here is a sample of the data:
```
ID_CLIENT CLIENT_NAME OTHER_ID
----------------------------------------
1 'COMPANY A' 1
2 'COMPANY B' 4
3 'COMPANY C' 3
4 ... | **SELF JOIN** will resolve your issue.
Try this:
```
SELECT C1.ID_CLIENT, C1.CLIENT_NAME, C2.CLIENT_NAME CLIENT_BRANCH
FROM CLIENT C1
INNER JOIN CLIENT C2 ON C1.OTHER_ID = C2.ID_CLIENT;
```
**EDIT**
If you have `NULL` value in `OTHER_ID` column then use **LEFT JOIN** instead of **INNER JOIN**
```
SELECT C1.ID_CL... | Try this:
```
select a.client_id, a.client_name, b.client_name as client_branch
from client a join client b on (a.other_id = b.client_id)
```
(seems that I have been too late, sorry) | How to select rows based on join on two columns of same table | [
"",
"sql",
"oracle",
"select",
"join",
"self-join",
""
] |
Here is my problem:
My database have table Book, Post. Each book has many post
Table *posts* has field '*book\_id*', that is foreign key reference table Book primary key (id).
This is my index page. The idea is to get latest post from each book and order by published date.
When I code on localhost, every thing is O... | Try this:
```
SELECT b.*, p.*
FROM my_book_store.books AS b
INNER JOIN posts p ON b.id = p.book_id
INNER JOIN (SELECT p.book_id, MAX(p.published_date) published_date
FROM posts p
WHERE posts.published = 1 AND posts.published_date <= NOW()
GROUP BY p.book_id
) AS p1 ON... | You can try the below queries which does the job of getting the last post from each book
```
select
b.id,
b.name,
p.content,
p.published_date
from book b
join post p on p.book_id = b.id
left join post p1 on p1.book_id = p.book_id and p1.published_date > p.published_date
where p1.id is null;
```
OR
```
select
b.id,... | Different result query when use mysql and mariadb | [
"",
"mysql",
"sql",
"select",
"group-by",
"greatest-n-per-group",
""
] |
I am running a procedure where I use yesterday's date through `DATEADD(day,-1,getdate())`. The challenge is that my procedure runs at 1:30 at night, and it then returns the data like
```
2014-12-09 01 30
```
I need it to return something like `2014-12-09 23 59`, because i have a `DATETIME` column. Does anyone have a... | I had used something like below in an SP :
```
SELECT Cast(Getdate()-1 AS DATE)
+ Cast('23:59:00' AS DATETIME)
``` | Just for fun - but this would work, but only with a datetime datatype in SQL Server:
```
SELECT CAST((FLOOR(CAST(GETDATE() AS FLOAT))) -0.0006944444 AS DATETIME)
```
This gives you yesterday 23:59:00
In SQL Server the DATETIME datatype is internally handled like a float, so by casting it to float and flooring it, it... | getdate with time 2359 | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This is a bit of a weird question, but that's what the customer wants :)
They want to control what is selected via a control table. Reason for that is, that they don't know how the columns will be called in the end.
So when someone wants to run the code, they check how the columns are named and write it down in this ... | You can write a dynamic query as:
```
DECLARE @SQLString nvarchar(500);
select @SQLString = 'Select '+ CASE WHEN Level1 IS NULL THEN '' ELSE Level1 END +
+ CASE WHEN Level2 IS NULL THEN '' ELSE + ' , ' + Level2 END +
+ CASE WHEN Level3 IS NULL THEN '' ELSE + ' , '+ Level3 E... | Here is one solution. Select the values into a in-memory table and then select the columns. This isn't that flexible as it requires some manual rework as you progress.
```
DECLARE @TempTable TABLE
(
Column1 varchar(50),
Column2 varchar(50),
Column3 varchar(50),
Column4 varchar(50)
)
INSERT INTO @TempT... | Define a Select via a control table, SQL Server 2008 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
**Scenario:** I am trying to build a query that will return the SUM of a COUNT.
**Purpose of the Query:** I need to identify all of our Participants that are currently listed on 2 or more Positions.
**Current Query:**
```
select pa.firstname, pa.lastname, pos.name as "POSITION", count(pos.name) as "POSITION COUNT"
... | You would just use aggregation with a `having` clause:
```
select pa.firstname, pa.lastname, count(*) as "POSITION COUNT"
from cs_participant pa join
cs_position pos
on pa.payeeseq = pos.payeeseq
group by pa.firstname, pa.lastname
having count(*) >= 2;
```
I removed the `where` conditions, because it is not... | This query uses analytic functions to return the first name, last name, position and (total) position count for each participant. It uses row\_number to only print the first and last name once per participant (and leaves it blank for rows after the 1st row).
```
select
case when rn = 1 then firstname else '' end f... | How to return the SUM of a COUNT in PL/SQL | [
"",
"sql",
"oracle",
"plsql",
"oracle-sqldeveloper",
""
] |
I have this sample table:
Table1
```
Column1
-------
Hi&Hello
Hello & Hi
Snacks & Drinks
Hello World
```
**Question:** in SQL Server, how can I replace all the `&` into a character entities (`&`) without affecting the existing character entities?
Thanks! | 1. If you really want to replace it in your database, you can try running
```
UPDATE Table1 SET Column1 = REPLACE(Column1, '&', '&');
```
2. I suppose you want to do this because you want to display data on the site exactly the same way in your database. So I suggest you to escape when you display it (in the ... | I am assuming that the reason you are asking is because it's not just character entities you have - I'm assuming it's more than 5 or 6, because if it's that small a number, the easy answer is run an update statement for each character entity replacing the ampersand at the beginning of it with some combination of char... | SQL Server : replace "&" to character entities (&) | [
"",
"sql",
"sql-server",
"replace",
"character-entities",
""
] |
I am using the OR operator in the following fashion:
```
SELECT * FROM Customers
WHERE City = "Berlin" OR City = "London"
```
The above returns a results table containing some data, however what also returns data is:
```
SELECT * FROM Customers
Where City = "Berlin" OR "London"
```
I am using a questionable SQL edi... | Well, Cassini i have check your syntax and run this query on my table i did not getting same result. I am getting correct output as expected.
i have run this command:
```
SELECT * FROM `city` where name = 'London' or 'Berlin'
```
and i got only london in name column. When i run this command:
```
SELECT * FROM `city... | You are looking for
```
SELECT * FROM Customers Where City IN('Berlin', 'London');
```
The query:
```
Where City='Berlin' OR 'London'
```
Applies the [logical OR operator (||)](http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html#operator_or), so `OR "London"` is equivalent to `OR 0`, and `Where City = 'Be... | SQL Using the OR & AND operators (Newbie) | [
"",
"mysql",
"sql",
"operators",
""
] |
I've got an issue I've been racking my brain on this and the code I have makes sense to me but still doesn't work.
Here is the question:
> Give me a list of the names of all the unused (potential) caretakers and the names and types of all unclaimed pieces of art (art that does not yet have a caretaker).
Here is how ... | I would suggest two queries for the reasons I noted in my comment on the OP above... However, since you requested one query, the following should get you what you asked for, although the result sets are not depicted side-by-side.
```
SELECT
CareTakerName, ArtName, ArtType
FROM
CareTakers
LEFT JOIN
Dona... | `Donations.CareTakerID = ''` is not the same as testing for `NULL`. That's testing for an empty string.
You want
```
Donations.CareTakerID is NULL
```
Also note that
```
Donations.CaretakerID = NULL
```
will not give you what you want either (a common mistake.) | SELECT statement that only shows rows where there is a NULL in a specific column | [
"",
"sql",
"sql-server",
""
] |
Why doesn't this work? (**NOW SOLVED**)
```
Declare @var1 Varchar(10)
Set @var1 = 'Value 1'
Declare @var2 Int
Set @var2 = (Select [IntValue]
From [TableOfValues]
Where [StringValue] = @var1
)
Select @var1, [IntValue]
From [TableOfValues]
```
But this does...
```
Declare @var1... | By default if you don't mention size of `varchar` in declaration then it will be `1` So in `@var1` only `'V'` will be stored obviously you won't get the desired result. Try changing your **declaration** like this.
```
Declare @var1 Varchar(10)
Set @var1 = 'Value 1'
``` | Your declaration is not doing what you expect for `@var1`. Here is the problem:
```
Declare @var1 Varchar
Set @var1 = 'Value 1'
```
It is setting `@var1` to `V`. The default length for `varchar` with no length is "1" in this context. In SQL Server, *always* use a length with `varchar`:
```
Declare @var1 Varchar(255)... | How to use a variable within a Set @var = Select statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to select the ID from a wp\_posts table where I need to do 3 conditions.
1. Is the *ID* matching with the *post\_id* from the *wp\_postmeta* table where the *meta\_key* = 'gtp\_analytics\_client\_id' and the *meta\_value* is not empty.
2. Is the *ID* matching with the *post\_id* from the *wp\_postmeta* tab... | The `and` is not part of the `in` operator, it is three separate `in` operators, so you need the first operand (`ID`) for all of them:
```
SELECT ID
FROM wp_posts
WHERE ID IN ( ... )
AND ID IN ( ... )
AND ID IN ( ... )
```
You could also write that as three joins:
```
SELECT
p.ID
FROM
wp_posts p
INNER JOIN ... | **When it can be either of the 3 cases**
```
SELECT ID
FROM wp_posts
WHERE ID IN (SELECT post_id
FROM wp_postmeta
WHERE (meta_key = 'gtp_analytics_client_id' AND meta_value != '')
OR (meta_key = 'gtp_conversion_uploaded' AND meta_value != 1)
OR (meta_key = 'gtp_r... | SQL Multiple WHERE IN | [
"",
"mysql",
"sql",
"database",
"wordpress",
"phpmyadmin",
""
] |
I would like to get the first null-valued column **name** when selecting by Id:
I tried:
```
SELECT Snap1,Snap2,Snap3,Snap4
where NULL
FROM tbtProgressSnap
where Id=3
Id | Snap1 | Snap2 | Snap3 | Snap4|
-----------------------------------
1 | | |/a.png |/b.png|
-----------------------------------
2 | d... | Try this:
```
SELECT WorkId,
(CASE WHEN Snap1 IS NULL OR snap1 = '' THEN 'Snap1'
WHEN Snap2 IS NULL OR snap2 = '' THEN 'Snap2'
WHEN Snap3 IS NULL OR snap3 = '' THEN 'Snap3'
WHEN Snap4 IS NULL OR snap4 = '' THEN 'Snap4'
WHEN Snap5 IS NULL OR snap5 = '' THEN 'Snap5'... | You need a case with a group by over min():
```
SELECT
min(id) id,
CASE
WHEN Snap1 IS NULL THEN 'Snap1'
WHEN Snap2 IS NULL THEN 'Snap2'
WHEN Snap3 IS NULL THEN 'Snap3'
WHEN Snap4 IS NULL THEN 'Snap4'
END snap
FROM tbtProgressSnap
WHERE Snap1 IS NULL OR Snap2 IS NULL OR Sna... | Select the first column name where a value is null by Id | [
"",
"mysql",
"sql",
"sql-server-2008",
"select",
""
] |
This i my procedure,that determines classId and liveareaId for Animal to insert it into table
```
CREATE PROCEDURE insertAnimal
@name nvarchar,
@birthyear int,
@classname nvarchar,
@livearea nvarchar
AS
BEGIN
DECLARE @classid int
DECLARE @liveareaid int
SET @classid =
(SELECT Id
FROM dbo.Class
WHERE dbo.Class.N... | This is because you have declared `@classname` as only `nvarchar` and have not specified a length. When length is not specified in a `nvarchar` variable declaration statement, the default length is 1.
Declare as:
```
CREATE PROCEDURE insertAnimal
@name nvarchar(10),
@birthyear int,
@classname nvarchar(10),
@livearea ... | ```
CREATE PROCEDURE insertAnimal
@name nvarchar,
@birthyear int,
@classname nvarchar,
@livearea nvarchar
AS
BEGIN
DECLARE @classid int
DECLARE @liveareaid int
SET @classid =
(SELECT Id
FROM dbo.Class
WHERE dbo.Class.Name=@classname
AND dbo.Class.Id IS NOT NULL)
SET @liveareaid =
(SELECT Id
FROM dbo.LiveArea
WHE... | SQL Assign value to local variable take from table | [
"",
"sql",
"select",
"declare",
""
] |
I have to remove all whitespaces in String `'5 000 000,5' to '5000000,5'`.
I tried 3 below but it did not work
```
select replace('5 000 000,5',' ','') from dual;
select regexp_replace('5 000 000,5', '[[:space:]]*','') from dual;
select regexp_replace('5 000 000,5', ' ','') from dual;
```
Or anyone know how to conv... | 1. Using **`REGEXP_REPLACE` and `SPACE` class**.
`Select regexp_replace('your_value', '[[:space:]]+', '') from dual:`
2. Using **`REPLACE`**
`Select REPLACE('your_value', chr(32), '') from dual:` | You can try this and remove any non-numeric chars like comma (`,`)
```
SELECT to_number(regexp_replace('5 000 000,5', '[^0-9]', '')) FROM dual;
``` | Remove all whitespaces in string | [
"",
"sql",
"oracle",
"removing-whitespace",
""
] |
I have a program say
```
DECLARE
str VARCHAR2(20);
BEGIN
str:='Test';
DBMS_OUTPUT.PUT_LINE(// Here I want to print a character of any index from string//);
END;
/
```
How to do it? | You'd use the [SUBSTR function](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions169.htm#SQLRF06114). For example:
```
DECLARE
str VARCHAR2(20);
BEGIN
str:='Test';
FOR i IN 1..LENGTH(str) LOOP
DBMS_OUTPUT.PUT_LINE('Character at index ' || i || ' is ' || SUBSTR(str, i, 1));
END LOOP;
END;
```... | If you are looking to find a particular character and its index within a string, also look at the Oracle function INSTR().
INSTR( string, substring [, start\_position [, nth\_appearance ] ] )
HTH | How to access an index of a string in PL/SQL? | [
"",
"sql",
"string",
"oracle",
"plsql",
""
] |
I am trying to create a select count statement where the where statement is different for each row.
For example i got the following table called dbo.job:
```
User: Job:
Mark Garbageman
Dirk Garbageman
Henk Garbageman
Steven Garbageman
Mark Delivery
Dirk Delivery
Henk Delivery
Steven De... | You can use Case When with Count.
<http://peoplesoft.wikidot.com/conditional-counting-in-sql>
MSDN reference -><http://msdn.microsoft.com/en-us/library/ms175997.aspx>
```
select
count(case when Job = 'Garbageman' then 1 end) as GarbageCount,
count(case when Job = 'Delivery' then 1 end) as DeliveryCount
from... | You can achieve this using conditional `sum()`
```
select
sum(Job = 'Garbageman') as GarbageCount,
sum(Job = 'Delivery') as DelivryCount
from job
``` | Sql Select statement with different where statements | [
"",
"sql",
""
] |
I'm getting following output from a query shown in figure 01. Every employee has two records showing their work locations together with effective dates. Current flag shows the current record denoted by 'Y'.
Now I want to convert this output to the following format shown in figure 02. Here an employee has a single row. ... | Try this:
```
--PREVIOUSRESULT will be your existing result.
SELECT A.EMPLOYEENO, A.NAME, A.CURRENTFLAG,
(SELECT B.LOCATION FROM PREVIOUSRESULT B
WHERE B.EMPLOYEENO = A.EMPLOYEENO AND B.CURRENTFLAG IS NULL) AS FROMVALUE,
A.Location AS ToValue, A.TRANSFERDATE AS EFFECTIVEDATE
FROM PREVIOUSRESULT A
WHE... | Just one more answer:
```
select a.empno, a.ename, a.cflag,
(select b.location from empdetails b where b.empno=a.empno and b.cflag is null) "From",
a.location "To", a.transfer_date from empdetails a where a.cflag is not null;
```
Check this [sqlfiddle](http://www.sqlfiddle.com/#!4/6ffc4/4) | Combining two rows to a single row | [
"",
"sql",
"database",
"plsql",
"oracle-sqldeveloper",
""
] |
I've a database of musical tracks, and I'm trying to find which genre has the most tracks. Genre is stored in a Work table, with each track in the Track table having a field for which Work it belongs to.
This query correctly returns the genres and how many tracks they each have:
```
SELECT w.genre
, COUNT(t.name... | Try this:
**MySQL**
```
SELECT w.genre, COUNT(t.name) AS numTracks
FROM work w
LEFT JOIN Track t ON t.workName = w.name
GROUP BY w.genre
ORDER BY COUNT(t.name) DESC
LIMIT 1
```
**SQL SERVER**
```
SELECT TOP 1 w.genre, COUNT(t.name) AS numTracks
FROM work w
LEFT JOIN Track t ON t.workName = w.name
GROUP BY w.ge... | ```
select * from (SELECT Work.genre, count(Track.name) as numTracks FROM Track LEFT JOIN Work ON Track.workName=Work.name LEFT JOIN AlbumContains ON Track.workName=AlbumContains.workName GROUP BY Work.genre)alias order by aias. numTracks desc limit 1
``` | Find the Maximum from a Count in SQL | [
"",
"sql",
"sql-server",
"select",
"count",
"group-by",
""
] |
I have compiled the following as an example of what i have done so far and would like to know how i should continue:
```
CREATE TABLE tblMembers
(
Member_ID int,
Name varchar(255)
);
CREATE TABLE tblHorses
(
Horse_ID int,
Name varchar(255),
Age int(10),
Member_ID int(10)
);
```
So i would like to specify both Member... | Is this what you ware asking?
```
CREATE TABLE tblMembers (
Member_ID int identity(1, 1) not null primary key
Name varchar(255)
);
CREATE TABLE tblHorses (
Horse_ID int identity(1, 1) not nullprimary key
Name varchar(255),
Age int,
Member_ID int references tblMembers(member_id)
);
```
Storing... | Use this. **[Fiddler Demo](http://sqlfiddle.com/#!6/c56d1)**
Refer this for creating [Primary Key](http://msdn.microsoft.com/en-IN/library/ms189039.aspx),[Foreign Key](http://msdn.microsoft.com/en-IN/library/ms189049.aspx), [Identity](http://msdn.microsoft.com/en-us/library/ms186775.aspx) .
```
CREATE TABLE tblMember... | Adding Primary keys and a Relationship to tables | [
"",
"sql",
"sql-server",
""
] |
I have a column with values like `AAA-BBB-CCC` or `AAA-BBB-CCC-DDD`.
I am only interested in splitting and retrieving `AAA BBB CCC`.
I've tried using `PARSENAME`, however that messes up. | [SQL Fiddle](http://sqlfiddle.com/#!3/7554ea/5)
**MS SQL Server 2008 Schema Setup**:
```
CREATE TABLE Table1
([value] varchar(50))
;
INSERT INTO Table1
([value])
VALUES
('AAA-BBB-CCC'),
('AAA-BBB-CCC-DDD'),
('AAAAA-BBBB-CCCC'),
('AAAAA-BBBB-CCCCCC-DDD'),
('AAAAAA-BBB-CCC'),
('AAAAAAAA... | One solution would be using replace function like so:
```
select replace(columnName, '-', ' ') as SplittedVal
```
If only AAA BBB CCC is needed and the values are formated like 3 characters space 3 characters space 3 characters (so 11 characters in total) then use:
```
select left(replace(columnName, '-', ' '), 11)
... | Split a column using delimiter | [
"",
"sql",
"sql-server",
""
] |
Im trying to list each BookId with all its authors on the same line using listagg.
I would like it to look like this;
```
BOOKID AUNAMES
1101: Dilbert Emerson Sartre.
```
But when I execute the command the output is poorly formatted
```
select BOOKID,
listagg (AUNAME,',') WITHIN GROUP (ORDER BY auname)
AUNAMES
FRO... | Nothing stops you to make your query a sub-query and select again:
```
SELECT BOOKID || ':' || AUNAMES FROM
(
select BOOKID,
listagg (AUNAME,' ') WITHIN GROUP (ORDER BY auname)
AUNAMES
FROM BOOK_AUTHOR
group by bookid
) A
```
If you want to use a space as a delimiter use it in the listagg function | It sounds like you just want to concatenate the two columns.
One way is to use `||`:
```
select BOOKID || ': ' || listagg (AUNAME,',') WITHIN GROUP (ORDER BY auname)
FROM BOOK_AUTHOR
group by bookid;
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!4/23522/1) | listagg output formatting | [
"",
"sql",
"oracle",
"sqlplus",
""
] |
```
SELECT
*
FROM tbl_Something
WHERE
RoleID = 1 AND
GroupID =
CASE
WHEN @GroupID = 1 THEN @GroupID OR GroupID IS NULL -- issue here
WHEN @GroupID = 2 THEN @GroupID
```
What I want to do is
when @GroupID = 2 then GroupID = @GroupID meaning get all the rows with groupID = 2
when @GroupID ==... | You need to split up the condition, because `OR GroupID IS NULL` cannot be part of an expression that selects a `GroupID` for comparison. Since you have only two possibilities for `@GroupID`, it would be cleaner to rewrite your query without `CASE` altogether:
```
SELECT
*
FROM tbl_Something
WHERE
RoleID = 1 AN... | You can use `ISNULL` for this.
It will test if `GroupId` is equal to `@GroupId`, if `GroupId` is null it will check if 1 is equal to `@GroupID`
```
ISNULL(GroupID,2) = @GroupID
``` | SQL where clause case | [
"",
"sql",
"sql-server",
""
] |
I have the following db diagram :
[](https://i.stack.imgur.com/OoEmh.png)
I want to find the decade (for example 1990 to 2000) that has the most number of movies.
Actually it only deals with "Movies" table.
Any idea on how to do that? | You can use the LEFT function in SQL Server to get the decade from the year. The decade is the first 3 digits of the year. You can group by the decade and then count the number of movies. If you sort, or order, the results by the number of movies - the decade with the largest number of movies will be at the top. For ex... | An alternative to the string approach is to use integer division to get the decade:
```
SELECT [Year]/10*10 as [Decade]
, COUNT(*) as [CountMovies]
FROM Movies
GROUP BY [Year]/10*10
ORDER BY [CountMovies] DESC
```
This returns all, ordered by the decade(s) with the most movies. You could add a TOP (1) to only ge... | Finding the decade with largest records, SQL Server | [
"",
"sql",
"sql-server",
""
] |
I need to create a list of GUID's in SQL Server 2008 R2 and I am using the `NEWID()` function.
This is what I am trying but I just get only one ID:
```
SELECT TOP 100 NEWID()
```
I am new to SQL Server and I don't know if there is a way to do that or a way to create a loop for do it.
I don't need to persist those G... | You can use an arbitrary table as "sequence-generator":
```
SELECT TOP (100) Guid = NEWID()
FROM [master]..spt_values;
```
`Demo`
Note that this table contains only 2346 rows.
Worth reading: [Generate a set or sequence without loops](http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1) | Just use a loop. Try the following:
```
create table #GUIDS (tempID uniqueidentifier)
declare @i int = 0
while (@i < 100)
begin
insert into #GUIDS
select newid()
set @i = @i + 1
end
select * from #GUIDS
drop table #GUIDS
```
**NOTE:** This is not a good solution to use for a large number of iterations, as... | There is a way to generate a list of GUID's using NEWID function? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
Basically this is what I have :
```
insert into A values(1689, 1709);
insert into A values(1709, 1689);
insert into A values(1782, 1709);
insert into A values(1911, 1247);
insert into A values(1247, 1468);
insert into A values(1641, 1468);
insert into A values(1316, 1304);
insert into A values(1501, 1934);
insert into... | Assuming I'm understanding your question, one option is to use `NOT EXISTS`:
```
select col2
from A A1
where not exists (
select 1
from A A2
where A1.col2 = A2.col1
)
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/22b11/1)
This will return all `col2` records that do no exist in `col1`. | ```
SELECT COL1, COL2 FROM A WHERE
COL1 NOT IN (SELECT DISTINCT COL2 FROM A)
``` | Checking If data from A column exists in B column | [
"",
"sql",
"sql-server",
"join",
"exists",
""
] |
Is it possible to limit the number of elements in the following `string_agg` function?
```
string_agg(distinct(tag),', ')
``` | I am not aware that you can limit it in the `string_agg()` function. You can limit it in other ways:
```
select postid, string_agg(distinct(tag), ', ')
from table t
group by postid
```
Then you can do:
```
select postid, string_agg(distinct (case when seqnum <= 10 then tag end), ', ')
from (select t.*, dense_rank() ... | There are two more ways.
1. make an array from rows, limit it, and then concatenate into string:
```
SELECT array_to_string((array_agg(DISTINCT tag))[1:3], ', ') FROM tbl
```
("array[1:3]" means: take items from 1 to 3 from array)
2. concatenate rows into string without limit, then use "substring" to trim ... | PostgreSQL - string_agg with limited number of elements | [
"",
"sql",
"postgresql",
"aggregate-functions",
""
] |
I tried like this
```
SELECT DATENAME(DW,GETDATE()) + ' ' + CONVERT(VARCHAR(12), SYSDATETIME(), 107)
```
result is
```
Thursday Dec 11, 2014
```
**Required OutPut:**
SELECT QUERY TO DISPLAY DATE AS SHOWN BELOW
```
Thu Dec 11, 2014
``` | ```
SELECT LEFT(DATENAME(DW,GETDATE()),3) + ' ' + CONVERT(VARCHAR(12), SYSDATETIME(), 107)
FROM yourtable
``` | All you need is to take only left 3 symbols of your day of the week name:
```
SELECT LEFT(DATENAME(DW,GETDATE()),3) + ' ' + CONVERT(VARCHAR(12), SYSDATETIME(), 107)
``` | select query to display Date format as DAY MMM DD YYYY in SQL server 2008 | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"sql-server-2005",
""
] |
[fiddle.](http://sqlfiddle.com/#!4/ea88e/4)
```
TABLE1
PROP1 PROP2 NUM
a a 1
a a 2
a a 3
a b 1
a b 2
a b 3
TABLE2
PROP1 PROP2 NUM
a a 1
a a 2
```
I want to query the missing NUM values in `TABLE2` with regards to ... | This will do what you want, but I don't know if it will be more efficient:
```
SELECT *
FROM TABLE1 T1 JOIN
(SELECT DISTINCT PROP1, PROP2
FROM TABLE2
) TT2
ON T1.PROP1 = TT2.PROP1 AND t1.PROP2 = TT2.PROP2 LEFT JOIN
TABLE2 T2
ON T1.PROP1 = T2.PROP1 AND T1.PROP2 = T2.PROP2 AND T1.NUM = T2.... | That's how I would have done it
```
with table1 as
(select 'a' prop1, 'a' prop2, 1 num from dual
union all
select 'a' , 'a' , 2 from dual
union all
select 'a' , 'a' , 3 from dual
union all
select 'a' , 'b' , 1 from dual
union all
select 'a' , 'b' , 2 from dual
union all
select 'a' , 'b' , 3 from dual),
table2 as(
... | Left join and excluding non-existent rows on certain matchups | [
"",
"sql",
"oracle",
"join",
""
] |
I have a select statement and returns one column but many rows. I want to convert that to a single string with commas like below.
```
SELECT CODE FROM LG_xxx_CLCARD WHERE CODE < 'KUR' AND CODE > 'CARI1'
```
this returns
```
ASD1
ASD2
ASD3
```
I want to convert this to
```
'ASD1','ASD2','ASD3'
```
How can I d... | Use the STUFF function:
```
SELECT STUFF(
(SELECT ',' + CODE
FROM LG_xxx_CLCARD
WHERE CODE < 'KUR' AND CODE > 'CARI1'
ORDER BY CODE
FOR XML PATH ('')), 1, 1, '')
```
If you need the single quotes, then the following will do the trick:
```
SELECT STUFF(
(SELECT ',' + '''' + CODE + ''''... | Try this:
```
SELECT LISTAGG(CODE , ',') WITHIN GROUP (ORDER BY CODE ) FROM LG_xxx_CLCARD WHERE CODE < 'KUR' AND CODE > 'CARI1'
```
The result should be
'ASD1','ASD2','ASD3', .. | how to convert rows values to a single string | [
"",
"sql",
"sql-server",
"select",
""
] |
basically i have a table1 table and tabl2 table.
relation one to many
So i'm trying to make a select like
```
$em->createQueryBuilder()
->select('t1')
->from('AcmeAppBundle:Table1', 't1')
->orderBy('t1.id', 'DESC')
->getQuery()->getResult();
```
so i need the same que... | ```
$qb = $em->createQueryBuilder();
$qb
->select('t1')
->from('AcmeAppBundle:Table1', 't1')
->leftJoin('BLABLABundle:BlaEntity', 't2', 'WITH', 't1.id = t2.table1_id')
->orderBy('t1.id', 'DESC')
->groupBy('t2.table1_id');
$result = $qb->getQuery()->getResult();
``` | This would order the result by number of records from table2:
```
$queryBuilder = $entityManager->createQueryBuilder()
->select('t1, COUNT(t2.id) AS myCount')
->from('AcmeAppBundle:Table1', 't1')
->leftJoin('t1.fields', 't2') //fields is the one to many field name for the target... | symfony 2 and doctrine, selecting rows table by number of joned records from another table | [
"",
"sql",
"symfony",
"orm",
"doctrine-orm",
""
] |
I have a query:
```
select 'False' as COL_1, coalesce(sum(volume),0) as COL_2
from table1
where eligible like 'False%' and Month = :month
```
Basically I am creating the first column to read False and what results are found and my problem is that if my col\_2 returns null then it still shows the col\_1 false in the ... | ```
SELECT CASE WHEN (coalesce(sum(volume),0)) IS NULL
THEN NULL
ELSE 'False'
END AS COL_1,
coalesce(sum(volume),0) AS COL_2
FROM table1
WHERE eligible LIKE 'False%' AND Month = :month
``` | ```
SELECT IF(SUM(volume) = 0, NULL, 'False') AS COL_1, SUM(volume) AS COL_2 ...
``` | Sql if one column returns null, the whole resultset is null | [
"",
"mysql",
"sql",
""
] |
I'm fairly new to MySQL and was having some difficulty understanding why the following query is working as it does:
```
select user, COUNT(*) c FROM user_rows GROUP BY user HAVING c > 1 ORDER BY c;
```
Now, the output is correct: it lists a user along with how many rows they have in the user\_rows table.
My question... | Because if you have a `group by` clause then all aggregate functions like `count` or `sum` are applied to each group and not the complete data in the table.
Since you group by the `user`, the count is calculated for each user. | The reason it doesn't count all rows in the table is because you are grouping by user | Assistance In Query Logic and Order of Operations | [
"",
"mysql",
"sql",
""
] |
I currently have the following SQL query to pull all duplicate values:
```
Select `Racetime`,`Trainer`
from tom_cards
where `Trainer` in (
select `Trainer`
FROM tom_cards
GROUP BY `Racetime`,`Trainer`
HAVING COUNT(*) > 1
)
```
I want to have something more like
```
Select `Racetime`,`Trainer`
from tom_cards
... | you can concatenate
```
Select Racetime,Trainer from tom_cards
where concat(Racetime,Trainer) in
(select concat(Racetime,Trainer) FROM tom_cards
GROUP BY Racetime,Trainer
HAVING COUNT(*) > 1)
``` | Sometimes I handle these situations by doing a group by clause in a sub query and then selecting the rows I want from that.
```
SELECT Racetime, Trainer FROM (
SELECT Racetime, Trainer, COUNT(*) as occurrences
FROM tom_cards
GROUP BY 1,2
) Racetime_Trainer_counts
WHERE occurrences > 1
``` | Selecting duplicate values from mysql and displaying all of them | [
"",
"mysql",
"sql",
""
] |
I have a sql join where I'm trying to get 3 values from another table at the same time. Below is the data: (SiteID which is Site, HomeId which is home, VisitorId which is Visitor). I have tried
```
Select GameDate
From Games
INNER JOIN Schools ON Schools.SchoolId = Games.SiteId
Where Games.GameId = '1'`
```
But it... | You'll need to join to the same table multiple times and use table aliases:
```
SELECT Games.GameDate AS Date,
SiteSchool.SchoolName AS Site,
HomeSchool.SchoolName AS Home,
VisitorSchool.SchoolName AS Visitor
FROM Games
INNER JOIN Schools SiteSchool
ON SiteSchool.SchoolId = Games.SiteId
INNER JOIN Sch... | You need to join the `Schools` table three times, one for each key:
```
Select g.GameDate , s.SchoolName as Site, h.SchoolName as home, v.SchoolName as visitor
From Games g INNER JOIN
Schools s
ON s.SchoolId = g.SiteId INNER JOIN
Schools h
on h.SchoolId = g.HomeId INNER JOIN
Schools v
on ... | SQL get 3 different values from separate table | [
"",
"sql",
"sql-server-2014",
""
] |
I have 4 tables **`tbl_user`, `tbl_usedetails`,`tbl_aboutme`,`tbl_looking`** contains details of different users. These four tables have a field named **userid** in common. I want to join these four tables with the **userid**.
Consider my user id as 3
**`tbl_user`** is the root table where the `userid` is always pres... | The question is not 100% clear and unambiguous but I think you want to pick up values from other tables where present. If rows are not present for a user in three of the tables, you still want results from other tables. That's a `LEFT JOIN`, as follows:
```
SELECT *
FROM `tbl_user` AS u
LEFT JOIN `tbl_usedetails` ... | try outer join so that you get the data even though there is no data in secondary table.
```
select *
from `tbl_user` as u,
left outer join tbl_usedetails ud on u.userid=ud.userid
left outer join tbl_aboutme a on a.userid=u.userid
left outer join tbl_looking l on l.userid=u.userid
where
u.userid='3'
``` | Error in Join query in mysql | [
"",
"mysql",
"sql",
"join",
""
] |
I'm trying to do a conditional `AND` within a SQL `WHERE` clause.
A pseudo code example is below.
```
SELECT
*
FROM [Table]
WHERE
[A] = [B]
AND
IF EXISTS
(
SELECT TOP 1 1
FROM [Table2]
WHERE
1 = 1
)
BEGIN
--Do conditional filter
(T... | This should cater for the chance of the conditional filter and without
```
AND
(
NOT EXISTS
(
SELECT TOP 1 1
FROM [Table2]
WHERE
1 = 1
)
OR
(
EXISTS
(
SELECT TOP 1 1
FROM [Table2]
WHERE
1 = 1
... | In a WHERE clause there is not only AND. You can also use OR, NOT and parentheses. Thus you can express any combination of conditions. In your example you don't want to select any data when there is a table2 entry but no matching table3 entry.
```
select *
from table1 t1
where a = b
and not
(
exists (select * from ... | SQL conditional 'WHERE' clause | [
"",
"sql",
"sql-server-2014-express",
""
] |
My first question here. This has been a really helpful platform so far. I am some what a newbie in sql. But I have a freelance project in hand which I should release this month.(reporting application with no database writes)
To the point now: I have been provided with data (excel sheets with rows spanning up to 135000... | Thanks a lot to @kbbucks.
Works with this so far.
```
SELECT T1.MonitorDateTime, T1.loc2, T.loc4
FROM Table1 T1
LEFT JOIN Table2 T2 ON T2.MonitorDateTime = T1.MonitorDateTime
WHERE T1.MonitorDateTime BETWEEN '04/05/2011 15:10:00' AND '04/05/2011 16:00:00'
UNION ALL
SELECT T2.MonitorDateTime, '', T2.loc4
FROM Tab... | Based on your comment:
> For a given date time there can be even empty values for fields in table 2
my understanding would be that you are not interested in orphaned records in table 2 (based on date) so in that case a LEFT JOIN would do it:
```
SELECT table1.t1DateTime, table1.tiID, table1.loc2, table2.t2id, table2... | sql query to Combine different fields from 2 different tables with no relations except a common field - SQL Server Compact 3.5 SP2 | [
"",
"sql",
"join",
"database-design",
"sql-server-ce",
"union",
""
] |
I have a DATETIME Column in a table and I need to show the date in the
following format "DD/MM/YYYY H:MM AM/PM"
```
CreatedBy
2013-07-30 12:44:06.000
2013-07-30 12:45:57.000
2013-08-05 16:51:26.000
2013-08-05 19:08:18.000
2013-08-05 19:11:46.000
2013-09-12 12:44:27.000
```
I need the date like this--> `"30/07/2013 12... | Use this in SQL:
```
print convert(nvarchar(10), getdate(), 103) + right(convert(nvarchar(30), getdate(), 0), 8)
``` | ```
declare @Date datetime = '2013-07-30 12:44:06.000',
@Time time = '12:44:06.000',
@VarcharDate varchar(100),
@VarcharTime varchar(100)
set @VarcharDate= CONVERT(varchar,@Date,111) -- get the date in the format you want
set @VarcharTime = CONVERT(varchar,@Date) -- get the time in format you want
print @Varc... | How to display Date in DD/MM/YYYY H:MM AM/PM format in SQL Server | [
"",
"sql",
"sql-server",
"datetime",
""
] |
Here's my schema:
```
CREATE TABLE T (A CHAR(1), B CHAR(1));
INSERT INTO T (A, B) VALUES('1', '1');
INSERT INTO T (A, B) VALUES('2', '2');
INSERT INTO T (A, B) VALUES('1', '2');
```
I wan't to select rows where columns A and B contain a combination of values. For example, lets say I want to find combinations A=1,B=1,... | You can check this query :
```
SELECT * FROM T WHERE (A,B) IN (('1', '1'),('2', '2'));
```
see given link below
Click [here](http://sqlfiddle.com/#!2/fc2535/11 "sql fiddle") | Is this what you're looking for using `OR` with parentheses?
```
select *
from T
where ( A = '1' AND B = '1' ) OR ( A = '2' AND B = '2' )
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!2/fc2535/1) | Select all rows where two columns contain a combination of values | [
"",
"sql",
""
] |
I have two tables that i need to consult with one query, i have the `Participante` table that will store some data from the user and the `ParticipanteResultado` that will store the answers of that user.
Table `Participante`
```
participanteID,
tipo,
**other fields**
```
The field `tipo` from `Participante` is used b... | Think of the data in terms of sets.
You need a set of data which is of all participants and all of their scores
and a set of the max quantidadeValidas by participant
So first get a list of the max quantidadeValidas for each participant
```
SELECT MAX(PR.quantidadeValidas), PR.participanteID
FROM ParticipanteResultad... | Since you only need the top result for each participant, I'd go with the rank function:
```
WITH cte
AS ( SELECT participanteID ,
nome ,
email ,
unidadeCE ,
telefone ,
tipo ,
... | SQL consult joining two tables, group and order by | [
"",
"sql",
"sql-server",
"entity-framework",
""
] |
I have 4 tables: booking, address, search\_address & search\_address\_log
**Tables: (relevant cols)**
booking: (pickup\_address\_id, dropoff\_address\_id)
address: (address\_id, postcode)
search\_address: (address\_id, postcode)
search\_address\_log: (id, from\_id, to\_id)
---
What I need to do is have a count f... | Technically, what you want is a `full outer join`, but MySQL doesn't support that. However, the following should do what you want -- getting summaries for each `from` and `to` value for the two columns:
```
SELECT b_from, b_to, sum(b_count) as b_count, sum(s_count) as s_count
FROM ((SELECT a1.postcode as b_From, a2.po... | Proposal: select on the addresses -- get counts of the to/from pairs, and then add them up by postcode
```
SELECT t.postcode, f.postcode, SUM(sal.count), SUM(b.count)
FROM search_address t, search_address f
LEFT JOIN ( SELECT from_id, to_id, COUNT(*) count
FROM search_address_log GROUP BY... | Complex Joins (Joining Joins) | [
"",
"mysql",
"sql",
"join",
"left-join",
"inner-join",
""
] |
I have the following schema:
```
|partner|
---------
id
|contract|
----------
id
partner_id
termination_date
|comtract_items|
---------------
id
contract_id
product_id
```
I want to select all partners which have a valid contract (`termination_date is NULL`) and
with no contracts with the `product_id`'s 392 an... | It's now clear that `"and with no contracts with the product_id's 392 and 393"` is supposed to rule out partners that have ***any*** contract with any of those blacklisted `product_id`s:
```
SELECT * -- unclear which columns you want
FROM partner p
WHERE EXISTS (
SELECT 1
FROM contract_contract c
WHERE ... | I think you were very close, but forgot some parentheses:
```
WHERE (c.termination_date is NULL or c.termination_date > '2014-12-11') and ...
```
Here's how I would do this::
```
SELECT DISTINCT c.partner_id
FROM Contract c
WHERE (c.TerminationDate IS NOT NULL OR c.TerminationDate > CURRENT_DATE)
AND NOT EXISTS (SEL... | Query over three tables | [
"",
"jquery",
"sql",
"database",
"postgresql",
""
] |
I have a problem to write a query. Please help me I am not a database specialist.
## My Goal is:
Select last modified date for some set of observed fields for each unique object of type ProjectA. I have available only AuditLog table which is audit trail table and contains all modifications made on all objects (the ol... | ```
select max(created_date), object_class, object_id
from AuditLog
where object_class = 'ProjectA'
and created_date >= sysdate-30 ---- This is just so we have more results
and field in ('text3', 'listValue5', 'largeText6', 'largeText7', 'largeText8', 'listValue9')
group by object_id, object_class... | So, in order by grab the latest date for an object\_id, it's a fairly straightforward query:
```
select object_id, max(created_date)
from auditlog
group by object_id;
```
And you get
```
object_id max(created_date)
---------- -------------------
1000 2014-12-12 10:45:49
12000 2014-12-09 20:44:27
100... | How to select last modified date for set of observed fields for each unique objects of some type? | [
"",
"sql",
"database",
"oracle",
""
] |
I have a many to many relationship between `stories` and `tags`, the table created to hold the relationship is `taxonomies`. I want to search all the stories that have all the given tags.
The query I'm using so far is this one, of course it doesn't work for me, it returns all stories that contain **any** of the given ... | I think you want this query
```
SELECT stories.id FROM `stories`
JOIN `taxonomies` ON `stories`.id = `taxonomies`.`story_id`
JOIN `tags` ON `tags`.id = `taxonomies`.tag_id
GROUP BY stories.id
HAVING SUM(`tags`.name = 'tag 1')>0
AND SUM(`tags`.name = 'tag 2')>0
``` | Do you know the number of tags you are checking? If so, could you use a [HAVING](http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html) to confirm that the number of matches for `stories.id` matches the total number of tags? Something like this:
```
SELECT stories.id, COUNT(stories.id)
FROM `stories`
JOIN `t... | Searching by tag, inclusive | [
"",
"mysql",
"sql",
""
] |
I am looking for a solution to (something I imagine to be) a common and trivial problem, but I couldn't find the correct words to find solutions on Google.
# Starting situation
I have a table `orders` that is associated to a `product` and a `customer`:
`orders (id, product_id, customer_id)`
# The problem
Each orde... | Your `Payment` table should have all fields that are common to all payments (amount, type of payment, etc) as well as a unique ID.
Variable fields would then be stored in a second table with three columns:
* Payment UID (foreign key to the Payment table)
* Type (what kind of data this current row is storing, i.e. the... | If you're never going to be using those fields' contents in a where or join clause (which it usually is):
1. Add a payment method field (an enum or varchar)
2. Serialize the paypal, stripe, or whatever the client used as json
3. Store the thing using the most appropriate database type -- text in MySQL, json in Postgre... | Database design: Associating tables of variable types | [
"",
"mysql",
"sql",
"database",
"postgresql",
"rdbms",
""
] |
I have two tables: users and photos.
Users have many photos. Photos have a column called user\_id, photos have one user. Photos also have a column called reported which is 0 or 1.
I need to know the number of users who have at least 1 photo with reported = 1. I also need to get the number of users who have at least 2... | Just get a histogram of the counts:
```
select numreported, count(*), min(user_id), max(user_id)
from (select p.user_id, sum(p.reported = 1) as numreported
from photos p
group by p.user_id
) p
group by numreported
order by numreported;
```
This gives you the number of users that have all counts of `n... | This is at least 1
```
select count(distinct userid)
from photos
where reported = 1
```
This is at least 2.
```
select count(distinct userid)
from photos
where reported = 1
group by userid
having count(userid) > 2
``` | Comparing counts in a SQL where clause | [
"",
"mysql",
"sql",
""
] |
Is there a command in PostgreSQL to select active connections to a given database?
`psql` states that I can't drop one of my databases because there are **active connections to it**, so I would like to see what the connections are (and from which machines) | Oh, I just found that command on PostgreSQL forum:
```
SELECT * FROM pg_stat_activity;
``` | Following will give you active connections/ queries in postgres DB-
```
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
```
You may use 'idle' instead of active... | How to list active connections on PostgreSQL? | [
"",
"sql",
"postgresql",
"database-connection",
"listings",
""
] |
I want to update the table called "user\_star\_rate" if the row is exists, otherwise insert data into table. It works well, but it is creating a duplicate row when updating. I want to prevent this problem.
Here is my SQL code.
```
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value)
VALUES ('... | `ON DUPLICATE KEY UPDATE` query works when inserted date have any unique key, for example you are inserting values `(email, product_id, rate_value)` so there `(email, product_id)` should combination unique so first add `unique` key of both fields and then try `ON DUPLICATE KEY UPDATE`
Add Unique key, if you have not a... | My suggestion would be INSERT.. ON DUPLICATION KEY UPDATE
Refer this [link](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html) for details | How to do update if exist without creating a duplicate row in SQL? | [
"",
"mysql",
"sql",
""
] |
I am trying to figure out the best way to join 3 table with unique IDs where 2 of the tables need to be the 'Left' Tables compared to the 3rd table. The 3rd table would provide all the nulls that I need for my analysis.
For example:
table 1 = table\_r, table 2 = table\_n, table 3 = table\_t
```
unique_r unique_n ... | Based on your example query, you want the results to contain all the columns from all three tables. Furthermore `table_r` and `table_n` seem to be unrelated, but I suppose you don't want a cross product of their rows. This is a rather strange scenario, but you should be able to achieve it like this:
```
SELECT *
FROM
... | If you have the same fields in table\_r and table\_n, you can do a UNION with \*, otherwise, specify the fields you want to select, e.g an unique\_n IS NOT NULL as match
```
select * from table_r left join table_t
on unique_r = unique_t
Union
select * from table_n left join table_t
on unique_n = unique_t
``` | How to do a Oracle SQL Left Outer Join on 3 tables with two left tables? | [
"",
"sql",
"oracle",
""
] |
Course (one table) and module (another table). Modules can be part of different courses. Joined in this table called coursemodule
```
CourseCode ModuleID
BS BS2029
CN CN5485
CS CN5485
BS CS1004
CN CS1004
CS CS1004
CS CS2017
BS CS2026
CS ... | You can try this query - it's easy to read and uderstand:
```
SELECT m.ModuleID, m.ModuleDescription
FROM Module as m
WHERE m.ModuleID in
((SELECT ModuleID FROM CourseModule WHERE CourseCode = 'CN'
INTERSECT
SELECT ModuleID FROM CourseModule WHERE CourseCode = 'CB')
EXCEPT
SELECT ModuleID FROM CourseModule WHERE Cour... | I'd probably go with something a little different - since you want two "in" and one "not in", I'd write it that way, which would make it clear what you're doing:
```
SELECT m.ModuleID, m.ModuleDescription
FROM Module as m
WHERE m.ModuleID in (SELECT ModuleID FROM CourseModule WHERE CourseCode = 'CS')
AND m.ModuleID in... | Excluding results | [
"",
"sql",
"sql-server",
""
] |

Considering the diagram above I am trying to select bulletins along with related info.
1. A bulletin can have only one associated user (the creator)
2. A bulletin can have only one state (the creator's home state)
3. A bulletin can have only one bulletin type (E.G. An... | Without the counts then those left joins don't even need to be performed and the query optimizer probably figures it out.
And you don't even user Events with the count - drop it
Make sure you have indexes on all those join conditions (BullitinID) and they are not fragmented.
When these two queries run fast your quer... | The first thing I'd try to check performance of much simpler query that touches tables that have the most effect (you mentioned BulletinLikes and BulletinComments are the biggest offenders of performance) :
```
SELECT TOP 10 b.id, COUNT(bl.Id) AS likes, COUNT(bc.Id) AS Comments
FROM Bulletins b
LEFT JOIN BulletinLik... | Counting Related Records : Query Taking Over 2 Minutes To Run | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to get a count of the field WOID for a specific date the trouble is that the date field [opendate] is a date time field so I decide to use cast to change [opendate] to a date field
```
SELECT distinct
cast([OPENDATE] as date) as [Opened Date]
,count([WOID]) as ID
FROM [Tasks]
Group by [OPENDATE]
```
... | You are grouping by something different than what you are selecting, change to:
```
SELECT cast([OPENDATE] as date) as [Opened Date]
,count([WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)
```
You may be after a count of distinct `WOID` per date, in which case you'd use:
```
SELECT cast([OPENDATE] ... | Give:
```
SELECT distinct
cast([OPENDATE] as date) as [Opened Date]
,count([WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)
```
a shot - you want to group it on the `date`, not the `datetime` - mimicking your selected column | Stumped on Group By | [
"",
"sql",
"sql-server",
""
] |
If I have table with a two columns:
* date (timestamp)
* milliseconds (int)
How could I write a query that would return the two columns and a third column that represents a sum of the first two as a timestamp.
Like this:
```
date | milliseconds | sum
------------------... | I think you answer is as follows:
```
# select date, milliseconds, date+milliseconds*interval '1 milliseconds' as sum from temp;
date | milliseconds | sum
----------------------------+--------------+----------------------------
2014-12-10 17:43:47.554989 | 11882 | 2014-12-... | Simply add it as an interval:
```
select stamp + (ms / 1000) * '1 second'::interval
``` | PostgreSQL get column with date + interval | [
"",
"sql",
"postgresql",
""
] |
I have three tables in MS Access as follow:
```
--Students(ID, Name, Class)
--Subjects (ID, Name)
--Marks (ID, StudentID, Subject.ID)
```
Relation is as follow:
```
Marks.Subject = Subjects.ID
Marks.StudentID = Students.ID
```
Please Help me write a query that can return Name of Students and All SubjectNames and Ma... | You have joined `students` and `marks` table with that Join `Subjects` table too
```
SELECT students.NAME,
marks.obtained,
subjects.NAME
FROM ( marks
INNER JOIN students
ON marks.studentname = students.id )
INNER JOIN subjects
ON marks.subject = subjects... | try this:
```
select Students.Name, Marks.Obtained, Subjects.Name from Marks
inner join Students on Marks.Subject = Subjects.ID
Marks.StudentID = Students.ID
``` | SQL Join operation in multiple tables | [
"",
"sql",
"ms-access",
""
] |
I tried to select a random data from table employees with query `rand()` but it can happen
```
SELECT email FROM employees
ORDER BY RAND()
LIMIT 1;
```
and the output is:
> ORA-00933: SQL command not properly ended
> 00933. 00000 - "SQL command not properly ended"
Can somebody tell me why?? | The Oracle equivalent of `rand()` is `dbms_random.value`.
The Oracle equivalent of `limit` is either a subquery with `rownum` or (in Oracle 12) `fetch first xx row only`. So, one of these should work:
```
select email
from employees
order by dbms_random.value
fetch first 1 row only;
```
or:
```
select email
from (s... | To speed-up operations on large table, you might use the `SAMPLE` clause to randomly extract a sample of data from your table, and then randomly pick one data from that sample:
```
select email from
( SELECT email,ROWNUM rn
FROM employees SAMPLE(5)
-- ^
-- each row has 5% chance of being... | Oracle rand() function | [
"",
"sql",
"oracle",
"random",
""
] |
This runs in 2 minutes:
```
SELECT
G.GKey,
Amount = SUM(fct.AmountEUR)
FROM
WH.dbo.vw_Fact fct
INNER JOIN #g G ON
fct.DateKey >= G.Livedate AND
fct.GKey = G.GKey
GROUP BY G.GKey;
```
This runs in 8 mins:
```
SELECT
G.GKey,
C.Amount
FROM
#g G
CROSS ... | Here's the logical difference between the two joins:
`CROSS APPLY`: yields the Cartesian cross product of an aggregation on a given value of `LiveDate` and `GKey`, this gets re-executed for every row.
`INNER JOIN`: yields a 1-to-1 match on vw\_Fact for every value of `LiveDate` and `GKey`, then sum accross common val... | I think you trying to get `Rolling sum`. use [**Over() clause**](http://msdn.microsoft.com/en-IN/library/ms189461.aspx) Try this.
```
SELECT G.GKey,
Amount = Sum(fct.AmountEUR)
OVER(
partition BY G.GKey
ORDER BY id rows UNBOUNDED PRECEDING)
FROM WH.dbo... | Why would CROSS APPLY not be equivalent to INNER JOIN | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Is it possible to create a SQL query returning a row which has any column matching input. For example:
```
SELECT row WHERE ANY column LIKE input
```
Thank you | Yes it is:
```
SELECT * FROM MyTable WHERE ColumnA LIKE '%input%' OR ColumnB LIKE '%input%'
```
---
If you want literally to dynamically check *any* column then you need to dynamically build up the list of columns and use a [prepared statement](http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.ht... | I think you are searching for this...
```
SELECT * from table WHERE column a LIKE '%input%' or column b LIKE '%input%'
``` | Return row where any column matches input | [
"",
"mysql",
"sql",
"database",
""
] |
When running a SQL command to search a small database (using for testing as I'm learning) it gives me very strange results. Can you see what's wrong with my command?
```
SELECT * FROM users,departments WHERE name LIKE '%Alex%' OR lastname LIKE '%Alex%' OR email LIKE '%Alex%' AND departments.departmentid = users.depart... | Try this:
```
SELECT * FROM users,departments WHERE (name LIKE '%Alex%' OR lastname LIKE '%Alex%' OR email LIKE '%Alex%') AND departments.departmentid = users.departmentid
```
You have to make brackets arround the `or` statements. | First, use explicit `join` conditions with an `on` clause. If you are learning SQL, you should learn it right.
```
SELECT *
FROM users JOIN
departments
ON departments.departmentid = users.departmentid
WHERE name LIKE '%Alex%' OR lastname LIKE '%Alex%' OR email LIKE '%Alex%';
```
That will fix your problem, ... | mySQL search function returning invalid results | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
Hi i am new to android programming, i have make an Http post request to get json data from an external sql database and displayed my result in a lisView. i want to be able to retrieve the string value from a clicked item in the listView. Please any help with this will be much appreciated | I would try something like this, which has worked for me in the past:
```
String itemValue = (String) listView.getItemAtPosition(position);
```
This is from within the `listView.setOnItemClickListener(new OnItemClickListener()` portion of your code.
If your strings are aggregated into one string, then try this:
... | Set OnItemClickListener on listview. See on below.
```
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String itemString=listView.getSelectedItem().toString()... | get string value from item clicked in a listView | [
"",
"android",
"mysql",
"sql",
"listview",
"onitemclick",
""
] |
I want to sort a table in descending order based on the maximum value of id for each name but each set of rows by name itself should be sorted in ascending order.
I have sorted my table descending on id.
```
id | name | other cloumns
----|------|---------------
11 | yv |
10 | abc |
9 | abc |
8 | zx |
7 ... | You want:
```
order by name desc, id asc
```
You can put multiple keys into the `order by`. The first key is used for the sorting. When the key values are the same, the second gets used, and so on.
EDIT:
I see, you want the names with the smallest id first. For this, use a `join`:
```
select t.*
from table t join
... | you can combine **Order by** with **Union** like this:
```
select * from (select * from table1 order by id where name='yv')
union all
select * from (select * from table1 order by id where name='abc')
union all
select * from (select * from table1 order by id where name='zx')
union all
select * from (select * from... | Order and reverse order by group? | [
"",
"mysql",
"sql",
""
] |
I've been able to get the query result I need using the following raw sql:
```
select `person`.`id`, `full_name`, count(actions.user_id) as total
from `persons`
left join `actions`
on `actions`.`person_id` = `persons`.`id`
and `actions`.`user_id` = $user
where `type` = 'mp'
group by `persons`.`id`
```
But I haven't... | So, for reference, I solved it like so:
```
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', '=', 'persons.id')
->where('actions.user_id', '=', "$user");
})
->groupBy('persons.id')
->where('type', 'foo')
->ge... | I found that the `where` doesn't always work on the `leftJoin` clause
If in the future you get any trouble with it, I'd suggest you using this:
```
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', '=', 'persons.id')
->on('actions.user_id', '=', "$... | mysql join ON and AND to laravel eloquent | [
"",
"mysql",
"sql",
"laravel",
"laravel-4",
"eloquent",
""
] |
I want to create a view of my database. \in fact, my database contains around 20 tables and i want to join the tables based on the foreign keys but there are some duplicates columns. Is there an easy and fast way to do it ? | Here's something that might help. You'll have to list out the columns if you do not want the dupes. You can run
**[SQL Fiddle Example](http://sqlfiddle.com/#!2/7913a/15)**
```
select group_concat(concat(table_name,'.', column_name) separator ', ')
from information_schema.columns
where table_name in ('Students', 'Cla... | You Should Use Alias in joining like this...
```
Select E.Name , U.Name,E.Age,U.Age
From
TblEmployee E
inner join
TblUser U on E.EmployeeId = U.EmployeeId
```
**Note : The above Query is only a Example So that you can go ahead**
**Edit:** you can also do your column name what you want like this
``... | Join many tables sql | [
"",
"mysql",
"sql",
"join",
""
] |
what i need is to run a sql query something like :
```
select * from table where alpahbetcolumn="A" and numbercolumn="10" and shelfcolumn="upper";
```
i want to know how to do this query in hibernate using `EntityManager`
currently this is my own try out, but not working....
```
@PersistenceContext
EntityManage... | i have worked out using criteriaquery to fullfill my needs, here is the code. it works
```
@Transactional
public List<Item> listItems(String alpahbet, String number, String shelf) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.creat... | Try this
```
Query q = em.createNativeQuery("select * from table where alpahbetcolumn='A' and numbercolumn= 10 and shelfcolumn='upper'");
q.getResultList();
```
`createNativeQuery()` accepts plain SQL as parameter. If you expect `Item` as result, you can use this
```
em.createNativeQuery("select * from table where a... | spring mvc hiberate, use CriteriaQuery to run select * from table where | [
"",
"sql",
"hibernate",
"spring-mvc",
"criteria",
"hibernate-criteria",
""
] |
Our application has a table called cargo\_items. It can be seen as kind of a queue to later process these items. Initially there was a SINGLE job which took 3000 entries and processed them one after another. Later on, somebody decided to start 3 other instances of the same job. What happened is quite obvious, many of t... | In the related answer you are referring to:
* [Postgres UPDATE ... LIMIT 1](https://dba.stackexchange.com/a/69497/3684)
The objective is to lock ***one*** row at a time. This works fine with or without advisory locks, because there is **no chance for a deadlock** - as long as you don't try to lock more rows in the sa... | You will have deadlocks with this approach. You could avoid them by simply using `order by id` in subquery.
But it will prevent any concurrent running of this queries, as concurrent queries will always try first to mark the lowest free id, and block until the first client will commit. I don't think this is a problem i... | How to mark certain nr of rows in table on concurrent access | [
"",
"sql",
"postgresql",
"locking",
"sql-update",
""
] |
I have 3 tables, this is Sql Fiddle Demo <http://www.sqlfiddle.com/#!15/89ac5/3/0>
```
create table entities (id int, credit int, debit int, value int,etype int, date date);
insert into entities values
(1,101,100,5000,1,'01/01/2014'),
(1,101,100,1000,2,'01/01/2014'),
(1,102,100,2000,1,'01/01/2014'),... | You can use conditional aggregation:
```
select row_number() over (order by creditname, debitname) as id, creditname, debitname,
sum(case when name = 'Medicine' then value end) as medicine,
sum(case when name = 'Diagnoise' then value end) as diagnoise,
date
from table t
group by creditname, debit... | You can do:
```
select distinct
e.id,
credit_account.name as CreditName,
debit_account.name as DebitName,
(select e1.value
from entities e1
where e1.etype = 1 //Medicine type
and e1.credit = e.credit) as Medicine,
(select e1.value
from entities e1
where e1.etype = 2 ... | Show same columns with different values in same row | [
"",
"sql",
"postgresql-9.3",
""
] |
I want to compare row count of two tables and then return `0` or `1` depending on whether its same or not.
I am thinking of something like this but can't move ahead and need some help.
```
SELECT
CASE WHEN (select count(*) from table1)=(select count(*) from table2)
THEN 1
ELSE 0
END AS Ro... | you have to remove :
```
FROM Table1,Table2
```
Otherwise it will consider the result of the Case-When for each row of this FROM clause. | Or Simply remove the CASE WHEN CLAUSE and write:
```
SELECT (SELECT count(*) from table1)=(SELECT count(*) from table2) AS RowCountResult;
```
as a boolean result will be returned. | Compare row count of two tables in a single query and return boolean | [
"",
"sql",
"database",
"sqlite",
""
] |
I have the following query
```
Select
Date, Item_Code,
SUM(In_Quantity) as In_Quantity,
SUM(Issue_Quantity) as Issue_Quantity,
(SUM(In_Quantity) - SUM(issue_Quantity)) as BalanceQty
from
(select
tbl_add_product.Date as Date, tbl_add_product.Item_Code,
tbl_add_product.In_Quantit... | Wrap it in another subquery and then use:
```
SELECT *, SUM(BalanceQty) OVER (PARTITION BY Item_Code ORDER BY [Date])
FROM ( ... ) o
``` | ```
--variant using LAG() OVER () function
SELECT [Date] ,
Item_Code ,
SUM(In_Quantity) AS In_Quantity ,
SUM(Issue_Quantity) AS Issue_Quantity ,
( SUM(In_Quantity) - SUM(issue_Quantity) )
+ COALESCE(LAG(SUM(In_Quantity) - SUM(issue_Quanti... | Getting grouped by record value in second row | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm still very new to SQL queries and can't quite figure this one out.
I have two tables, one table I'm running a general `SELECT ... WHERE`, super easy SQL statement.
Ex:
```
SELECT * from maindata where somedata4 LIKE "%data4.%"
```
This gives me back a list of all 6 entries below, however I want an additional co... | Here is the SQL Query I was looking for (I think):
```
SELECT m.*, IFNULL(u.amount,0) AS "Amount"
FROM maindata m
LEFT OUTER JOIN userdata u ON m.id = u.itemId AND userid = 1
WHERE m.somedata4 LIKE "%data4.%"
```
It's giving me the desired results listed above, I just don't know if it's the most efficient way of hand... | ```
SELECT m.*, IFNULL(u.amount,0) from maindata m LEFT OUTER JOIN
userdata u ON m.id = u.itemId WHERE m.userId = 1
``` | MySQL Join and Default | [
"",
"mysql",
"sql",
""
] |
In MySql I need to select top student in every class in a school in `termid=10` to get discount for next term enrollment .
Please notice that total is not in table(I put in below for clearing problem)
I have this workbook table for all students workbook:
```
id studentid classid exam1 exam2 total term... | Another approach is to join the table with itself. You find out the max for each class and then join all students of this class which match the class max:
max for each class (included in the final statement already):
```
SELECT classid, MAX(CAST(exam1 AS UNSIGNED) + CAST(exam2 AS UNSIGNED)) as 'maxtotal'
FR... | You can get the total for the students by just adding the values (MySQL will convert the values to numbers). The following gets the max total for each class:
```
select w.classid, max(coalesce(w.exam1, 0) + coalesce(w.exam2, 0)) as maxtotal
from workbook w
group by w.classid;
```
You can then `join` this back to the ... | Mysql best students in every class in a school | [
"",
"mysql",
"sql",
""
] |
I have to write the script that will pull IDs of all members that email has been hard bounced. In order to do it I wrote this
```
Select id FROM Members m
Join tbl_memberlanguageid mli on m.ID = mli.MLI_MemberID
Where Cast(dateCreated as date) >= '01-Dec-2014'
and mli.MLI_LanguageID = 3
and EmailHardBounces = 1... | Another way:
```
DELETE FROM Members WHERE ID IN(Select id FROM Members m
Join tbl_memberlanguageid mli on m.ID = mli.MLI_MemberID
Where Cast(dateCreated as date) >= '01-Dec-2014'
and mli.MLI_LanguageID = 3
and EmailHardBounces = 1)
``` | You can just change the `Select id` to `Delete m`:
```
BEGIN TRAN
DELETE m
FROM Members m
JOIN tbl_memberlanguageid mli ON m.ID = mli.MLI_MemberID
WHERE CAST(dateCreated AS DATE) >= '01-Dec-2014'
AND mli.MLI_LanguageID = 3
AND EmailHardBounces = 1
ROLLBACK
COMMIT
```
Just confirm the r... | How to remove data from table if the ID is in the column | [
"",
"sql",
"sql-server",
"remove-if",
""
] |
I am having three tables with different data and i need to insert into one TEMP table and return that table in StoredProcedure.
I tried as:
```
-- To get last 10 Days Letters count
SELECT col1,col2,1 AS Type, LettersCount
INTO #temp FROM tblData
-- To get last 4 weeks Letters count
SELECT col1,col2,2 AS Type, Letter... | You can Check it Already Exists or NOT
```
IF OBJECT_ID ('tempdb..#TempLetters') is not null
drop table #TempLetters
SELECT col1,col2,1 AS Type, LettersCount
INTO #TempLetters FROM tblData
-- To get last 4 weeks Letters count
INSERT INTO #TempLetters
SELECT col1,col2,2 AS Type, LettersCount
FROM tblData
-- To get ... | Create the temporary table once, then insert into it for the other two SELECT statements:
```
SELECT col1, col2, 1 AS Type, LettersCount
INTO #temp
FROM tblData;
INSERT INTO #temp
SELECT col1, col2, 2 AS Type, LettersCount
FROM tblData;
INSERT INTO #temp
SELECT col1, col2, 3 AS Type, LettersCount
... | How to insert multiple select statements into a temp table | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"select",
""
] |
I have two tables.
Table 1 contains orders and customer codes.
Table 2 contains orders with issue codes.
I need to be able to return distinct order count by customer from table 1 along with a distinct count by customer of orders with issuecode of 'F' from table 2. Then the final field will be a ratio of the two. Issu... | You can use an `outer join` to your issues table and `count` with `distinct`. Something like this depending on your table definitions:
```
select o.customercode,
count(distinct o.orderid),
count(distinct i.orderid),
count(distinct i.orderid)/count(distinct o.orderid) ratio
from table1 o
l... | I'm doing this w/ a few subqueries to make it more readable in terms of the description of the problem you presented. sgeddes' solution probably also works (and might perform better) depending on the precise structure of your data.
```
SELECT t.customer,
count(t.orderID_All),
count(t.orderID_F),
c... | SQL two tables distinct counts with join | [
"",
"sql",
"db2",
"ibm-midrange",
""
] |
```
SELECT * FROM Fruit
INNER JOIN Apple ON Fruit.Id = Apple.FruitId
WHERE Apple.Type = 1 AND Apple.Type = 3
```
I need to get unique rows of Fruit that have both Apples that are of type 1 AND 3. Apple.Type is considered unique, but I wouldn't think it matters though.
With these rows, this should return two rows with... | Group your apples table by fruit id and pick the results that have both desired types. Use this to get your fruits.
```
SELECT *
FROM Fruit
WHERE id IN
(
SELECT FruitId
FROM Apple
WHERE Type IN (1,3)
GROUP BY FruitId
HAVING COUNT(DISTINCT Type) = 2
);
``` | This would return the fruits with ID 50 and 52.
```
SELECT *
FROM Fruit
WHERE EXISTS (
SELECT 1 FROM Apple
WHERE Type = 1 AND Apple.FruitId = Fruit.Id
) AND EXISTS (
SELECT 1 FROM Apple
WHERE Type = 3 AND Apple.FruitId = Fruit.Id
)
``` | How to retrieve unique rows where multiple children that reference it exist for different types? | [
"",
"sql",
"sql-server",
"group-by",
"distinct",
""
] |
I would like get the ID from the query, but I am getting a NULL, where is my mistake?
```
DECLARE @TblZimz NVARCHAR(256)
DECLARE @IdModul INTEGER
DECLARE @Id INTEGER
SET @TblZimz = '_ZIMZ000001'
SET @IdModul = 1
--SET @Id = -1
EXECUTE [InsertZimz] @TblZimz, @IdModul, @Id OUT... | First, select the desired `id` in an output variable using `@Id = ([ID])` then assign this `@Id OUTPUT` value in the `@Id` variable using `@Id = @Id OUTPUT`. Also, you should pass data in where clause using a variable to avoid sql injection problem like `[ModulId] = @IdModul` (i.e. you should not concatenate it like `[... | Like [Deepak's](https://stackoverflow.com/a/27486184/1501497) answer, but easier:
> EXEC SP\_EXECUTESQL @SqlQuery,
> N'@Id INT OUTPUT, @IdModul INT',
> @IdModul OUTPUT, @Id | SP_EXECUTESQL and Output Parameter | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have this query that I have to manually change the date daily but not the time.
Below you can see that I have 2014-12-11 the next day I have to change the date ONLY to 2014-12-12. Any ideas how to make this dynamic ?
```
UPDATE tblData SET Issued = '2014-12-11 08:00:00.000'
where issued < '2014-12-11 08:00:00.000... | ```
DECLARE @Date DATE = '2014-12-11' --<-- Date variable
UPDATE tblData
SET Issued = CAST(@Date AS DATETIME) + CAST('08:00:00.000' AS DATETIME)
where issued < CAST(@Date AS DATETIME) + CAST('08:00:00.000' AS DATETIME)
and called > CAST(@Date AS DATETIME) + CAST('08:00:01.000' AS DATETIME)
and tbldate = @Da... | Can you just use the DATEADD function here?
Demo:
```
DECLARE @TestData TABLE (Issued DATETIME);
INSERT INTO @TestData VALUES(DATEADD(day, -1, GETDATE()));
SELECT * FROM @TestData;
UPDATE @TestData
SET Issued = DATEADD(day, 1, Issued);
SELECT * FROM @TestData;
``` | Make Date dynamic but keep Time static | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have a database that stores the log-in and log-out of the employees but we don't have work on weekends. My supervisor want the DTR report format(I'm using RDLC report) include the weekends. (*see attached image*)

The image above is the expected ou... | Use common table expression and generate date range with from and to date and than use CTE as left join to actual table. I haven't used user\_id filter in left join so apply it to your query:
```
DECLARE @TMEP TABLE
(
[Date] DATE,
[IN] VARCHAR(10),
[OUT] VARCHAR(10)
)
INSERT INTO ... | try below solution :
```
DECLARE @startdate DATE = '11/21/2014' -- your start date
DECLARE @enddate DATE = '12/09/2014' -- your start date
-- create list of all dates between min(log_date) and MAX(log_date)
;WITH cte
AS (SELECT @startdate AS log_date
UNION ALL
SELECT Dateadd(dd, 1, log_date) ... | include weekends on sql query | [
"",
"sql",
"sql-server-2008-r2",
"formatting",
"reporting",
"rdlc",
""
] |
please, i have a database, in this database i have a table (FICHENAME), this elements have several criteria (Ex : core competence and condition of access and ..) each element for the criteria is represented by a table in this database.
i need to create a combination between the same table to compare FICHENAME1 with (F... | A self join is simply when you join a table with itself.
<http://www.tutorialspoint.com/sql/sql-self-joins.htm>
[SQL join on multiple columns in same tables](https://stackoverflow.com/questions/16597660/sql-join-on-multiple-columns-in-same-tables)
[[What is SELF JOIN and when would you use it?](https://stackoverflow... | thank you for your answer, i can use Cross join to create a combination :D
<http://www.sqlguides.com/sql_cross_join.php> | SQL Query: combining data for the comparaison | [
"",
"sql",
"sql-server",
"database",
"ssis",
"sql-server-2012",
""
] |
How to get the Max and Min length allowed in column of `varchar2`.
I have to test for incoming data from the temp table which is coming from some remote db. And each row value is to be tested for specific columns that it has maximum or minimum value which can be set into the column.
So I was to get the column specs us... | You can query the table 'user\_tab\_columns table' to retrieve metadata information of a specific table:
```
SELECT
COLUMN_NAME, DATA_LENGTH, DATA_PRECISION
FROM
user_tab_columns
WHERE
t.table_name IN ('<YOURTABLE>');
```
with this information you can query the metadata directly in your stored procedure... | Try creating your procedure like this:
```
create or replace procedure Checking_size(column_name varchar2,columnvalue varchar2,state out varchar2) is
begin
execute immediate 'declare
z '||column_name||'%type;
begin
z:=:param2;
end;' using columnvalue;
state:='OK';
exception when value_error then
state:='NOT OK';
en... | Get Maximum Length allowed in column | Oracle | [
"",
"sql",
"oracle",
"maxlength",
""
] |
I have a column called "WasCancelled" in a MySQL DB, it's of a Boolean type.
I save the number 0,1 and 2 to it.
**I need a query that will count how many one's, two's and zeros are there.**
for example:
my column:
```
WasCanceled
-----------
0
0
1
1
1
2
0
0
0
2
0
0... | You can do this by grouping:
```
SELECT WasCancelled, COUNT(*)
FROM <Table>
GROUP BY WasCancelled
```
If you need more information, look here for details on [Group By](http://www.tutorialspoint.com/sql/sql-group-by.htm) and [Count](http://www.tutorialspoint.com/sql/sql-count-function.htm).
# Update
To include the q... | Use **GROUP BY** with **COUNT** fuction:
Try this:
```
SELECT WasCanceled, COUNT(1) as times
FROM tableA
GROUP BY WasCanceled;
``` | count column items in mysql | [
"",
"mysql",
"sql",
"select",
"count",
"group-by",
""
] |
Is there a way to do a partial string match on a string array column in postgres?
I'm trying the following syntax, but it is not working as I'd expect it to:
```
SELECT * FROM example_table WHERE '%partial string' ILIKE ANY(array_column)
```
Is there a correct way of doing this? | ```
drop table if exists temp_a;
create temp table temp_a as
(
select array['alpha','beta'] as strings
union all
select array['gamma','theta']
);
select *
from (select unnest(strings) as string from temp_a) as sq
where string ilike '%eta'
``` | You need to search each subscript separately -- here's an example that can be expounded on to include more columns
```
SELECT distinct array_column FROM
(SELECT array_column,
generate_subscripts(array_column, 1) AS s
FROM example_table) AS foo
WHERE array_column[s] like '%partial string';
```
Alt... | How to use LIKE with ANY in Postgresql? | [
"",
"sql",
"postgresql",
"postgresql-9.2",
""
] |
Hi friends I have table from customer where in I want to get distinct values of its three columns CustomerType, CustomerReg,CustomerID.
Instead of doing three separate queries for the distinct
like select distinct CustomerType From Customer.. and then for CustomerReg..Can it be achieved in one query...
The reason is... | You can do this with `grouping sets`. If you want the values in three separate columns:
```
select CustomerType, CustomerReg, CustomerId
from Customer
group by grouping sets ((CustomerType), (CustomerReg), (CustomerId))
``` | If I understand correctly, you want to show a distinct list of all the customer types, customerreg and customerIds in a list, in one column?
Try this...
```
select distinct CustomerType + ' : ' + CustomerReg + ' (' + CustomerId + ')' as Name
from Customer
```
This will return a string like 'External : 23423412 (2344... | How can I apply distinct on multiple columns | [
"",
"sql",
"sql-server",
"sql-server-2008",
"distinct",
""
] |
Please have a look at the below code.
```
SELECT Transactions.`idTransactions`,
Transactions.`Transaction_TimeStamp`,
Transactions.`idPortfolio`,
CASE when Transactions.`Transaction_Amount`< 0 THEN END AS "Encashments" ELSE END AS "Additions" ,
Portfolio.Activation
FROM Transactions
INNER JOIN Portfolio ON Transa... | If you want 2 different columns then use two cases
```
SELECT Transactions.`idTransactions`,
Transactions.`Transaction_TimeStamp`,
Transactions.`idPortfolio`,
CASE when Transactions.`Transaction_Amount` <= 0
THEN (Transaction_Amount*-1)
END AS Encashments,
CASE when Tra... | You have no result in your case.
```
CASE when Transactions.`Transaction_Amount`< 0 THEN something_missing_here END AS
``` | MySQL: Retrieving values into different columns | [
"",
"mysql",
"sql",
"database",
"select",
"case",
""
] |
In my `SELECT` query, I would like to put a condition in my `CASE` for a value called *IsActive* so that if the current row's column Type is *"adhoc"* then set the value of IsActive to "n/a".
```
SELECT CASE Type
WHEN 'scheduled' THEN 'Scheduled'
WHEN 'adhoc' THEN 'AdHoc'
ELSE 'Unkn... | Your second `case` is based on a single column, then you are trying to put a condition in the `when`, which is not allowed:
```
CASE IsActive
WHEN (Type) = 'adhoc' THEN 'n/a'
WHEN 0 THEN 'Stopped'
WHEN 1 THEN 'Active'
END AS 'Status'
```
I think you meant to do this (use a ... | Try this:
```
SELECT (CASE Type
WHEN 'scheduled' THEN 'Scheduled'
WHEN 'adhoc' THEN 'AdHoc'
ELSE 'Unknown'
END) AS 'Type',
(CASE
WHEN Type = 'adhoc' THEN 'n/a'
WHEN IsActive = 0 THEN 'Stopped'
WHEN IsActive = 1 THEN 'Active'
... | WHEN condition based on the current row value | [
"",
"sql",
"sql-server",
"database",
"select",
"case",
""
] |
I have done my research on this in Stack Overflow and am aware of offered solutions whereby the advice is that MSAccess reports override queries and the sort order is usually set in the report properties, or by VBA OnLoad, or something similar. I have noticed something weird in my MS Access reports however, and that is... | Problem solved!
I created a simple query to list all the "Enrolled" [Outcomes]:
```
SELECT Outcomes
FROM T_Enquiry
WHERE T_Enquiry.Outcomes="Enrolled";
```
and then inserted the following into the `Data` Property of the *Txt\_TotalEnrol* textbox in the report:
```
=DCount("Outcome","qry_TotalOutcomeEnrolled")
```
... | As @parakmiakos said, check first that there is no other constraint in the `OrderBy` property of the report that may be overriding your bound query.
If your report is shown in a form, also check that the form doesn't have its own `RowSource` and `OrderBy` properties set to something that would explain the behaviour.
... | SQL ORDER BY behaving strangely in MS Access 2010 report | [
"",
"sql",
"vba",
"ms-access",
"report",
"ms-access-2010",
""
] |
I have a view pulling together data from a number of tables. Let's consider it to be like this:
```
TransPK Amount Currency_ID
-------------------------------
1 2000 0
1 -2000 0
2 3600 1
2 -7200 2
. . .
```
I want to calculate sum(Amount), per distinct Tra... | Try this:
```
SELECT TransPK, SUM(Amount)
FROM tableA
GROUP BY TransPK
HAVING COUNT(DISTINCT Currency_ID) = 1;
```
Check the [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!3/f3c16/2)
**OUTPUT**
```
| TRANSPK | AMOUNT |
|---------|--------|
| 1 | 0 |
| 3 | 3000 |
``` | I guess this is what you are after:
```
SELECT TransPK, SUM(Amount) AS Amount, Currency_ID
FROM TableName
GROUP BY TransPK, Currency_ID
HAVING COUNT(Currency_ID) > 1
```
Result:
```
TRANSPK AMOUNT CURRENCY_ID
1 0 0
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/161d6/10). | SQL SUM restricted | [
"",
"sql",
"select",
"group-by",
"sum",
"aggregate-functions",
""
] |
I want to learn ASP.NET MVC5 so I decided to make somekind of review site. I want to add diffrent console / pc games and movies etc. For the Games table I have this:
```
CREATE TABLE [dbo].[Games] (
[GameId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NOT NULL,
[Genre] NVARCHAR ... | ```
AspNetUsers
------
Id (PK)
Game
------
Id (PK)
Review
------
Id (PK)
GameId (FK)
UserId (FK)
```
or make a composite key if a user can only review a game 1 time
```
Review
------
GameId (PK)
UserId (PK)
```
but if you want to have Movies and Games you could do
```
Review
------
Id (PK)
GameId (FK NULL)
MovieI... | Technically, you should actually have a separate join table with a foreign key to the movie and one to the user, since you're dealing with a M2M relationship here: users can review many movies and movies can be reviewed by many users. Likewise for games.
However, since you're starting off with MVC you're actually putt... | database structure - linking data | [
"",
"mysql",
"sql",
"asp.net-mvc-5",
""
] |
I'll try to be as clear as possible.
I have these 3 tables `Customer`, `Link` & `Customer_link`.
I am using the following query to retrieve the `customer_no` column from `Customer` which has values that are not available in the `customer_no` of the table `Customer_link`:
```
SELECT c.customer_no
FROM CUSTOMER c
LE... | I finally found a way to get this working with the use of a cursor. I will be putting up the solution here so that someone else may need help with this.
I created a variable `cust` that was of the type Customer.Customer\_no
`cust Customer.Customer_no%type;`
I then created a Cursor to be able to add the values of unu... | There is no need for a loop. Just use the select as a source for the insert:
```
insert into customer_link (customer_no)
select c.customer_no
from customer c
left Customer_link cl ON c.customer_no = cl.customer_no
where cl.customer_no is null;
```
Or alternatively use a NOT EXISTS query which is sometimes faster... | Retrieving the first value of the column to a variable in pl sql | [
"",
"sql",
"oracle",
"plsql",
"plsqldeveloper",
""
] |
I have 2 tables:
Downtime Categories:
`CatID ----- CatName ----- SiteID`
Downtimes:
`DtID ----- DtName ----- CatID`
How do I create a query so I can pull all of the records from Downtimes where the SiteID from Downtime Categories = x?
I don't know how to word this search to get what I need, I have tried all the Joi... | You can try this
```
SELECT D.CatID ,D.CatName ,D.SiteID
FROM Downtimes D INNER JOIN DowntimesCategories DC
ON D.CatID = DC.CatID
WHERE DC.SiteID = put your id here
``` | ```
SELECT D.* FROM
DOWNTIMES D INNER JOIN DOWNTIMECATEGORIES DC ON (D.CATID = DC.CATID)
WHERE DC.SiteID = X
``` | SQL join 2 tables, query 1st with condition from 2nd | [
"",
"sql",
"sql-server",
""
] |
I've got a query that is:
```
SELECT DISTINCT a.field1, a.field2, a.field3, b.field1, b.field2, a.field4
FROM table1 a
JOIN table2 b ON b.fielda = a.fieldb
WHERE a.field1 = 'xxxx'
```
I run this and it returns three xxxx rows. I need all of the information listed above with the first field being distinct. Do I have... | In Postgres, you can use `distinct on`:
```
select distinct on (a.field1) a.field1, a.field2, a.field3, b.field1, b.field2, a.field4
from table1 a join
table2 b
on b.fielda = a.fieldb
where a.field1 = 'xxxx'
order by a.field1;
```
In either Postgres or SQL Server, you can use `row_number()`:
```
select ab.... | One option is to use `row_number()`:
```
with cte as (
select distinct a.field1, a.field2, a.field3, b.field1, b.field2, a.field4,
row_number() over (partition by a.field1 order by a.field1) rn
from table1 a
join table2 b on b.fielda = a.fieldb
where a.field1 = 'xxxx'
)
select *
fro... | Select Distinct returning multiple rows | [
"",
"sql",
"sql-server",
"postgresql",
"distinct",
""
] |
I have a mysql join result which looks like this.
```
ID | Name | Score | SomeID
---------------------------
1 | abc | 100 | 2
1 | abc | 100 | 2
1 | abc | 100 | 3
1 | abc | 100 | 3
1 | abc | 100 | 4
1 | abc | 100 | 4
```
I want the result of this join result in sum as distinct
Like
```... | Try this:
```
SELECT ID, Name, SUM(Score), SomeID
FROM tableA
GROUP BY ID, Name, SomeID;
``` | Things are this simple:
```
SELECT ID, Name,SUM(Score),SomeID
FROM table_name
GROUP BY SomeID;
``` | DISTINCT WITH SUM | [
"",
"mysql",
"sql",
"select",
"group-by",
"sum",
""
] |
There is a SQL table `mytable` that has a column `mycolumn`.
That column has text inside each cell. Each cell may contain "this.text/31/" or "this.text/72/" **substrings** (numbers in that substrings can be any) as a part of string.
What SQL query should be executed to display a list of unique such substrings?
P.S. O... | How about using a recursive CTE:
```
CREATE TABLE #myTable
(
myColumn VARCHAR(100)
)
INSERT INTO #myTable
VALUES
('abcd/eftthis.text/31/sadflh adslkjh'),
('abcd/eftthis.text/44/khjgb ljgnkhj this.text/447/lhkjgnkjh'),
('ljgkhjgadsvlkgnl'),
('uygouyg/this.text/31/luinluinlugnthis.text/31/ouygnouyg'),
... | Having a table named test with the following data:
```
COLUMN1
aathis.text/31/
this.text/1/
bbbthis.text/72/sksk
```
could this be what you are looking for?
```
select SUBSTR(COLUMN1,INSTR(COLUMN1,'this.text', 1 ),INSTR(COLUMN1,'/',INSTR(COLUMN1,'this.text', 1 )+10) - INSTR(COLUMN1,'this.text', 1 )+1) from test;
```... | SQL: select unique substrings from the table by mask | [
"",
"mysql",
"sql",
"sql-server",
"select",
""
] |
I am trying to sort a varchar column A which contains the data like this:
```
A.1) NULL
A.1.xc) 1131820
B.1) NULL
B.1.xc) 1131822
C.1) NULL
C.1.xc) 131824
C.2) (CE) NULL
C.2) (NRML) NULL
C.2.xc) 131826
C.2.xc) 132152
C.3) NULL
C.3.a) 131828
C.3.a.xc) 131830
C.3.xc) 131828
C.4) NULL
C.4.a) 131838
C... | Try this.
It uses the PARSENAME function is sql which is actually to split an object name into it's various parts, but will split anything with dots...
```
SELECT A, B
FROM (
SELECT A, B,
CASE
WHEN LEN(A) - LEN(REPLACE(A, '.', '')) = 3 THEN A
WHEN PATINDEX('%.', REPLACE(A, ')', '.')) > 0 THEN ... | **Step 1: Split your sort criterion**
Use the SQL Server string manipulation and casting methods to add the following fields to your result set:
```
Major (varchar) Minor (int) Remainder yourOtherFields
-------------------------------------------------------------
A 1 NULL ... | Sorting a varchar column in customized way | [
"",
"sql",
"sql-server",
""
] |
I have an unresolved doubt about a query I'm making in PostgreSQL.
I have these 2 tables
**PLAYER**
```
playerID title
1 Rondo
2 Allen
3 Pierce
4 Garnett
5 Perkins<
```
**PLAYS**
```
playerID TeamID
1 1
1 2
1 ... | Use `string_agg()`
```
SELECT concat(N.playerID, ':', N.title),
string_agg(p.TeamID::text, ',') as teamid_list
FROM player N
JOIN plays p ON n.playerID = p.playerID
GROUP BY n.playerID, n.title
ORDER BY 1;
```
Your derived table is not necessary (and the distinct even more so) | For **MySQL**
Try this:
```
SELECT CONCAT(N.playerID, ':', N.title) playerTitle,
GROUP_CONCAT(P.TID SEPARATOR ', ') TID
FROM player N
LEFT JOIN plays P ON N.playerID = PID
GROUP BY N.playerID
ORDER BY playerTitle
``` | SQL aggregation of columns with common value in another column | [
"",
"sql",
"postgresql",
"select",
"group-by",
"string-aggregation",
""
] |
I have a table, with types `varchar`, `datetime`, `datetime`:
```
NAME | START | END
Bob | 10/30 | 11/2
```
What's a SQL query can I look up to find out how to make that table be?:
```
NAME | START | END
Bob | 10/30 | 10/30
Bob | 10/31 | 10/31
Bob | 11/01 | 11/01
Bob | 11/02 | 11/02
```
This is only ran once, ... | May be you need a `Recursive CTE`.
```
CREATE TABLE #dates(NAME VARCHAR(50),START DATETIME,[END] DATETIME)
INSERT INTO #dates
VALUES ('Bob','2014-10-30','2014-11-02')
DECLARE @maxdate DATETIME = (SELECT Max([end]) FROM #dates);
WITH cte
AS (SELECT NAME,
START,
[END]
... | You can do this with a recursive cte:
```
;with cte AS (SELECT Name,Start,[End]
FROM YourTable
UNION ALL
SELECT Name
,DATEADD(day,1,Start)
,[End]
FROM cte
WHERE Start < [End])
SELECT Name, Start, Start AS [En... | For each day between two dates, add a row with the same info but only that day in the start/end columns | [
"",
"sql",
"sql-server",
"datetime",
"insert",
""
] |
i am trying to join the following two tables:
```
Table Patient | Table incident
patient.id patient.birthdate | incident.patientid serviceid
1 1/1/2000 | 1 8
2 1/1/1990 | 1 ... | Instead of `sum()` use `count(distinct)`. Here is an example:
```
SELECT serviceid,
COUNT(DISTINCT CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 0 AND 15
THEN Patient.Id
END) AS [Under 15],
. . .
``` | Instead of `group by serviceid` use `group by patient.patient_id` | Join tables resulting only one row | [
"",
"sql",
"join",
""
] |
I have a simple database that keeps track of contributions (donations) to a charitable organisation.
For the purposes of this question, I only need mention the two tables involved: `contributions` and `benefactors`.
**Benefactors:**
```
ID | BenefactorName | AssociatedFundraiser | Other Meta Columns
----------------... | Since Access doesn't support the `MINUS` set operator, things can be a little confusing in situations like this. I think a query such as this would meet your needs:
```
SELECT v.ID, v.[Benefactor Name], v.MaxContributionDate
FROM (
SELECT b.ID, b.[Benefactor Name], mx.MaxContributionDate
FROM benefactors b
... | ```
SELECT b.*
FROM Benefactors b
INNER JOIN Contributions c ON b.id = c.BenefactorID
WHERE c.ContributionDate < DATEADD(year,-1,GETDATE())
``` | How to select benefactors that have not made contributions in the last year (SQL) | [
"",
"sql",
"ms-access",
""
] |
I have a postgres table with the following format:
```
id key value
-------------------------------------
a 1 p
b 2 q
c 3 r
a 2 s
```
I want to convert it into the following format:
```
... | You **must** provide a second parameter with the list of possible values to allow for missing values in each resulting row:
```
SELECT *
FROM crosstab(
'SELECT id, key, value
FROM tbl
ORDER BY 1, 2'
, 'SELECT generate_series(1,25)' -- assuming your key is type integer
... | Try this:
```
SELECT *
FROM crosstab(
'SELECT id,
key,
value
FROM table
ORDER BY 1, 2'
)
AS CT(id text, one text, two text, three text);
```
You need the final four column names in `as ct()`, chec... | Using crosstab to convert rows to columns fails | [
"",
"sql",
"postgresql",
"crosstab",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.