Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Hi I'm trying to build a sql query where I update the value of a table where the left join of another table is equal to 3.
Example when a vehicle has 3 photos.
The query I've written thus far, it seems to fail with group by though.
```
UPDATE domain.vehicle_listing AS t0 LEFT OUTER JOIN photo AS t1 ON t0.id = t1.veh... | It is silly to use a `left join` for this. You want `inner join`:
```
UPDATE cardaddy.vehicle_listing vl INNER JOIN
(SELECT p.vehicle_listing_id, count(*) as cnt
FROM photo p
GROUP BY p.vehicle_listing_id
) p
ON vl.id = p.vehicle_listing_id AND
p.cnt = 3
SET vl.active... | You can also use `exists`
```
UPDATE vehicle_listing AS t0
SET t0.active = 0
WHERE t0.`create_date` >= '2015-05-02'
AND t0.user_profile_id is not null
AND t0.active = 1
AND EXISTS (
SELECT 1
FROM photo
WHERE vehicle_listing_id=t0.id
GROUP BY vehicle_listing_id
HAVING COUNT(DISTINCT id) = 3
)
```
Sample... | Sql update where left join count equal to 3 | [
"",
"mysql",
"sql",
""
] |
I have a requirement where I have two tables `tbl_bb` and `tbl_rr` and data in them like this:
**tbl\_bb**:
```
isin agency rating date
----------------------------------
142356 MDA A 2010-01-20
142356 MDA AA 2012-05-14
142356 MDA BB 2013-07-04
```
**tbl\_rr**:
```
isin agency... | I would do this using [`APPLY`](https://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) to get the closest 1 record from `tbl_rr`:
```
SELECT bb.isin,
bb.agency,
bb.rating,
bb.date,
rr.rr_rating,
rr.rr_date
FROM tbl_bb AS bb
OUTER APPLY
( ... | What I would do is I would join these tables as given in description, find `DATEDIFF` between two dates and then just find lowest `DATEDIFF` value for each `ISIN` and `agency` | Data comparison between two tables in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have a table that has a column with data like below:
```
aaaa;1
aaaa;2
aaaa;3
bbbb;1
cccc;1
dddd;1
dddd;2
```
I need to select the data with the highest number after the semicolon (`;`) like this:
```
aaaa;3
bbbb;1
cccc;1
dddd;2
```
Can anyone give me ideas to how to do this? | As simple as this:
```
select
-- Construct the string by left part + max(right part)
LEFT([column], CHARINDEX(';', [column], 0) - 1) + ';' +
MAX(RIGHT([column], LEN([column]) - CHARINDEX(';', [column], 0)))
from
[table]
group by
LEFT([column], CHARINDEX(';', [column], 0) - 1) -- The left part o... | Use CharIndex to discover the location of the semicolon and then sort using the result. Example code below:
```
declare @table table (
col1 varchar(25)
)
insert into @table (col1) values ('aaaa;1')
insert into @table (col1) values ('aaaa;2')
insert into @table (col1) values ('aaaa;3')
insert into @table (col1) values... | Comparing data from the same column in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Is possible to delete all contents in scheme in Oracle? I found this script:
```
Begin
for c in (select table_name from user_tables) loop
execute immediate ('drop table "'||c.table_name||'" cascade constraints');
end loop;
End;
/
```
But I would like to know if are there anything to drop everything in the... | Normally, it is simplest to drop and add the user. This is the preferred method if you have system or sysdba access to the database.
If you don't have system level access, and want to scrub your schema, the following sql will produce a series of drop statments, which can then be executed.
```
select 'drop '||object_t... | Found the following script on github which worked out-of-the-box (SQL\*Plus: Release 12.2.0.1.0 Production):
<https://gist.github.com/rafaeleyng/33eaef673fc4ee98a6de4f70c8ce3657>
Thanks to the author Rafael Eyng.
Just login into the schema whose objects you want to drop.
```
BEGIN
FOR cur_rec IN (SELECT object_n... | Delete all contents in a schema in Oracle | [
"",
"sql",
"oracle",
"plsql",
""
] |
**Question 1:** regarding performance, which is the best: subqueries or JOINs?
**Question 2:** is there any way to measure and compare the time when running the subquery or JOIN?
**Edit**
I am a bit confused, though less than earlier. I found this <http://www.akadia.com/services/sqlsrv_subqueries.html>
It wrap it u... | > There are a lot of opinions about JOINs vs Subqueries.
Chris London has a great article on this subject.
> So it seems like the verdict is to do subqueries. The reason the
> subquery in the join is faster than the subquery in the where clause
> is, I believe, because when it’s in the where it has to run that
> cond... | There is no generic answer. It depends on the platform you are using (Microsoft SQL Server, Oracle, MySQL, etc.) as well as the query.
As PM 77-1 said, optimizers these days are pretty good at resolving the relational algebra of a query to the most efficient execution plan. But each server and each query are different... | Performance on subqueries and JOINS? | [
"",
"sql",
"pdo",
""
] |
I have a table which has the following structure and sample data:
```
ITEM LOC STOCK
0001 KS5 10
0001 KS6 30
0002 KS5 10
0002 KS6 20
```
I need to query cross tab so that I get
```
ITEM KS5 KS6
0001 10 30
0002 10 20
```
The LOC (KS5 and KS6) can vary and new locations can be added.
... | For dynamically generated results you need some dynamic PLSQL solution, something like this procedure creating view `v_list_loc`:
```
create or replace procedure p_list_loc is
v_sql varchar2(32000) := '';
begin
for c in (select distinct loc from test order by loc) loop
v_sql := v_sql || '''' ||c.loc|| ''' '... | Please try this query .
```
SELECT *
FROM (SELECT ITEM ,LOC ,STOCK
FROM TABLE_NAME)
PIVOT (SUM(STOCK) FOR (LOC) IN ('KS5' , 'KS6'))
ORDER BY ITEM;
```
Regards. | Oracle SQL Cross Tab Query | [
"",
"sql",
"oracle",
"oracle11g",
"report",
"crosstab",
""
] |
In my database I have a column where the value is separated by a comma (`firstname,lastname`).
I am trying to search this entire field in where clause using like condition.
I have tried this:
```
SELECT fullname
from users
where ( upper( fullname ) like upper('abc, xyz'))
``` | I have used regexp\_like instead of only like and it worked for me. | Are you looking something like this-
It will retrieve field values separated with comma ','
```
select * from table_name where filedName LIKE %,%;
```
If this is not what you are finding, please eleborate or explain more about your question. | How to use like clause for a value separated with comma in Oracle | [
"",
"sql",
"oracle10g",
"sql-like",
""
] |
This is my model with associations:
```
class ProjectLineThreshold < ActiveRecord::Base
belongs_to :project_line
belongs_to :source, class_name: 'Language'
belongs_to :target, class_name: 'Language'
end
```
ProjectLineThreshold table has these columns (:id, :source\_id, :target\_id, :score). I need to add names... | The following query will only hit the db once:
```
self.project_line_thresholds
.joins(:source, :target)
.includes(:source, :target)
.map {|plt| [plt.id, plt.source_id, plt.target_id, plt.score, source.name, target.name]}
``` | You don't need the select statement, just get the names through the associations:
```
ProjectLineThreshold.includes(:source, :target).each do |plt|
puts "Source name: #{plt.source.name}"
puts "Target name: #{plt.target.name}"
end
```
Note that `includes` just makes sure to preload the associated records, otherwis... | Rails SQL Join two tables, One table has two columns with ids of other table, I need to get names of these ids | [
"",
"sql",
"ruby-on-rails",
"postgresql",
"join",
""
] |
I'm making a stored procedure where I need to use a value that has been set earlier. I'm pretty bad at explaining this so I will use an example:
```
CASE
WHEN ((select top 1 stuksweergeven from componenten
where componentid = componentlink.componentid) = 1) and
((select opbrengstperkilo f... | The thing is that all expressions in `SELECT` list are evaluated in `all at once` manner. That's why you need to replicate your code. But you can create `subquery` for that or `cte` like:
```
with cte as(
select Amount1,
ComponentID,
CASE
WHE... | you can totally use `CROSS APPLY` to make things work for you. A very informative article: <http://sqlmag.com/blog/tip-apply-and-reuse-column-aliases> | Use value of 'AS ColumnName' later in query | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Why doesn't the following code work in SQL
```
SELECT *
FROM DATA
WHERE VALUE != NULL;
``` | we can not Compare null value with **=** We Special operator to compare null
value in sql
**IS OPERATOR**
```
SELECT *
FROM DATA
WHERE VALUE is not NULL;
```
Null is not any Value.Sql consider Null as **Unknown/absence of data**. | The condition you written is not in proper format.
If you want to select not null values from your table then you can use the following command
```
select *from table name where column name IS NOT NULL
``` | Selecting rows which are not null in sql | [
"",
"sql",
""
] |
I have a problem in SQL Wich i'll try to explain briefly
**TABLENAME:** EXAMPLE
```
Customer name | ProductClass
-----------------------------
A | Accessory
B | Accessory
B | Bicycle
C | Bicycle
```
**My goal:**
Show Only the 2 rows of Customer B. So letting the query ... | > show the custumors who have 2 value's for ProductClass
```
SELECT *
FROM Example e
INNER JOIN
(
select [customer name]
from example
group by [customer name]
having count(*) = 2
) c on c.[customer name] = e.[customer name]
``` | ```
Select [Customer name]
From Example
group by [Customer name]
having count(distinct ProductClass) > 1
```
If you want to get the entire row, then you could use
```
SELECT *
FROM Example
WHERE [Customer name] in (
Select [Customer name]
From Example
group by [Customer name]
having count(distinct Produc... | SQL: WHERE & the AND-statement problems | [
"",
"sql",
"sql-server",
""
] |
I have two tables.
**table\_1 :**
```
id,value1
2015,100
```
**table\_2 :**
```
id,target
2015,200
```
I want to find the percentage of achievement : `table_1.value1/table_2.target=...%`.
How to create `SQL` scripts in Microsoft Access and Oracle? | You need to join the tables.
Assuming you mean per id:
```
SELECT table_1.id, value/target
FROM table_1
JOIN table_2 ON table_1.id = table_2.id
``` | ORACLE - to get the percent value with 2 decimal places (for example):
```
SELECT
table_1.id,
ROUND(table_1.value/table_2.target * 100, 2) percentage
FROM
table_1,
table_2
WHERE
table_1.id = table_2.id
``` | Calculation between fields in different tables | [
"",
"sql",
"oracle",
"ms-access",
"select",
""
] |
I'm looking for a sql statement to count the number of unique characters in a string.
e.g.
```
3333333333 -> returns 1
1113333333 -> returns 2
1112222444 -> returns 3
```
I did some tests with REGEX and mysql-string-functions, but I didn't find a solution. | There is no direct or easy way of doing it. You may need to write a store function to do the job and by looking at all the characters you may expect in the data. Here is an example for just digits , which could be extended for all the characters in a stored function
```
mysql> select * from test ;
+------------+
| val... | This is for fun right?
SQL is all about processing sets of rows, so if we can convert a 'word' into a set of characters as rows then we can use the 'group' functions to do useful stuff.
Using a 'relational database engine' to do simple character manipulation feels wrong. Still, is it possible to answer your question ... | Count number of unique characters in a string | [
"",
"mysql",
"sql",
"database",
""
] |
I am casting `DateTime` field to Time by using `CAST` Syntax.
```
select CAST([time] as time) as [CSTTime]
```
DateTime
`2015-03-19 00:00:00.000`
Present Output : Time
`03:05:36.0000000`
I need only `HH:MM:SS` and not Milliseconds or 0000's
How to filter or Cast it to exact `HH:MM:SS` Format. | `Time` is not stored with its *display format* in SQL Server.
Therefore, from the user perspective, you can say that it **has no format.**
Of course, that's not completely accurate since it does have a *storage format*, but as an average user you can't really use it.
This is true for all date and time data types:... | You can achieve it with `CAST` just simple use `TIME(0)` datatype in following:
```
SELECT CAST('2015-03-19 01:05:06.289' AS TIME(0))
```
**OUTPUT:**
`01:05:06` | How to cast the DateTime to Time | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I just switched from sqlite3 to postgresql-9.4. Before, when I search with my method "typeahead", I would get results that were not case-sensitive. But now that I switched, the method is suddenly case-sensitive. How can I make the method case-insensitive with postgresql?
```
def typeahead
q = params[:query]
render... | I think you can use ILIKE instead of LIKE
```
Subject.where('name ilike ? OR second_name ilike ? OR keywords ilike ?', "%#{q}%", "%#{q}%", "%#{q}%")
```
or to simplify a little
```
Subject.where('name ilike :name OR second_name ilike :name OR keywords ilike :name', name: "%#{q}%")
``` | You can also use "ilike" keyword instead "like". | How to make postgresql search method case-insensitive? | [
"",
"sql",
"ruby-on-rails",
"ruby",
"postgresql",
""
] |
I'm trying to get my head around this SQL question:
A database for a hotel chain contains the following tables:
```
Hotel(HotelNo, HotelName, City)
Room(RoomNo, HotelNo, Type, Price)
Booking(HotelNo, GuestNo, DateFrom, DateTo, RoomNo)
Guest(GuestNo, GuestName, GuestAddress)
```
I want to Li... | The correct syntax is:
```
SELECT Room.*, Guest.GuestName
FROM Room
INNER JOIN Hotel on Hotel.HotelNo = Room.HotelNo,
inner join Booking on Booking.hotelno= Hotel.HotelNo
inner join Guest on Booking.GuestNo = = Guest.GuestNo
where Hotel.HotelName = "Grosvenor Hotel"
``` | Try this :
```
select g.roomno, g.guestname
from hotel h join room r on h.hotelno = r.hotelno
join booking b on b.hotelno=r.hotelno
join guest g on g.guestno=b.guestno
where h.hotelname='Grosvenor Hotel';
``` | Joining many tables in SQL | [
"",
"mysql",
"sql",
"sql-server",
"inner-join",
""
] |
My table Data looks like
```
Sno Componet Subcomponent IRNo
1 1 C1 to C100 001
2 1 C101 to C200 002
3 1 C201 to C300 003
4 1 C301,C400 004
5 1 C401,C500 005
```
If user ent... | This is a terrible design and should be replaced with a better one if possible.
If re-designing is not possible then [this answer](https://stackoverflow.com/a/30013830/3094533) by Eduard Uta is a good one, but still has one drawback compared to my suggested solution:
It assumes that the Subcomponent will always conta... | No comments about the design. One solution for your question is using a CTE to sanitize the range boundaries and get them to a format that you can work with like so:
```
DECLARE @inputVal varchar(100) = 'C340'
-- sanitize input:
SELECT @inputVal = RIGHT(@inputVal, (LEN(@inputVal)-1))
;WITH cte (Sno,
Sub... | How to split two words and number between two number? | [
"",
"sql",
"sql-server",
""
] |
I want to get all dates between `startend` and `Enddate`.I used between to get the desired result. But the between function skipping the current date.
```
Declare @StartDate Datetime ='2014-04-01 11:13:37'
,@EndDate datetime ='2014-04-04 11:13:37'
```
Query:-
```
Select * from table where date betwee... | You Can Try this
```
Declare @StartDate Date ='2014-04-01'
,@EndDate date ='2014-04-04'
(OR)
Declare @StartDate Datetime ='2014-04-01 00:00:00'
,@EndDate datetime ='2014-04-04 12:59:59'
```
Query:-
```
Select * from table where date between @Startdate and @EndDat... | You could create a procedure like this:
```
CREATE PROCEDURE getAllDaysBetweenTwoDate
(
@StartDate DATETIME,
@EndDate DATETIME
)
AS
BEGIN
DECLARE @TOTALCount INT
SET @StartDate = DATEADD(DAY,-1,@StartDate)
Select @TOTALCount= DATEDIFF(DD,@StartDate,@EndDate);
... | How to get all dates between two dates in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have a query like this:
```
DECLARE @Sortorder VARCHAR(5) = 'asc',
@ColumnNumber INT = 9
SELECT
SUBSTRING(csu.UserName, CHARINDEX(CHAR(92), csu.UserName) + 1, LEN(csu.UserName)) AS UserName, w.WorkItemId
FROM [tasks].[WorkItems] w
LEFT JOIN operations.CustomerServiceUser csu ON csu.UserId = w.AssignedTo... | You have the column `UserName` and an alias `UserName`. It is the **column** value that is being used to sort the results, not the alias. While it is perfectly acceptable to use an alias name inside the `ORDER BY` clause, it cannot be used inside `CASE WHEN` statement.
The solution is to use a sub-query (or CTE):
```... | You can use CROSS APPLY to make your code look more friendly. It does not affect performance:
```
DECLARE
@Sortorder VARCHAR(5) = 'asc' ,
@ColumnNumber INT = 9;
SELECT
SUBSTRING(csu.UserName, CHARINDEX(CHAR(92), csu.UserName) + 1,
u.UserName ,
w.WorkItemId
FROM
[tasks].[WorkItems] w
... | ORDER BY clause is not sorting by alias in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"sorting",
"sql-order-by",
""
] |
I want to check if the id I want to insert into tableA exists in tableB into an if statement
Can I do something like this
```
if new.id exists (select id from tableB where stat = '0' ) then
some code here
end if;
```
When I try this I get an error message, any thoughts? | This is usually done with a trigger. A trigger function does the trick:
```
CREATE FUNCTION "trf_insert_tableA"() RETURNS trigger AS $$
BEGIN
PERFORM * FROM "tableB" WHERE id = NEW.id AND stat = '0';
IF FOUND THEN
-- Any additional code to go here, optional
RETURN NEW;
ELSE
RETURN NULL;
END IF;
END... | Why not do it like this? I'm not very knowledgeable about PostgreSQL but this would work in T-SQL.
```
INSERT INTO TargetTable(ID)
SELECT ID
FROM TableB
WHERE ID NOT IN (SELECT DISTINCT ID FROM TargetTable)
``` | sql query inside if stage with exists | [
"",
"sql",
"postgresql",
""
] |
I'm a new student to database and I've come across a question in my book that I'm having a hard time solving. Pretending I'm the DBA of this bookstore...
I need to determine which books are generating less than 55% profit and how many copies of the books have been sold. Here is what I have tried doing:
```
SELECT tit... | You need to make a join to see how many of your books has been sold
```
SELECT b.ISBN, b.Title, COUNT(ISBN)
FROM books AS b
INNER JOIN ORDERITEMS AS oi ON oi.ISBN = b.ISBN
WHERE Retail >= .55 * Cost
GROUP BY b.ISBN, b.Title;
``` | in your posted request `... count(*)... group by title` returns the number of rows for each title in the table Books, that' s why you always obtain 1.
What you want is to sum the quantity in orderItems, and get the title with isbn matching value in table books. I would do something like this :
```
select Books.title... | How to write this select statement that counts if profit is < 55% of the cost of the item? | [
"",
"sql",
"database",
""
] |
I have a table of `users` that may or may not have `photos` uploaded. I want to delete any users that *don't* have photos. Right now I can get the users with no photos like this:
```
SELECT a.id FROM users a
LEFT JOIN images b
ON a.id = b.user_id
WHERE b.user_id is null
```
However, I'm a little stumped on how to act... | I am guessing your 2nd example failing because it is referencing the table in the subquery, but it shouldn't actually need to:
```
DELETE FROM users c WHERE c.id NOT IN ( SELECT DISTINCT user_id FROM images);
```
Otherwise, I would've done this:
```
DELETE FROM users
USING users AS u LEFT JOIN images AS i ON u.id =... | ```
DELETE users
WHERE NOT EXISTS (
SELECT 1
FROM images i
WHERE users.user_id = i.user_id)
``` | delete results of a select with a JOIN | [
"",
"mysql",
"sql",
"join",
""
] |
How can I create a select query to select every month and year column per column, so the result should be like this:
<http://www.google.de/url?source=imglanding&ct=img&q=http://www.calenweb.com/png/en/2015/2015-yearly-calendar.png&sa=X&ei=Ma1IVeHLLtHjavfsgfAI&ved=0CAkQ8wc&usg=AFQjCNHw0gwp3G9-bSGGNspsZJjMqZbjBA>
Of cou... | You can use PIVOT to arrange the data and a tally table to calculate it:
```
DECLARE @year CHAR(4) = 2015
;WITH N1 (N) AS
(SELECT 1 FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1)) n (N)),
N2 (N) AS
(SELECT
ROW_NUMBER() OVER(ORDER BY N1.N)-1 FROM N1 AS N1
CROSS JOIN N1 AS N2 CROSS JOIN N1 N3),
CTE as
(
... | ```
<?php
$monthNames = Array("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December");
?>
<?php
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");
?>
<?php
$cMonth = $_REQUEST["... | Select year overview like columns | [
"",
"sql",
"sql-server",
"calendar",
""
] |
This must be simple, but I think I'm lost. I have a table A:
```
name id
Tom 1
Barbara 2
Gregory 3
```
...and table B:
```
id nickname preferred
1 Spiderman 0
1 Batman 1
2 Powerpuff 0
3 Donald Duck 0
3 Hulk 1
```
How do I query the table to get a nickname when it is ... | Try below Query:
Which 1. selects row with value A, otherwise, 2. select row with value B
using **LEFT JOIN**,
```
SELECT A.name, B.nickname
FROM A
LEFT JOIN
(
SELECT MAX(preferred) AS preferred, id
FROM B
GROUP BY id
)AS B1
ON A.id = B1.id
LEFT JOIN B ON B.preferred = B1.preferred ... | Just an immediate solution:
```
select a.id,
b.nickname
from a
join b on a.id = b.id and b.prefered = 1
union all
select a.id,
b.nickname
from a
join b on a.id = b.id and b.prefered = 0
where a.id not in(
select a.id
from a
join b on a.id... | In a left join, select row with value A, if not select row with value B | [
"",
"sql",
"join",
"sqlite",
""
] |
I'm having some trouble joining the contents of two tables. Here's the current situation:
**Bought**
`Article``Bought``Year`
**Sold**
`Article``Sold``Year`
**Desired Result**
`Article``Bought``Sold``Year`
I've tried the following to achieve the desired result:
```
SELECT b.article, b.bought, s.sold, b.year
F... | It sounds like you want a `full outer join`:
```
SELECT coalesce(b.article, s.article) as article, b.bought, s.sold,
coalesce(b.year, s.year) as year
FROM Bought b FULL OUTER JOIN
Sold s
ON s.article = b.article AND s.year = b.year
WHERE (b.article = '1' OR s.article = '1')
ORDER BY year
``` | You should use `full outer join` :
```
select coalesce(b.article, s.article)
, b.bought
, s.sold
, coalesce (b.year, s.year) as year
from Bought b
full join Sold s on s.article = b.article
and s.year = b.year
where coalesce(b.article, s.article) = '1'
order by year
``` | SQL join two tables with null values in either table | [
"",
"sql",
"postgresql",
""
] |
```
SELECT [Code], [Due Date Calculation],
--original string that is causing the error
--SUBSTRING([Due Date Calculation], 1, LEN([Due Date Calculation]) - 1) as OG,
--here are the tests that run fine by themselves
LEN([Due Date Calculation]) - 1 as Test1,
SUBSTRING([Due Date Calculation], 1, 2) AS Test2,
SUBSTRING(... | If you want to cut off the last character, just do it like this.
```
DECLARE @String VARCHAR(100) = '123D'
SELECT SUBSTRING(@String,0,LEN(@String))
```
Or if you have multiple characters at the end, then try this which will grab until the numbers stop.
```
DECLARE @String VARCHAR(100) = '123D'
SELECT SUBSTRING(@St... | If i understand your problem correctly you are looking for this
```
Select SUBSTRING([Due Date Calculation],0,CHARINDEX('D',[Due Date Calculation]))
As [Due Date Calculation] FROM Test
```
[**SQLFIDDLE**](http://sqlfiddle.com/#!6/17fbf/2) | SQL Issue using SUBSTRING and LEN | [
"",
"sql",
"sql-server",
"t-sql",
"substring",
"special-characters",
""
] |
I have a column with few different `ID`'s
```
abc_1234
abc_2345
bcd_3456/
cde_4567/
```
And I want a new column that takes off the `/` if it exists
```
abc_1234
abc_2345
bcd_3456
cde_4567
```
I know I'll be using a combination of IF/THEN, `LEFT`, and `LEN`, but I don't know the syntax. Help is appreciated! Thanks! | (*In case your are using SQL Server RDBMS*)
You can try the following combination of `right` and `left`:
```
case when right(col, 1) = '/' then left(col, len(col)-1) else col end
```
[**SQLFiddle**](http://sqlfiddle.com/#!6/855d2/1)
(*In case your are using MySQL RDBMS*)
```
trim(trailing '/' from col);
```
[**SQ... | If your using SQL Server try this
```
SELECT REPLACE(col,'/','')
```
[Replace (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms186862.aspx) | SQL Take off last character if a certain one exists in a string | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I'd like to select a particular value from a table while using an information from another database that is set based on a current database's value.
So a select case to find the operator code and set the DB path.. then use the same path and collate the result.
```
DECLARE @DB varchar (1000)
CASE
WHEN @Operator= 1 T... | Control flow method (likely to be the most efficient):
```
IF @Operator = 1
BEGIN
SELECT stuff
FROM Group_Transactions
INNER
JOIN "Server1\Instance1".Database1.Schema.Table_Trans
ON Group_Transactions... = Table_Trans...
WHERE things...
;
END
ELSE IF @Operator = 2
BEGIN
... | If this is TSQL (I am guessing from your colation names) then you are best trying out [OPENQUERY](https://msdn.microsoft.com/en-us/library/ms188427.aspx) to run your join against another database server. If you are querying a database on the same server you could build your query up as a parameter and then run it using... | SELECT case using a variable which can be set based on a parameter | [
"",
"sql",
"sql-server",
""
] |
What is the expected behaviour due to SQL Standard when we perform `UNION` on two tables with different data types:
```
create table "tab1" ("c1" varchar(max));
create table "tab2" ("c3" integer);
insert into tab1 values(N'asd'), (N'qweqwe');
insert into tab2 values(123), (345);
select
c_newname as myname
from
(
selec... | If you want to use `union all` columns in every query need to have the same type.`C3` must be converteted to varchar because `c1` is varchar. Try below solution
```
create table "tab1" ("c1" varchar(max));
create table "tab2" ("c3" integer);
insert into tab1 values(N'asd'), (N'qweqwe');
insert into tab2 values(123), (... | From [T-SQL UNION](https://msdn.microsoft.com/en-us/library/ms180026.aspx) page:
> The following are basic rules for combining the result sets of two
> queries by using UNION:
>
> * The number and the order of the columns must be the same in all queries.
> * The data types must be compatible.
When one datatype is `VA... | UNION ALL two SELECTs with different column types - expected behaviour? | [
"",
"sql",
"sql-server",
"t-sql",
"standards",
"union-all",
""
] |
I am having trouble writing a query for the following problem. I have tried some existing queries but cannot get the results I need.
I have a results table like this:
```
userid score timestamp
1 50 5000
1 100 5000
1 400 5000
1 500 5000
2 100 5000
3 1000 4000
```
... | This is a pretty typical [greatest-n-per-group](https://stackoverflow.com/questions/tagged/greatest-n-per-group) problem. When I see those, I usually use a correlated subquery like this:
```
SELECT *
FROM myTable m
WHERE(
SELECT COUNT(*)
FROM myTable mT
WHERE mT.userId = m.userId AND mT.score >= m.score) <= 3;
`... | Query for selecting top three scores from table.
SELECT score FROM result
GROUP BY `id`
ORDER BY `score` DESC
LIMIT 3; | Select sum of top three scores for each user | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I have this table
```
ID AGE ACCNUM NAME
--------------------------------
1 10 55409 Intro
2 6 55409 Chapter1
3 4 55409 Chapter2
4 3 69591 Intro
5 6 69591 Outro
6 0 40322 Intro
```
And I need a query that return... | TSQL Ranking Functions: `Row_Number()` <https://msdn.microsoft.com/en-us/library/ms186734.aspx>
```
select id, age, accnum, name
from
(
select id, age, accnum, name, ROW_NUMBER() Over (Partition By accnum order by age desc) as rn
from yourtable
) a
where a.rn <= 2
``` | You can use [`row_number()`](https://msdn.microsoft.com/en-us/library/ms186734.aspx):
```
select accnum
, age
from ( select accnum
, age
, row_number() over(partition by accnum order by age desc) as r
from table1 as T1) t where r < 3
``` | Select Max two rows of each account SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the below statement in my VBA:
```
DoCmd.RunSQL "UPDATE customer SET Status = 'Premier' WHERE customer_id = 41308408 AND location IN ('London','New York') AND Status = ''"
```
which is meant to update a table called "customer". I can see in my table there are about 20 entries where the customer\_id is 41308408... | Maybe `status` isn't blank, maybe it's null? Try below solution:
```
UPDATE customer
SET Status = 'Premier'
WHERE customer_id = 41308408
AND location IN ('London','New York')
AND Status is null
``` | The blank is probably a `null` in the database. `Null`s are values - they are the lack thereof. You can't query them with the `=` operator, you need to treat them explicitly with the `is` operator:
```
DoCmd.RunSQL "UPDATE customer SET Status = 'Premier' WHERE customer_id = 41308408 AND location IN ('London','New York... | sql update table - statement not working | [
"",
"sql",
"ms-access",
"vba",
"sql-update",
""
] |
I have a query like this. I want to use the `PaidAmount` column to calculate another column. Is it possible?
```
SELECT
B.SubProjectCode,
A.StatementBreakDown,
A.Description,
A.ApplicableInvoices,
A.AgreedAmount,
A.SettlePercentage,
(A.AgreedAmount * (A.SettlePercentage/100)) DueToSe... | Try this
```
Select *,(DueToSettle - PaidAmount ) BalanceAmt
from
(SELECT
B.SubProjectCode,
A.StatementBreakDown,
A.Description,
A.ApplicableInvoices,
A.AgreedAmount,
A.SettlePercentage,
(A.AgreedAmount * (A.SettlePercentage/100)) DueToSettle... | Use common table expression (CTE), it will not harm performance.
```
;WITH CTE as
(
SELECT
B.SubProjectCode,
A.StatementBreakDown,
A.Description,
A.ApplicableInvoices,
A.AgreedAmount,
A.SettlePercentage,
(A.AgreedAmount * (A.SettlePercentage/100)) DueToSettle,
(SELECT SUM(C.Pay... | Use subquery columns in another column | [
"",
"sql",
"sql-server",
""
] |
I have few SQL queries which has very low query running performance and I want to check the query execution plan for this query. I am trying to execute the below query but its not showing any query execution plan. Its only display message plan FOR succeeded. I dont know is there any settings that we have to do in oracl... | > EXPLAIN PLAN FOR
In **SQL Developer**, you don't have to use `EXPLAIN PLAN FOR` statement. Press **`F10`** or click the **Explain Plan icon**.

It will be then displayed in the **Explain Plan window**.
If you are using **SQL\*Plus** then use **DB... | Explain only shows how the optimizer thinks the query will execute.
To show the real plan, you will need to run the sql once. Then use the same session run the following:
```
@yoursql
select * from table(dbms_xplan.display_cursor())
```
This way can show the real plan used during execution. There are several other ... | How do I view the Explain Plan in Oracle Sql developer? | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
"sql-execution-plan",
""
] |
I have following MySQL queries:
```
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-02' AND startdate <= '2015-05-09'
UNION ALL
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-11' AND startdate <= '2015-05-12'
```
Is it po... | You can use `OR` operator instead as below
```
SELECT *
FROM bookings
WHERE record_id = 7
AND status = 'available'
AND ((startdate >= '2015-05-11' AND startdate <= '2015-05-12') or (startdate >= '2015-05-02' AND startdate <= '2015-05-09'))
``` | This schould work:
```
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND
((startdate >= '2015-05-02' AND startdate <= '2015-05-09') or (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
``` | Union all, combining query results | [
"",
"mysql",
"sql",
"select",
"union-all",
""
] |
Attempting to get duplicate values of produce.prod\_id using distinct, having clauses.but not giving out the expected result.
Here's my data:
```
PRODUCE
--------- -----------
PROD_ID PROD_NAME
--------- -----------
1 APPLES
2 PEARS
3 ORANGES
4 BANANAS
5 PEACHES
... | You need to use analytical function for your requirement
```
WITH PRODUCE(PROD_ID, PROD_NAME) AS (
SELECT 1, 'APPLES' from dual union all
select 2, 'PEARS' from dual union all
select 3, 'ORANGES' from dual union all
select 4, 'BANANAS' from dual union all
select 5, 'PEACHES' from dual),
BUYERS (BUYER_ID, BUYER_NA... | you don't need distinct. you only need group by and having. you also cant group by buyer\_name to get a count > 1. that is where the issue lies, you can to do this as a set of nested queries
```
select dupes.prod_name,
buyers.buyer_name
from (
select produce.prod_name,
SALES.PROD_ID,
count(SALES... | HAVING COUNT() not giving out the expected result | [
"",
"sql",
"oracle",
"count",
"having-clause",
""
] |
I have following Oracle database. A certain ID can have an accepted status, but can continue in a failed status, and return back in an accepted status. This can happen X time, so it can be called a loop
```
ID STATUS TIME INSERT
------------------------------
1 Accepted 01:00:00
1 Fai... | You can just find max(time\_insert) and group by id. Take a look at sample query
```
with src as (
select 1 as id, 'Accepted' as status, to_date('2015-05-05 01:00:00','yyyy-mm-dd hh24:mi:ss') as time_insert from dual
union all
select 1 as id, 'Failed' as status, to_date('2015-05-05 02:00:00','yyyy-mm-dd hh24:mi:ss... | Hope this will help you:
```
-- this will give you the minimum date of all id's
select * from tab1 where TIME_INSERT in (select min(TIME_INSERT) from tab1 )and STATUS ='Accepted'
```
```
-- this will give you the minimum date of a specefique id
select * from tab1 where TIME_INSERT in (select min(TIME_INSERT) from ... | SQL: age of oldest items | [
"",
"sql",
"oracle",
"select",
"max",
""
] |
A table `users` has three columns: `id, name, pass`.
Another table `logins` has `user_id` column, an `isright` boolean (tinyint) column which says whether the login was successful or not and a `date` column.
I need a simple `left join` to get the user's name and his password **(1)**, the last login datetime (successf... | The straight-forward way is to have two derived tables: One to get the last login date per user, the other to get the last successful login date per user. Then select from users, outer join the two derived tables and look whether the last login was successful and count the (failed) logins after the last successful logi... | I guess you could do something like
```
select count(*)
from logins as l join users as u on l.user_id = u.id
where l.timestamp > (select max(timestamp)
from logins
where user_id = u.id and isright = 1)
```
Get the last timestamp of the login that was successful (subquery) for... | Count rows after specific one | [
"",
"mysql",
"sql",
"subquery",
"left-join",
""
] |
I know this might probably sound like a stupid question, but please bear with me.
In SQL-server we have
```
SELECT TOP N ...
```
now in that we can get the first n rows in *ascending order* (by default), cool. If we want records to be sorted on any other column, we just specify that in the order by clause, something ... | You can think of it like this.
`SELECT TOP N` without `ORDER BY` returns *some* `N` rows, neither first, nor last, just *some*. Which rows it returns is not defined. You can run the same statement 10 times and get 10 different sets of rows each time.
So, if the server had a syntax `SELECT LAST N`, then result of this... | There is no select last because there is no need for it. Consider a "select top 1 \* from table" . Top 1 would get you the first row that is returned. And then the process stops.
But there is no guarantees about ordering if you don't specify an order by. So it may as well be any row in the dataset you get back.
Now d... | Why is there no `select last` or `select bottom` in SQL Server like there is `select top`? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
Having the following dataset. I need some help with a sql statement that would give me the latest row based on `PING_DATE` with unique `PING_DESTINATION` and `PING_SOURCE` with added column with the `AVG` of `PING_AVG` for all rows within the last 10 minutes.
```
PING_DATE | PACKET_LOSS | PING_MIN | PING_... | For "last 10 minutes average" being "last 10 minutes in each group" this is the query you are looking for:
```
with xyz as (
select X.*,
row_number() over (
partition by ping_destination, ping_source
order by ping_date desc
) as latest_row#,
avg(ping_avg) over (
... | Here is a straight forward query based on the question.
Edited based on the sample output. For last 10 minutes from now, use systemtimestamp instead of i.latest\_ping in the snippet "(i.latest\_ping - interval '10' minute)". Use i.latest\_ping for last 10 minutes from max\_ping\_time for that source-dest pair.
```
se... | Oracle query latest row with average for specific column? | [
"",
"sql",
"oracle",
"average",
"window-functions",
""
] |
I have a table in which I am selecting the following columns
```
Work_Role
Date_Invoice
Bill_Amnt
```
I have multiple work roles invoiced at multiple dates. I would like to summarize this by work role and see the amount billed by year on each column, only 2014 and 2015.
Something like this:
```
Work_Role Bill_2... | Use the `case` expression to conditionally sum the bill\_amnt depending on year:
```
select Work_Role,
sum(case when year(date_invoice) = 2014 then bill_amnt end) as "Bill_2014",
sum(case when year(date_invoice) = 2015 then bill_amnt end) as "Bill_2015"
from your_table
group by Work_Role
``` | Use `conditional case expression`:
```
select role,
sum(case when year(bill_date) = 2014 then amount else 0 end),
sum(case when year(bill_date) = 2015 then amount else 0 end)
from table
group by role
``` | SQL Summarize and Group | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have the following table :
```
**Country Name Number**
us John 45
us Jeff 35
fr Jean 31
it Luigi 25
fr Maxime 23
ca Justin 23
```
This table is order by Number. I want to have a quer... | [SQL Fiddle](http://sqlfiddle.com/#!4/a3074/4)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE Countries AS
SELECT 'us' AS Country, 'John' AS Name, 45 AS "Number" FROM DUAL
UNION ALL SELECT 'us' AS Country, 'Jeff' AS Name, 35 AS "Number" FROM DUAL
UNION ALL SELECT 'fr' AS Country, 'Jean' AS Name, 31 AS "Nu... | Try below query:
```
SELECT Country, MAX(numbeer) FROM Table_Name GROUP BY Country
```
PFB updated query to include Name:
```
SELECT t1.* FROM table1 t1 INNER JOIN
(SELECT country, max(numbeer) as numbeer FROM table1 GROUP BY country) t2
ON t1.country=t2.country AND t1.numbeer=t2.numbeer;
``` | Oracle Sql : distinct value in a specific field | [
"",
"sql",
"oracle",
"distinct",
""
] |
The below `create table` statement is giving an error but everything seams OK.
```
explain create table inventory(`id` int primary key,
name varchar(30), price float, category varchar(25));
```
> ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL serve... | [`explain`](https://dev.mysql.com/doc/refman/5.6/en/explain.html) is used to get an execution plan of a `select` query (or the structure of an existing table, although it's more common to use `describe` for that). You cannot apply it to a `create table` statement. Just remove the `explain` keyword and you should be fin... | Read manual [EXPLAIN](https://dev.mysql.com/doc/refman/5.0/en/explain.html) and [EXPLAIN Output Format](https://dev.mysql.com/doc/refman/5.0/en/explain-output.html)
When you precede a `SELECT` statement with the keyword `EXPLAIN`, MySQL displays information from the optimizer about the statement execution plan. That ... | ERROR 1064 (42000) in Create table statement in MYSQL | [
"",
"mysql",
"sql",
"ddl",
"create-table",
""
] |
Sorry for the title. Not really sure how to word it. Edits appreciated.
I have a table, `bin_content`, which has a column, `LotId` that I'm trying to do a calculation on. The calculation is a bit complex, but I've boiled it down to the part that is failing in the sql below:
```
SELECT bc.LotId, bc.ModelId, x.datecode... | Edited answer after the question was updated:
Since you only rely on a single row for this calculation, you can move all the columns to the inner query and select from there:
```
SELECT x.LotId,
x.ModelId,
x.monthAge
FROM (SELECT bc.LotId,
bc.ModelId,
@report... | The issue is because `bin_content` is not in the scope of your subquery.
Removing a lot of the code, you have a skeleton like this:
```
SELECT stuff
FROM(
SELECT stuff
) x, bin_content bc...
```
There is no `FROM` clause inside your inner select query, so `bc` cannot be referenced. The query is complex, so I'm no... | How to access column from other table in calculation? | [
"",
"mysql",
"sql",
"select",
""
] |
I got a problem with a select query
I need to `select coid,model,km,year` for all the vehicles which have `AC` and `MP3`.
I wrote this SQL:
```
select distinct
vehicle.vehid, model, km, year
from
vehicle, models, extras, veh_extras
where
models.modid = vehicle.modid
and vehicle.vehid = veh_extras... | ```
SELECT v.vehid, m.model, v.km, v.year
FROM vehicle v
JOIN model m ON v.modid = m.modid
WHERE EXISTS ( SELECT 'a'
FROM extras e
JOIN veh_extras ve ON e.id = ve.extraid
WHERE ve.vehid = v.vehid
AND e.descr = 'AC'
)
AND EXISTS ( SELECT ... | Assuming you want vehicles that have both AC and MP3, then one option would be to join to the `veh_extras` table multiple times:
```
select distinct v.vehid, m.model
from vehicle v
join models m on m.modid = v.modid
join veh_extras ve on v.vehid = ve.vehid
join extras e on ve.extraid = e.extraid and e.descr = 'A... | Select query including a link table | [
"",
"sql",
"sql-server",
""
] |
I've been trying to get a query that, based on a given condition (if isCurrent = 1 or not) should give me just one value/row based on the CurriculumId /which will be a parameter on a stored procedure).
This value should, in case isCurrent = 1 return to me the item with the most current StartDate but if isCurrent = 0 th... | Give each row a rank in its curriculumid group, using ROW\_NUMBER with an appropriate order by clause. Then only take the records ranked 1 (i.e. best matching).
```
select
intprofessionalexperienceid,
iscurrent,
startdate,
enddate
from
(
select mytable.*
row_number() over
(
partition by curriculumid... | Split this into multiple conditions, like this:
```
SELECT
table.IntProfessionalExperienceId,
table.IsCurrent,
table.StartDate,
table.EndDate
FROM table
WHERE
table.CurriculumId = 12 AND
(
(
Table.IsCurrent = 1 AND
table.StartDate =
(
... | SQL Case on Where clause to different columns | [
"",
"sql",
"sql-server",
""
] |
I have the following table:
```
user_id post_streak streak_date streak first_name club_id
-------- ----------- ------------ --------- ----------- --------
18941684 1 2015-05-05 15:36:18 3 user 1000
```
I want to change streak to 0 if it has been ... | ```
UPDATE table
SET (streak)
VALUES (0)
WHERE streak_date < DATEADD(DAY, -12, NOW() );
SELECT first_name, streak, user_id from myTable
WHERE
club_id = 1000
AND
post_streak = 1
ORDER BY streak DESC;
```
First query will set all streak values to 0 for records that have streak\_date of more than 12 days ag... | <http://sqlfiddle.com/#!9/d8bbd/6>
```
select
user_id,
first_name,
streak_date,
IF(streak_date between date_sub(now(),INTERVAL 12 DAY) and now(),streak,0)
from myTable
where
club_id = 1000
and
post_streak = 1
order by streak desc;
``` | Change MySql value based on time that has past | [
"",
"mysql",
"sql",
""
] |
The set up is a contact table, employee table, and an Employee\_contact table with a many to many relationship. I want to know how to combine these two queries into one for a combined result set.
```
SELECT FirstName, LastName, (ContactNumber) AS Home
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.EmployeeID... | One option is to use conditional aggregation:
```
SELECT FirstName, LastName,
MAX(CASE WHEN ContactType = 'Home Phone' THEN ContactNumber END) AS Home,
MAX(CASE WHEN ContactType = 'Home Fax' THEN ContactNumber END) AS Fax
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.EmployeeID = EC.EmployeeID
J... | Using Case Statement
```
SELECT FirstName, LastName,
CASE
WHEN ContactType = 'Home Phone' then ContactNumber
ELSE NULL
END AS Home,
CASE
WHEN ContactType = 'Home Fax' then ContactNumber
ELSE NULL
END AS Fax
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.Employee... | I need the results from these two queries to be combined into one statement | [
"",
"sql",
"many-to-many",
""
] |
I have a table named `Inventory` with the following structure:
```
Location_ID |Item_ID |Stock
1 |A |100
1 |B |500
1 |C |300
2 |A |10
2 |B |20
```
field `location_ID` and `item_ID` are composite key. I want to produce the following data f... | ```
select DIS_ITME_ID,
IFNULL ((select stock
from inventory
where location_id = 1
and item_id = DIS_ITEM_ID), 0) as stock_1,
IFNULL ((select stock
from inventory
where location_id = 2
and item_id = DIS_I... | I know it's probably too late but there is a simpler way:
```
SELECT Item_Id,
SUM(
CASE WHEN Location_ID = 1 THEN
Stock
ELSE
0
END) As Stock1,
SUM(
CASE WHEN Location_ID = 2 THEN
Stock
ELSE
0
END) As Stock2
FROM Inventory... | MySQL Self Join Table | [
"",
"mysql",
"sql",
""
] |
I have this query:
```
select
(select GETDATE()) as Date,
(select ROUND(sum(QuantityInStore * AveragePrice),2) as "Photo"
from
inventoryinfo,
InventoryStoreInfo
WHERE
InventoryCategoryID IN
('3','6','19','22','23','40','32','56','52','41'))
```
The results are fine, but the column names... | Try this:
```
select
(select GETDATE()) as Date,
(select
ROUND(sum(QuantityInStore * AveragePrice),2)
from
inventoryinfo,
InventoryStoreInfo
WHERE
InventoryCategoryID IN
('3','6','19','22','23','40','32','56','52','41')
) as Photo
``` | Try this query
```
select GETDATE() AS [Date]
,ROUND(sum(QuantityInStore * AveragePrice),2) as [Photo]
,ROUND(sum(QuantityInStore * AveragePrice),2) as COG_Facilities -- Add other outputs here
from
inventoryinfo,
InventoryStoreInfo
WHERE
InventoryCategoryID IN
('3','6','19... | Column Names in SQL Query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have the following which outputs `2015-05-06 10:30:00`
`SELECT DATE_FORMAT( NOW( ) , '%Y-%m-%d' ' 10:30:00' )`
I would now like to increase the day so it outputs, `2015-05-07 10:30:00`
Using `DATE_ADD` I have been able to incease the date, however its now removed the time, `2015-05-07`
`SELECT (DATE(DATE_ADD(DATE... | Pretty much already there, removing the extra ( not required ) *Date* cast :
```
SELECT (DATE_ADD(DATE_FORMAT(NOW(),'%Y-(%m)-%d' ' 10:30:00'), INTERVAL
+1 DAY));
```
which gives
**output**
> 2015-05-07 10:30:00 | You `concat()` instead of just putting the two strings next to each other:
```
SELECT CONCAT(DATE_FORMAT(NOW( ) , '%Y-%m-%d'), ' 10:30:00' )
```
And for tomorrow:
```
SELECT CONCAT(DATE_FORMAT(DATE_ADD(NOW( ), INTERVAL 1 DAY), '%Y-%m-%d'), ' 10:30:00' )
``` | MYSQL DATE_FORMAT to return additional day plus custom time | [
"",
"mysql",
"sql",
""
] |
Function to get time stamp to date format for example
```
Date Field
2014-06-15 00:00:00.000
```
I want it to show the date as
6/15/2014
in another column call day.
What function do i use in sql server?
Thanks | If the source column is of type `Datetime` and target column can be of `varchar` then you can simply write as:
```
SELECT CONVERT(VARCHAR(10), mydatetimecolumn, 101) AS [MM/DD/YYYY]
From Testtable
```
else if source column is of type `varchar` and you are sure that all dates are valid then you can write as:
```
SELE... | ## For SQL 2012 and above:
```
DECLARE @TimeStamp DATETIME = '2014-06-15 00:00:00.000'
SELECT FORMAT(@TimeStamp,'d','en-US') AS Format_Date
```
Results:
```
Format_Date
---------------
6/15/2014
``` | SQL Server Convert Time Stamp in date | [
"",
"sql",
"sql-server",
""
] |
I have a database table `foo` and I want to replace `null` values present in specific columns with empty string. For removing null values present in particular column `x`, I would do like
```
update foo set x = '' where x is null;
```
Is there anyway I would do like,
```
update foo set x,y,z = '' where x,y,z is null... | You can:
```
set
x = case when x is null then '' else x,
y = case when y is null then '' else y,
z = case when z is null then '' else z
...
``` | This will update all rows, where *any* of columns *x*, *y* or *z* has NULL value and uses [COALESCE function](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) to modify values only in columns where value is NULL:
```
UPDATE
foo
SET
x = COALESCE(x, ''),
y = COALESCE(y, ''... | How to replace values present in multiple columns? | [
"",
"mysql",
"sql",
""
] |
Using PostgreSQL 9.4.1, I am trying to identify/display the occurrences of values over 3 different columns. See below (apologies for the formatting, I can't get a proper table format. Type, type1 and type2 are the column names. The table name is `documents`
```
CREATE TABLE documents
AS
SELECT *
FROM ( VALUES
... | You can use `union all` to pivot the columns into rows and then do a group by to count the occurrences for each type
```
select type, count(*) from (
select type1 as type from mytable
union all select type2 from mytable
union all select type3 from mytable
) t1 group by type
``` | Try this:
```
SELECT WORD, COUNT(1) OCCURENCES
FROM (
SELECT Type FROM TableName
UNION ALL
SELECT Type1 FROM TableName
UNION ALL
SELECT Type2 FROM TableName)
GROUP BY WORD;
``` | PostgreSQL: Display and count distinct occurrences of values across multiple columns | [
"",
"sql",
"postgresql",
""
] |
I want to select the balance of the last 2 days(today and yesterday) which the code look something like this
```
select a.balance as "today",b.balance as "yesterday"
from account a,account b
where a.id='xxx'
and a.id=b.id
and a.dates=to_date(sysdate, 'DD-MM-YYYY') --today
and b.dates=to_date(sysdate-1, 'DD-MM-YYYY') -... | No need to join two tables ,if we are allowed to hard code two dates
```
--code with sysdate
with tab as --dummy data
(
select 1 id,sysdate -level+1 dat,level*1000 balance
from dual
connect by level <=10
)
--main query
select max(decode(trunc(dat),trunc(SYSDATE),balance)) "today"
,max(decode(trunc(dat... | No need to join, use `LAG` function to track previous.
If you would like to know about Lag function. Please visit below link.
<http://www.techonthenet.com/oracle/functions/lag.php>.
I have taken below as input. 
and executed below query using lag wh... | oracle query balance | [
"",
"sql",
"database",
"oracle",
"analytics",
""
] |
I have the below view, what I need to do is to get the date difference of the field ActionDate between each 2 records having the same Vehicle AND OrderCode, how can I achieve this in Oracle database.
Also taking into consideration that the dates subtracted should be the one having the **Mode O - Mode I**
I need to ge... | You could use the analytic **LAG() OVER()** function to get the difference between the dates.
For example,
```
SQL> WITH t AS
2 (
3 select 'O' as "MODE", 'V1234567890' as Vehicle, '1411196232' as OrderCode, to_date('2014-11-19 16:34:35','yyyy-mm-dd hh24:mi:ss') as ActionDate from dual
4 union all
5 ... | Use GROUP BY and subtract the dates within a sub query
```
SELECT t.IO_SEQ, t.Vehicle, t.OrderCode, (SELECT MAX(t2.ActionDate) FROM table t2 WHERE t.IO_SEQ = t2.IO_SEQ) - (SELECT MIN(t2.ActionDate) FROM table t2 WHERE t.IO_SEQ = t2.IO_SEQ) AS ActionDiff
FROM table t
GROUP BY t.IO_SEQ, t.Vehicle, t.OrderCode
``` | Date/Time Difference in Oracle for same field in different rows | [
"",
"sql",
"oracle",
"datetime",
"date-arithmetic",
""
] |
I have three tables:
1. `project: project_id, project_name`
2. `milestone: milestone_id, milestone_name`
3. `project_milestone: id, project_id, milestone_id, completed_date`
I want to get the second highest completed\_date and milestone\_id from project\_milestone grouped by project\_id. That is I want to get the mil... | I think you can do what you want with the `project_milestone` table and `row_number()`:
```
select pm.*
from (select pm.*,
row_number() over (partition by project_id order by completed_date desc) as seqnum
from project_milestone pm
where pm.completed_date is not null
) pm
where seqnum = 2... | Using LATERAL (PG 9.3+) can yield better performance than the window function version.
```
SELECT * FROM project;
project_id | project_name
------------+--------------
1 | Project A
2 | Project B
SELECT * FROM project_milestone;
id | project_id | milestone_id | completed_date
----+----... | Query to find second largest value from every group | [
"",
"sql",
"postgresql",
"postgresql-9.3",
""
] |
I have the following table with two fields namely a and b as shown below:
```
create table employe
(
empID varchar(10),
department varchar(10)
);
```
Inserting some records:
```
insert into employe values('A101','Z'),('A101','X'),('A101','Y'),('A102','Z'),('A102','X'),
('A103','Z'),('A103','Y'),... | This is a ***Relational Division with no Remainder (RDNR)*** problem. See this [**article**](https://www.simple-talk.com/sql/learn-sql-server/high-performance-relational-division-in-sql-server/) by Dwain Camps that provides many solution to this kind of problem.
*First Solution*
[**SQL Fiddle**](http://sqlfiddle.com/... | I know that this question has already been answered, but it was a fun problem to do and I tried to do it in a way that no one else has. Benefits of mine is that you can input any list of strings as long as each value has a comma afterwards and you don't have to worry about checking counts.
**Note:** Values must be lis... | Select users belonging only to particular departments | [
"",
"sql",
"sql-server",
"postgresql",
"sql-server-2008-r2",
""
] |
I have an RDD containing a timestamp named **time** of type long:
```
root
|-- id: string (nullable = true)
|-- value1: string (nullable = true)
|-- value2: string (nullable = true)
|-- time: long (nullable = true)
|-- type: string (nullable = true)
```
I am trying to group by value1, value2 and time as YYYY-MM-... | I solved the issue by adding this function:
```
def convert( time:Long ) : String = {
val sdf = new java.text.SimpleDateFormat("yyyy-MM-dd")
return sdf.format(new java.util.Date(time))
}
```
And registering it into the sqlContext like this:
```
sqlContext.registerFunction("convert", convert _)
```
Then I could ... | I'm using Spark 1.4.0 and since 1.2.0 `DATE` appears to be present in the Spark SQL API ([SPARK-2562](https://issues.apache.org/jira/browse/SPARK-2562)). `DATE` should allow you to group by the time as `YYYY-MM-DD`.
I also have a similar data structure, where my `created_on` is analogous to your `time` field.
```
roo... | Aggregation with Group By date in Spark SQL | [
"",
"sql",
"group-by",
"apache-spark",
"aggregation",
""
] |
I am getting `0` on executing the following statement:
```
SELECT DATEDIFF(mi,'1970-01-01 00:00:00','1970-01-01 00:00:01') * CONVERT(BIGINT,60)*1000 as BidTicks
```
Whereas I get `6000` on executing this:
```
SELECT DATEDIFF(mi,'1970-01-01 00:00:00','1970-01-01 00:01:01') * CONVERT(BIGINT,60)*1000 as BidTicks
```
... | You need to use s or ss for your expected output .
```
select DATEDIFF(s,'1970-01-01 00:00:00','1970-01-01 00:00:01') * CONVERT(BIGINT,60)*1000 as BidTicks
```
it will prodece :
```
60000
``` | To return the difference in seconds as the first argument in your query, you'll want to use seconds as the argument, which is an s:
```
select DATEDIFF(s,'1970-01-01 00:00:00','1970-01-01 00:01:01')
```
Basically, your query is asking for the number of minutes between the two. Your first query returns 0, the second r... | SQL Server DATEDIFF keeps ignoring seconds part of date | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
How can one update the same field's value using a different ID?
```
Customer ORderType
Matt 1
Jake 2
```
For all "Matt"s I want to set the orderType to 2 from Jake.
This doesnt work.
```
declare @X nvarchar (250)
set @x = (select OrderType from table where Customer = 'Matt')
update table
... | You can include a FROM clause in an UPDATE query.
```
UPDATE C SET OrderType = J.OrderType
FROM [Table] C
CROSS JOIN [Table] J
WHERE C.Customer = 'Matt' AND J.Customer = 'Jake'
```
If you use a subquery instead, that subquery must return precisely one row.
Note also that your quoted line:
```
set @x = (select Or... | ```
update table
set OrderType = (select TOP 1 OrderType from table where Customer = 'Matt')
where Customer = 'Jake'
``` | SQL Update same field using a different ID | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
For example I have a following table(tbl\_trans) like below
```
transaction_id transaction_dte
integer timestamp without time zone
---------------+----------------------------------
45 | 2014-07-17 00:00:00
56 | 2014-07-17 00:00:00
78 | 2014-04-17 00:00:00
```
so how ca... | ```
select count(transaction_id) tot_tran
,to_char(max(transaction_dte),'Month') month from tbl_trans
where extract (month from transaction_dte)=7
```
PostgreSQL Extract function explained [here](https://stackoverflow.com/a/29839100/3682599)
Reference : [Date/Time Functions and Operators](http://www.postgresql.... | ```
select count(transaction_id),date_part('month',transaction_dte)
from tbli_trans where date_part('month',transaction_dte)=7
``` | select values of a specific month from table contain timestamp column | [
"",
"sql",
"postgresql",
"timestamp",
""
] |
I'm trying to figure out a query that will efficiently allow me to check a specific number against a list of prefixes.
My table structure looks like this
Table 1
```
MobileNumber
408726172
307612535
408642517
111824374
```
Table 2
```
Prefix
408
3076
```
Now as you can see some MobileNumber's start with 408 and 3... | select all numbers will valid/invalid attribute:
```
select
MobileNumber,
case when exists (select 1 from Table_2 where MobileNumber like Prefix + '%')
then 1 else 0 end as IsValid
from Table_1
```
select only valid numbers:
```
select
MobileNumber
from Table_1
where exists (select 1 from Table_2 where Mobi... | Something like
```
SELECT Table1.MobileNumber
FROM Table1
INNER JOIN Table2 ON Table1.MobileNumber LIKE Table2.Prefix +'%'
``` | How to efficiently check records based off a list of prefixes | [
"",
"sql",
"sql-server",
""
] |
I have datatable in Microsoft SQL 2012

It is possible to select data values with newest key position with one request?
Or maybe not with one?
Result i want should be 10,20,30,50,70 | Try this:
```
select data from tableName where id in (select MAX(id) from tableName group by key)
``` | You could do it using the following:
```
SELECT data
FROM datatable
WHERE id IN (
SELECT MAX(ID) latest_id
FROM datatable
GROUP BY key
)
```
This picks out the latest row for each key (going by incrementing ID). Then you simply only pick these rows using the `IN` which excludes the non-latest rows. | Looking for SQL request | [
"",
"sql",
"sql-server",
""
] |
Am using MYSQL
```
SELECT m.proposalId, m.title, n.stageNumber, n.committeeId, n.modifiedDate, o.msNumber , o.description,o.ics,o.edition FROM mystands_Proposal m
INNER join
mystands_ProjectLifecycle n on m.proposalId = n.proposalId
INNER join
mystands_Project o on m.proposalId = o.proposalId
WHERE
... | IF you are getting everything because newstate = 0 is always true then you just need to put this, if I am misunderstanding then I apologise but this seems to be the problem as I understand it:
> "because newState=0 is true and whole where condition is getting true"
```
n.newState=0 AND (n.committeeId=80246 OR (n.assi... | ```
WHERE
n.newState=0
AND (
n.committeeId=80246 OR (n.assignedTo=79977 OR n.actionBy=79977) OR n.proposalId LIKE '%ads%' OR o.projectNumber LIKE '%sds%' OR n.stageNumber=30.99 OR o.category=1 OR o.degreeofCorrespondence=1 OR o.msNumber LIKE '%sadsa%' OR (n.modifiedDate <='2015-05-22' AND n.stageNumber=40.2) O... | OR Operation in JOINS SQL(MYSQL) | [
"",
"mysql",
"sql",
"join",
""
] |
I have a field named `Order_ID` from table `Order`.
when value of `Order_ID` starts with numeric value then it should exclude those records, otherwise it should include those records in the report.
For example: if the `Order_ID` starts with a value **1ABC** it should exclude that record from report .
If `Order_ID` h... | Gayatri,
put following in report where condition
`WHERE NOT REGEXP_LIKE(Order_ID, '^[0-9]');`
report it exclude entries start with numbers and contains values start with Alphabetics only.
Hopes this helps. | <http://docs.oracle.com/cd/B12037_01/server.101/b10759/conditions018.htm#SQLRF00501>
for your particular case it's going to be something like
```
SELECT ... WHERE REGEXP_LIKE (Order_ID, '^[a-zA-Z]+.*$');
``` | How to use Regex_Like for this case? | [
"",
"sql",
"regex",
"oracle-apex",
"regexp-like",
""
] |
I have the following structure
```
----------
presences
----------
id
started
ended
user_id
---------
breaks
---------
id
presence_id
started
ended
```
I need to create an SQL query that returns me the following information
`presence_id user_id presence_time breaks_time`
where presence time is (presence.ended - pr... | <http://sqlfiddle.com/#!9/650a2/3>
```
SELECT p.id presence_id,
p.user_id,
(p.ended-p.started) presence_time ,
SUM(b.ended-b.started) breaks_time
FROM presences p
LEFT JOIN breaks b
ON p.id = b.presence_id
GROUP BY p.id
```
**UPDATE** Same query grouped by user\_id:
<http://sqlfiddle.com/#!9/1ce21/1>
`... | If your `started` and `ended` are stored as `datetime` or `timestamp`, then you can easily do the calculation and find the data in minutes.
The following example will be useful when someone taking multiple short breaks through out the working hours.
Later in the application level you can convert the minutes to hour. H... | get time difference from childs | [
"",
"mysql",
"sql",
"date",
"laravel",
"eloquent",
""
] |
Given a table like that below, how can I get the first `k` rows of it **without using `LIMIT` or `TOP`** ?
```
+--------+-------+-----+
| Person | Group | Age |
+--------+-------+-----+
| Bob | 1 | 32 |
| Jill | 1 | 34 |
| Shawn | 1 | 42 |
| Jake | 2 | 29 |
| Paul | 2 | 36 |
| Laura ... | OK. If variables weren't allowed, you could still do it this way...
```
SELECT some, stuff
FROM an_instance x
JOIN another_instance y
ON (y.something < x.something)
OR (y.something = x.something AND y.some_other_thing <= x.some_other_thing)
GROUP
BY x.something,x.some_other_thing
HAVING COUNT(*... | You can do this by numbering the rows in a derived table and then selecting the rows with row numbers up until your threshold.
For MySQL the query could look like this:
```
SELECT
*
FROM
(SELECT
@row_number:=@row_number + 1 AS row_number,
person,
`group`,
age
... | Get first k records / rows of a table using SQL | [
"",
"mysql",
"sql",
""
] |
I have a function that has to convert currencies based on a conversion rate retrieved from a a table with historic values. It takes four parameters (@to\_curr, @from\_curr, @trans\_date, @gl\_cmp) adn returns the exchange rate.
The table structure is
* `currencypk int primary key`
* `gl_crcnv_bdate datetime`
* `gl_cr... | You could try:
```
SELECT isnull(SELECT convert(decimal(5,4), gl_crcnv_rate)
FROM (select 1/gl_crcnv_rate as gl_crcnv_rate
from [TABLE]
WHERE gl_cmp_key = @gl_cmp AND
gl_CRNCY_TO = @from_curr AND
gl_CRNCY_FROM ... | This is all I can think of based on privided information
Create computed column so that we don't have to calculate it for ever query.
```
ALTER TABLE [TABLE] ADD gl_crcnv_rate_invert AS (1/gl_crcnv_rate) PERSISTED;
```
Craete index
```
CREATE NONCLUSTERED INDEX ix_cmpkey_crncyto_crncyfrom_bdate_edate ON [TABLE] (g... | Optimize SQL query with and or and structure in WHERE clause | [
"",
"sql",
"sql-server",
"query-optimization",
"where-clause",
"sql-function",
""
] |
Consider the following table
```
create table temp (id int, attribute varchar(25), value varchar(25))
```
And values into the table
```
insert into temp select 100, 'First', 234
insert into temp select 100, 'Second', 512
insert into temp select 100, 'Third', 320
insert into temp select 101, 'Second', 512
insert into... | Here is how you can achieve this using `ROW_NUMBER()`:
```
WITH t
AS (
SELECT *
,ROW_NUMBER() OVER (
PARTITION BY id ORDER BY (CASE attribute WHEN 'First' THEN 1
WHEN 'Second' THEN 2
WHEN... | You can use analytical function like `dense_rank` to generate a numbering, and then select those rows that have the number '1':
```
select
x.id,
x.attribute,
x.value
from
(select
t.id,
t.attribute,
t.value,
dense_rank() over (partition by t.id order by t.attribute) as priority
from
Temp t... | Using Case in a select statement | [
"",
"sql",
"sql-server",
""
] |
I have this table:
```
id_category | id_service | amount | date
```
This table have more than one rows with same id\_category and id\_service. How I can get only row from same id\_category and id\_service with the max date of them?
Example data:
```
1 | 1 | 0.1 | 2015-05-05
1 | 1 | 0.12 | 2015-05-06
1 | 2 | 0.2 |... | <http://sqlfiddle.com/#!9/ad96b/3>
```
SELECT t1.*
FROM t1
LEFT JOIN t1 t2
ON t1.id_category = t2.id_category
AND t1.id_service = t2.id_service
AND t1.`date` < t2.`date`
WHERE t2.date IS NULL
``` | Maybe your query like this
```
select a.* from table a
where a.date =
(select max(b.date) from table b where a.id=b.id group by b.id_service, b.id_category)
group by a.id_category, a.id_service;
``` | How I can get only row from same id_category and id_service with the max date of them | [
"",
"mysql",
"sql",
"group-by",
"max",
""
] |
I have the following dynamic SQL query that I am using to filter results for a data range. If my "`createdFrom`" and "`createdTo`" date are not null, I add a where clause to my select statement.
I have 2 questions:
1. How would you go about doing this? Is my logic correct?
2. I am currently getting an error message w... | What's causing your issue is your trying to concatenate a `smalldatetime` with, so string data-types like `VARCHAR`. You can just cast your dates as `VARCHAR` to get around that. `CONCAT()` would be even better though. It is your best friend when concatenating values of different data-types. I HIGHLY recommend using it... | For your question
> I am currently getting an error message when I add the below code, why would I be getting this?
The reason you are getting this error is when the query is executed your condition becomes
```
AND g.CreatedOn > 2015-05-07
```
Which is invalid, but instead your need
```
AND g.CreatedOn > '2015-05-... | TSQL - See if date falls between date | [
"",
"sql",
"t-sql",
"datetime",
""
] |
I am struggling with converting a sql query in rails.
**Background**
I have 3 tables named bus,stop and schedule. Bus table has fields id, and name. Stop table has fields id, and name. Schedule table has fields id,bus\_id,stop\_id,arrival,and bustag.
This is the query i have in sql
```
select A.bus_id as busid, A.s... | Other awnsers have provided the right SQL. So I only show how to execute raw SQL in Rails.
Rails supports not only active record, but also it allows executing raw SQL. It returns an array, each element in the array is a hash with all your selected columns as key and data as value. The returned array is just like which... | Sorry, it should be a comment but as soon as I did job for you
<http://sqlfiddle.com/#!9/45f47/9>
And I expect that you will explain what is wrong with your query or result I post this answer for future real response.
So as you can see in my fiddle your query (with small change to select `A.id` field) already return... | Convert a complex query in rails given a sql query | [
"",
"mysql",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have a table similar to this:
```
Index Name Type
--------------------------------
1 'Apple' 'Fruit'
2 'Carrot' 'Vegetable'
3 'Orange' 'Fruit'
3 'Mango' 'Fruit'
4 'Potato' 'Vegetable'
```
and would like to change it to this:
```
Index Name Type
----------... | You can run `update` with `join` to get [`row_number()`](https://msdn.microsoft.com/en-us/library/ms186734.aspx) within `[type]` group for each row and then concatenate this values with `[type]` using `[index]` as glue column:
```
update t1 set t1.[type] = t1.[type] + ' ' + cast(t2.[rn] as varchar(3))
from [tbl] t1
jo... | Suppose that your table has a Primary Key called ID then you can run the following:
```
update fruits
set Type = newType
from
(
select f.id
,f.[index]
,f.Name
,f.[Type]
,Type + ' '+ cast((select COUNT(*)
from fruits
where Type = f.Typ... | SQL update column depending on other values in same column | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
Can anyone help me format my dollars data into millions of dollars for SQL Server?
```
3,000,000
--> $3M
```
I have this but it's not working
```
SELECT '$' + SUM(Sales_Information.Sales_in_Dollars / 1000000)
AS [Sales in Millions]
```
Doing this gives me #Error
```
format(SUM(Sales_Inf... | The `FORMAT` function has a way of trimming the thousands
each comma reduces the displayed value by 1000
e.g.
```
select format(3000000,'$0,,,.000B')
select format(3000000,'$0,,M')
select format(3000000,'$0,K')
```
(note that I had to use decimals to show 3 million in Billions)
Output:
> $0.003B
> $3M
> $3000... | Try this....
```
SELECT '$' + CONVERT(VARCHAR(100),CAST(3000000 AS MONEY),1)
RESULT: $3,000,000.00
``` | Format Currency into millions of dollars SQL Server | [
"",
"sql",
"sql-server",
""
] |
I've a MySQL table like this: `id | reference_id | name`
And I wish to get rows `WHERE` reference\_id is `IN` a certain list of values: `SELECT * FROM TABLE WHERE reference_id IN(2,3);`
The problem is that the table will contain data like:
```
id | reference_id | name
1 | 1 | nameA
2 | 2 | n... | <http://sqlfiddle.com/#!9/6412b/2>
```
SELECT `table1`.*
FROM `table1`
LEFT JOIN `table1` t
ON `table1`.reference_id = t.reference_id
AND `table1`.id<t.id
WHERE `table1`.reference_id IN(2,3)
AND t.id IS NULL
GROUP BY `table1`.reference_id
``` | ```
select * from your_table
where id in
(
select max(id)
from your_table
where reference_id in (2,3)
group by reference_id
)
``` | MySQL: WHERE IN() limited to one row peer argument | [
"",
"mysql",
"sql",
"limit",
"where-in",
""
] |
I have a JDBC database (DB2 specifically but am looking for something DB agnostic, at a minimum DB2 and Oracle) that has a table that, every 10 minutes, gets records inserted with statistics about APIs that are run by the application in question. It looks something like:
```
StatKey, StartDate, EndDate, APIName, StatN... | Another possible solution:
```
select to_char(StarDate,'rrrr-mm-dd HH24:')||'00' as DateHour,
APIName as API,
sum(StatValue) as Invocations
from STATISTICS
where StatName = 'Invocations'
group by to_char(StarDate,'rrrr-mm-dd HH24:')||'00', APIName
```
There are differents ways to do this..
Good luck! | [SQL Fiddle](http://sqlfiddle.com/#!4/3ad6f/2)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE Data AS
SELECT '201505071498224437562706' AS StatKey, TO_DATE( '2015-05-07 14:12:44', 'YYYY-MM-DD HH24:MI:SS' ) AS StartDate, TO_DATE( '2015-05-07 14:22:44', 'YYYY-MM-DD HH24:MI:SS' ) AS EndDate, 'API5' AS APINam... | SQL: Group by date and summing values in a column | [
"",
"sql",
"oracle",
"jdbc",
"db2",
""
] |
**Note: I cant change the datatype of column**
I want to store a character into a table that has column with number datatype.
The work around i found is convert the character values to ASCII and when retrieving it from the database convert it back to character.
I used couple of function ASCII and ASCIISTR but the li... | While I advise not to proceed like this as this could be rife for errors and a possible maintenance nightmare, I do like a challenge and have been forced to do some screwy things myself in order make some vendor's bizarre way of doing things work for us so I sympathize with you if that is the case. So, for the fun of i... | You can't get the exact string back because Oracle numbers are only stored up to 38 digits of precision.
So if you run this:
```
select cast(no as varchar2(100))
from test;
```
You'll get:
```
80040117040110040101040101040116040950400000000000000000000000000000000000000000000
``` | Insert character to a number datatype column | [
"",
"sql",
"database",
"oracle",
"oracle11g",
"type-conversion",
""
] |
I am trying to return results in TSQL where it ***only*** displays addresses where there are multiple names. The tricky part has been there are multiple duplicates already in this table... so the Having Count variations that I've tried do not work because they all have a count greater than one. So I have not been able ... | You can do a `GROUP` with `COUNT(Distinct Name) > 1` to get Address with more than 1 unique name, and then do a select distinct with a filter on the above grouped Addresses like this.
```
SELECT DISTINCT Address,Name
From Table1
WHERE Address IN (
SELECT Address
FROM Table1
GROUP BY Address
HAVING COUNT(distinct Name)... | You could use multiple `CTE's` to simplify this task. You first want to clean up your data, so remove all those duplicates, therefore you can use `DISTINCT`. Then use `Count(*)OVER(Partition By Address)` to get the count of rows per `Address`:
```
WITH CleanedData AS
(
SELECT DISTINCT Address, Name
FROM dbo.tblL... | Return Distinct Values Where One Column Is The Same But One Column Different | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
There are two tables, OrderID and Order Details.
Orders:
```
OrderID PK
Freight
|....|
```
Order Details:
```
OrderID PK FK
ProductID PK FK
UnitPrice
Quantity
|....|
```
Each `OrderID` is unique for `Orders`, but Order Details can contain several details for the same `OrderID` and different `ProductId`, `UnitPrice... | > My task is to select physical addresses of all Freight records which more than total cost of entire order Freight > UnitPrice \* Quantity \* (Quantity of OrderID in Order Details)
You can achieve that easily by using aliases and filtering the subquery in the following way...
```
SELECT %%physloc%%
FROM Orders o
WHE... | The easiest way of thinking of the process is as follows:
1. The outer query processes each record within the Orders table. As this happens, the current OrderID is shared with the subquery. This is made possible by the subquery's "where" statement. This will ensure the data being summed in the subquery has the same Or... | How to compare row with subquery output in SQL? | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
I'm trying to join a table of data to another table, but one of the ID that I'll be joining on is NULL. However, I have a specific ID I want it to link to with the NULLs.
I might be oversimplifying this question too much with this example, but I'm hoping this will point me in the right direction. So suppose we have th... | You can explicitly check it in the `on` clause:
```
SELECT name, value
FROM table1
JOIN table2 ON (table1.id = table2.id) OR
(table1.id IS NULL AND table2.id = 3)
``` | Join using COALESCE(ID,3) instead of table1.id | Joining an ID with a NULL | [
"",
"sql",
"sql-server",
"select",
"null",
"sql-server-2012",
""
] |
It is known that `GROUP BY` produces one row per group. I want to produce multiple rows per group. The particular use case is, for example, selecting two cheapest offerings for each item.
It is trivial for two or three elements in the group:
```
select type, variety, price
from fruits
where price = (select min(price)... | For any database that supports analytic functions\ window functions, this is relatively easy
```
select *
from (select type,
variety,
price,
rank() over ([partition by something]
order by price) rnk
from fruits) rank_subquery
where... | To save anyone looking some time, at the time of this writing, apparently this won't work because <https://dev.mysql.com/doc/refman/5.7/en/subquery-restrictions.html>.
I've never been a fan of correlated subqueries as most uses I saw for them could usually be written more simply, but I think this has changed by mind..... | Producing n rows per group | [
"",
"sql",
"greatest-n-per-group",
""
] |
I need to sort a varchar2 datatype column with date value in number format as `YYMM` to `MMYY`
The value ranges from
```
3
6
9
12
103
.
.
9909
9912
```
The value with 4 characters in length denotes the year between 1900 and 1999
less than 4 characters denotes the year starts with 2000 and above.
I tried using LPAD(... | You can prepend a century marker based on the length of the value:
```
select value,
case when length(value) = 4 then '19' else '20' end || lpad(value, 4, '0') as dt
from t
order by case when length(value) = 4 then '19' else '20' end || lpad(value, 4, '0');
VALUE DT
---------- ------
9909 199909
... | You need to distinguish the existing four digit values first, so you know they're 20th century dates before you pad out the rest.
Then convert it to a date and fiddle with the format to get the sort order you require :
```
select to_char( expanded_dt, 'MMYYYY') as switched_dt
from (
select to_date(
... | sorting date field with datatype as varchar2 in oracle 11g | [
"",
"sql",
"oracle",
"oracle11g",
"date-arithmetic",
"date-conversion",
""
] |
I have a table with 5 columns `ReportId, Date, Area, BuildingName, Amount`.
Sample data looks like this :
```
-------------------------------------------------------
ReportId | Date | Area | BuildingName | Amount
-------------------------------------------------------
1 | 01/01/2013 | S1 | A1-01 ... | Try this query
```
SELECT @Date AS 'Date'
,t.Area
,t.BuildingName
,t.Amount
,temp.SumAmount
FROM TABLE t INNER JOIN (SELECT Area,
BuildingName,
SUM(Amount) 'SumAmount'
FROM TABLE t
... | This should work:
```
;with filter as (
select Date, Area, BuildingName, Amount
from data
where data.Date = @date
)
select
filter.Date
,filter.Area
,filter.BuildingName
,filter.Amoount
,sum(data.Amount) as [Sum]
from data
join filter
on filter.Area = data.Area
and filter.B... | How to get data by a condition and sum of every row with another condition? | [
"",
"sql",
"sql-server",
""
] |
I want to select either week days or a full week depending on a parameter.
I was looking at using a case statement to do the following, but I don't know how to convert a string of number to a value that can be passed as integers.
Im probably doing this all wrong but any help would be appreciated.
This is where im se... | Why not simplify it and do it this way:
```
Where (Fullweek = 1) -- Will get all days of week
or
(Fullweek = 0 and datepart(dw,date) in (2,3,4,5,6))
``` | This isn't even a problem with sql, it's a conveptual problem. You can't convert such a value to a numeric. What do you expect the Numeric value to be in each case?
You are making a very popular beginer's mistake, when you try to convert a delimited string into an array. What you should do in this case is this:
```
w... | Sql convert string of numbers to int | [
"",
"sql",
"sql-server",
"string",
"int",
""
] |
I have lots of data that is pulled by a press of a button from SQL query through connections in Excel. Then I compose few simple calculations to get results. I also have 4 graphs that are based off that data.
I run into an issue where the code will take few minutes to execute. I believe it is due to the fact that whil... | Have you considered offsetting the chart area in vba and switching back at the end of the code?
Here's how you can [Select the Chart Area](https://msdn.microsoft.com/en-us/library/office/ff841196.aspx) in VBA.
For example. If you want to chart data in Range A1:A10 then you can do the following
`Charts(1).SetSourceDa... | I suggest using
```
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
```
And perhaps also
```
Application.EnableEvents = False
```
Before the query,
And reversing it after the query
```
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.En... | Pause Excel graph while data is updating | [
"",
"sql",
"excel",
"vba",
"graph",
""
] |
Hello I want to extract month inside a trigger, but I get a syntax error near new is there another way to get month from fdate inside the trigger
```
SELECT EXTRACT(MONTH FROM TIMESTAMP new.fdate) into month_extr;
``` | Try using [`date_part(text, timestamp)`](http://www.postgresql.org/docs/9.4/static/functions-datetime.html#FUNCTIONS-DATETIME-TABLE) instead:
```
SELECT date_part('month', NEW.fdate) INTO month_extr;
``` | Have you tried NEW.fdate instead of lowercased? SQL is case insensiteve, but to the best of my knowledge in plpgsql procedures it may be significant.
Another clue - NEW and OLD variables are available only in the row context (so the trigger must be executed "for each row" and not for a statement). | date part in a trigger | [
"",
"sql",
"postgresql",
""
] |
I have a query where each row consists of 3 columns:
1. Name
2. Distance
3. Proximity
I want to sort the rows based on number of `NOT NULL` (i.e. present) values exactly as follows:
1. All values are present
2. Two values are present in this order
* Name and Distance
* Name and Proximity
* Distance and Prox... | Assign a present value as if it were a number (a name=4, a distance=3, a proximity=2), then sum them and sort by that:
```
select ...
from ...
order by
case when name is null then 0 else 4 end +
case when distance is null then 0 else 3 end +
case when proximity is null then 0 else 2 end desc
```
The trick here ... | This doesn't have any cool fancy math, but if you were to have multiple values for the same [type] then mine would sort those in order as well.
```
SELECT *
FROM #Temp
ORDER BY [Type],
LEN(CONCAT(LEFT(Name,1),LEFT(Distance,1),LEFT(Proximity,1))) DESC, --counts number of non null columns ... | Sort results by number of NOT NULL values | [
"",
"sql",
"sql-server",
"t-sql",
"sorting",
""
] |
I need a SQL which generates sequence of alphabets between given start and end point.
Like,for `Start='C' End='G'` output should be
```
C
D
E
F
G
``` | ```
select chr(ascii('C') + level - 1)
from dual
connect by ascii('C') + level - 1 <= ascii('G');
```
Using `connect by` like this (no `start with` and an end condition that only depends on the level) is undocumented (and unsupported) so it might break any time (although I'm not aware of any version where this would ... | Something like this worked
```
WITH X AS
(SELECT 'C' as St, 'G' as En FROM dual)
SELECT CHR(ASCII(X.St)+ROWNUM-1)
FROM X
CONNECT BY ROWNUM<=(ASCII(X.En)-ASCII(X.St)+1)
``` | SQL which generates sequence of alphabets between given start and end point | [
"",
"sql",
"oracle",
""
] |
I have a two tables (Brands and Customers) in my database.
Brands

Customers
What I want is firstly looking up BRANDID for each customer.
Then comapre if BRANDID matches agains BRANDID from BRANDS table.
If matched, appropriate BRANDNAME goes in Customers BRANDNAME.
... | You simply need an OUTER JOIN plus COALESCE:
```
select
c.id,
c.brandid,
coalesce(b.brandname, 'Invalid')
from customers c
left join brands b on c.brandid = b.brandid;
```
This is pure Standard SQL and should run in any DBMS. | Oracle has its own outer join syntax, which is much nicer than standard SQL, but here's the ANSI SQL enquiry:
```
select customers.id,customers.brandid,
if(brands.brandname is null,'Invalid',brands.brandname) as 'Brandname'
from customers
left join brands on (customers.brandid = brands.brandid) ;
``` | Simple SQL Statement in Oracle | [
"",
"sql",
"oracle",
""
] |
I want to insert details of employees into sql table where salary is greater than 5000. How to write this query? Can I use where clause in insert query? | First we have to create employee table with CHECK constraint.
For Example -
```
create table employee(varchar(45) ename, numeric salary CHECK(salary>5000));
```
Now we can insert into employee table.
For Example -
```
insert into employee values('abc', 4000);
```
//it will not be inserted into employee table.
```
... | If I understand your question correctly, you want to insert values of employees with salary greater than 5000, into another sql table. Here's what you can do:
```
INSERT INTO SOME_SQL_TBL (NAME, SALARY)
SELECT
NAME, SALARY
FROM
EMPLOYEES
WHERE
SALARY > 5000;
``` | How to insert value into sql table while checking condition? | [
"",
"sql",
""
] |
I have thousands of groups in a table, something like :
```
1..
1..
2..
2..
2..
2..
3..
3..
.
.
.
10000..
10000..
```
How can i make a select that give me the Top 3 groups each time.
I Want something like select Top 3 from rows , but it have to return the first three groups not the first three rows. | You can try this :
```
;with cte as (
select distinct groupId from mytable order by groupid
)
select * from mytable where TheGroupId in (select top 3 groupdid from cte)
``` | You can use `DENSE_RANK` to assign a number to each group. All members of the same group will have the same number. Then in an outer query, select top 3 groups:
```
SELECT *
FROM (SELECT *, DENSE_RANK() OVER (ORDER BY id) AS rnk
FROM mytable ) t
WHERE t.rnk <= 3
```
The above query assumes that `id` is the colu... | Select Top 100 Groups | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a sample query like this:
```
;WITH view1 AS (
SELECT 1 AS id, 1 AS pId, 'a' AS pName, 1 AS kind
UNION ALL SELECT 2, 1, 'a', 2
UNION ALL SELECT 3, 1, 'a', 1
UNION ALL SELECT 4, 2, 'b', 2
UNION ALL SELECT 5, 2, 'b', 2
UNION ALL SELECT 6, 2, 'b', 1
), view2 AS (
SELECT 1 AS id, 1... | I found a way for with using a inline select:
```
SELECT
ISNULL(v2.pId, v1.pId) AS pId,
ISNULL(v2.pName, v1.pName) AS pName,
(SELECT COUNT(*) FROM view1 vi WHERE vi.kind = 1 AND vi.pId = ISNULL(v2.pId, v1.pId)) AS countKind1,
SUM(v2.price) AS sumPrice
FROM
view1 v1
LEFT OUTER JOIN
view2 v... | Your query looks a bit weird. I can create a few ways of getting desired result, but I'm not sure what's the meaning behind your data. In general, I'd always advice group your data as early as you can, so you probably could group `view1` and then join by `pId`.
Here's the query which gives your results, though
```
;W... | SQL Server : Sum over a field changed after adding a LEFT JOIN | [
"",
"sql",
"sql-server",
"left-join",
""
] |
I see many examples on how to find records that are not in another table, but I'm having a lot of trouble finding records that are either not in table 2, or are in table two, but the freq column value is less than 10%.
I'm first joining a list of variants with ensembl gene names for BRCA1, BRCA2 and any genes that sta... | The two queries you present don't seem to match up. Table names differ, and some of the filter conditions simply don't correlate. In particular, from whence came the condition `AND ens.chromosome NOT LIKE "H%"` (with its incorrect quotes)?
I do think your outer join approach is promising, but I don't understand why yo... | Start by fixing your base query to use proper `join` syntax and simplify the logic (the `IN` is unnecessary, for instance).
```
SELECT DISTINCT *
FROM puzz p JOIN
ensembl ens
ON p.chr = ens.chromosome AND
p.pos >= ens.start AND p.pos <= ens.stop
WHERE ens.gene_name LIKE 'BRC%'
```
I suspect the `DIS... | SQL find records from table 1 that are not in table 2 OR in table 2 with condition | [
"",
"mysql",
"sql",
"left-join",
"exists",
"impala",
""
] |
When I try to exec this query I'll get the error:
> Must declare the scalar variable
What am I doing wrong?
```
@username varchar(50),
@routenaam varchar(50),
@van varchar(50),
@naar varchar(50),
@bezoekadres varchar(50),
@geredenroute varchar(50),
@karakterrit varchar(50),
@toelichti... | You forgot starting DECLARE clause, and in last line you omitted comma between first two variables:
```
DECLARE
@username varchar(50),
@routenaam varchar(50),
@van varchar(50),
@naar varchar(50),
@bezoekadres varchar(50),
@geredenroute varchar(50),
@karakterrit varchar(50),
@toelicht... | You need to `set` the value of the variable like this:
```
DECLARE @sql NVARCHAR(MAX)
SET @sql = N'insert into '+@username+ N'routeinformatie'+ N' values(
@routenaam,@van,@naar,@bezoekadres,@geredenroute,@karakterrit,@toelichting)'
```
Also if this is complete query then you need to add declare at the starting
... | Must declare the scalar variable | [
"",
"sql",
"sql-server",
""
] |
I have two tables (created here for example) like:
```
X1 Y1
a 1
b 2
c 3
d 4
```
and
```
X2 Y2
a 5
m 6
n 7
b 4
```
And I want the output column:
```
X Y1 y2
a 1 5
b 2 4
c 3 0
d 4 0
m 0 6
n 0 7
```
What I tried is:
```
SELECT (A.X1 UNION B.X1) AS X,... | `union` is used to join results one after another. You're attempting to `join` results side by side (which you already did!). The only thing you're missing is a `coalesce` call to handle the missing values:
```
SELECT COALESCE(a.x1, b.x2) AS x,
COALESCE(a.y1, 0) AS y1,
COALESCE(b.y2, 0) AS y2
FROM a ... | You can try [COALESCE](http://www.postgresql.org/docs/8.1/static/functions-conditional.html)
> The `COALESCE` function returns the first of its arguments that is not
> null. Null is returned only if all arguments are null.
```
SELECT COALESCE(A.X1,B.X2) AS X, COALESCE(A.Y1, 0) AS Y1, COALESCE(B.Y2, 0) AS Y2
FROM A FU... | How to use union in select clause? | [
"",
"sql",
"postgresql",
"select",
"union",
""
] |
I have two tables :
***company*** and ***users***
the users table:
```
id | name | cpf | phone_number | company_id
1 | Jonh | 111.11.11 | 1111-1111 | 1
2 | Marie | 222.22.22 | 2222-2222 |
3 | Paul | 333.33.33 | 3333-3333 | 3
4 | ... | You need the same number of columns for both selects, simply add a NULL column (you might have to cast it to a datatype):
```
Select u.name as name,
u.cpf as document,
u.phone_number as phoneNumber,
CAST(NULL AS VARCHAR(20)) as companyData,
'false' as company
FROM u... | If `users` and `company` have the same columns you can use a union query
```
select u.name, null from users where company_id is null
union
select c.name, c.some_column from users u
join company c on u.company_id = c.id
```
If they don't have the same columns, you'll have to specify the column names you want to selec... | PostgreSQL - Merge two selects queries | [
"",
"sql",
"postgresql",
""
] |
I have two tables in sql. One is a table of test cases and the other is a table of test runs with a foreign key that links back to a test case. I want to get the most recent 10 test runs for each test case. I don't want to loop through if I don't have to, but I don't see any other way to solve this problem. What is the... | The idea:
```
select
...
from <test cases> as tc
outer apply (
select top 10 *
from <test runs> as tr
where
tr.<test case id> = tc.<id>
order by tr.<date time> desc
) as tr
```
or, if you just need to get data from table:
```
;with cte_test_runs as (
select
... | You can use Row No. Use Inner of Left Join as the case may be..
```
Select * from testCase a
left outer join
(Select Row_number() over (partition by testcase order by RecentDate desc ) RowNo, * from TestRuns) b
on a.pk = b.fk
where b.RowNo <=10
``` | How do I select a given number of rows for one table for each parent primary key in another table in sql server 2012? | [
"",
"sql",
"sql-server",
"sql-server-2012",
"iteration",
""
] |
Here's my current dataset:
```
rname ename
Advises Grad_student
Advises Faculty
Chairs Department
Chairs Faculty
```
I'm trying to get it into this format:
```
rname ename1 ename2
advises grad_student faculty
chairs department faculty
```
Here's what i've tried so far:
```
select distinct
r1.... | You can use `row_number()` with `conditional aggregation`:
```
with cte as (
select rname, ename, row_number() over (partition by rname order by ename) rn
from relationships
)
select rname,
max(case when rn = 1 then ename end) ename1,
max(case when rn = 2 then ename end) ename2
from cte
group by rname
```
... | In oracle
```
select * from
(select rname,ename,
RANK() over (partition by rname order by ename) Id
FROM relationships)
PIVOT(MAX(ename) for Id in (1 as ename1, 2 as ename2))
``` | How to pivot second column in tsql | [
"",
"sql",
"t-sql",
""
] |
I'm using SUM to add up one of the fields but for the rest of the fields I would like those coming from the latest entry.
**Current Query:**
```
SELECT cu.*,
SUM(cu.use_count) AS total_use_count
FROM coupons_used cu
GROUP BY cu.coupon_id;
```
**Current result:**
```
Array
(
[0] => stdClass Object
(
... | If the `(coupon_id,timestamp)` tuple is unique (that is, if we are guaranteed that there are not two (or more) rows with the same `timestamp` value for a given coupon\_id, at least for the "latest" timestamp)....
```
SELECT c.id
, c.timestamp
, c.coupon_id
, c.user_id
, c.use_count
, c.redempt... | When you use `GROUP BY` the columns that you return should be one of two categories:
* A column computed with an aggregate function, or
* A column that is part of `GROUP BY` list.
MySql relaxes this restriction by letting you put any columns in a select list, but this comes with understanding that *any* row in a grou... | mysql SUM aggregate with ORDER BY | [
"",
"mysql",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.