Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need to remove the sixth character from a `nvarchar` string in sql. I need to do this on every row for the column.
For example:
```
111116111111
```
The length of every record is `12` characters, so I would need to make it `11` characters and remove the `6`th.
Can anyone assist me? Thank you. | You could just do
```
UPDATE table
set column = LEFT(column,5) + RIGHT (column,6)
```
But maybe someone has a fancier way of achieving the same result. | ```
select left([ColumnName],5)+right([ColumnName],6)
```
such as below:
```
declare @Something as nvarchar(12)
set @Something = '111116111111'
select @Something, left(@Something,5)+right(@Something,6)
```
if it gives conversion errors (such as cannot convert datatype nvarchar to numeric), you may have to cast both... | removing the sixth character from a string | [
"",
"sql",
"sql-server",
""
] |
I am trying to show some stats for a fictitious game.
There's a Team model, a Player model, and a Run model.
I am able to get runs for a particular month in the player model:
```
def count_runs(date)
self.runs.count(:conditions => {:created_at => (date.beginning_of_month..date.end_of_month)})
end
```
I am able to ... | I would suggest creating a model that just stored these monthly aggregations:
```
create_table "placements", :force => true do |t|
t.integer "player_id"
t.date "month"
t.integer "runs_count", :default => 0
end
```
So after each run is created, perhaps add a callback like so: (You will want to do something for ... | If you wanted to add another column to your table, I'd create an instance method to handle the calculation:
```
def avg
positions = runs.map(&:position)
avg = positions.inject(:+) / positions.size
return avg
end
```
You could also perform an [SQL query to calculate the average](http://guides.rubyonrails.o... | How to work out average position over a certain period | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
So a little bit of a amateur question. I haven't worked too much with `MySQL`, but I need to pull a *query* from a table and I am not sure where I am going.
The table `core_user` has the following fields:
```
user_id
user_display_name
user_name
user_password
user_email
user_group
user_role
date_registered
language
ti... | You can `GROUP BY` **user\_display\_name** field as follows;
```
SELECT user_display_name, user_name, user_password, user_email
FROM core_user
GROUP BY user_display_name
```
This works great for `MySQL` listing *unique* display names as you suggested in question description:
> I only want the query to return one res... | You can use distinct to get only one result for all same username.
`SELECT DISTINCT user_display_name, user_name, user_password, user_email
FROM core_user` | SELECT from single table one user per company | [
"",
"mysql",
"sql",
"self-join",
""
] |
I have a table of user data in my SQL Server database and I am attempting to summarize the data. Basically, I need some min, max, and sum values and to group by some columns
Here is a sample table:
```
Member ID | Name | DateJoined | DateQuit | PointsEarned | Address
00001 | Leyth | 1/1/2013 | 9/30/2013 | 57 ... | For almost everything you can use a simple groupby, but as you need "the same address than the row where the minimum datejoined is" is a little bit tricker and you can solve it in several ways, one is a subquery searching the address each time
```
SELECT
X.*,
(select Address
from #tmp t2
where t2.Memb... | You could `rank` your rows according to the date, and select the minimal one:
```
SELECT t.member_id,
name,
date_joined,
date_quit,
points_earned
address AS address
FROM (SELECT member_id
name,
MIN (date_joined) AS date_joined,
MA... | Find Min Value and value of a corresponding column for that result | [
"",
"sql",
"select",
""
] |
I am trying to select items from a table that contains the followings columns: `productName`, `ProductPrice` and `ProductCategory`. The products in this table have been categorised into Alcoholic and Soft Drinks.
I am trying to write a SQL statement that will select the `productName` and `ProductPrice`, but only selec... | This is good,
```
SELECT * FROM Products
WHERE ProductPrice BETWEEN '100' AND '300'
```
Here's what you need to add -
```
AND ProductCategory = 'Soft Drinks'
```
To get the final query -
```
SELECT * FROM Products
WHERE ProductPrice BETWEEN '100' AND '300'
AND ProductCategory = 'Soft Drinks'
``` | ```
select
productname,
productprice
from
productsTable
where
price between 100 and 300
and productcategory = "soft drinks";
``` | How to write this SQL Command | [
"",
"sql",
""
] |
I have a couple of tables. One table with Groups:
```
[ID] - [ParentGroupID]
1 - NULL
2 1
3 1
4 2
```
And another with settings
```
[Setting] - [GroupId] - [Value]
Title 1 Hello
Title 2 World
```
Now I'd like to get **"Hello"** back if I'd query the Title for Group ... | This is a problem we've encountered multiple times in our company. This would work for any case, including when the settings can be set only at some levels and not others (see SQL Fiddle <http://sqlfiddle.com/#!3/16af0/1/0> :
```
With GroupSettings(group_id, parent_group_id, value, current_level)
As
(
Select g.id ... | Don't knoww the SQL Server syntax but something like the following?
```
SELECT settings.value
FROM settings
JOIN groups ON settings.groupid = groups.parentgroupid
WHERE settings.setting = 'Title'
AND groups.id = 3
``` | How to get first entry with a value from an hierarchical setting structure? | [
"",
"sql",
"sql-server",
""
] |
I am currently creating a full install script for Magento and Node.js/Grunt
I'd like to skip installation steps.
One of my goals is to configure skin and package directly without accessing the admin (I know how i can do that in the magento admin)
So, someone know which table(s) contain package and skin name ?
Thanks a... | it is in **core\_config\_data** just check it out with your **scope** and **scope\_id** with if u have multistore.
below are the **path** column which you can find in table
**design/theme/skin**
**design/theme/template**
**design/theme/layout**
hopw this will sure help you | you can find on table core\_config\_data,
with path:
```
- design/theme/locale
- design/theme/template
- design/theme/skin
- design/theme/layout
``` | Magento - Change Skin and Package in DataBase | [
"",
"sql",
"database",
"magento",
"package",
"skin",
""
] |
What I'm trying to do is show all the information about the countries from Asia and Europe, but not the other continents. Then order them by continent. I'm just missing something obvious, but what is it?
If I put `AND` between Asia and Europe then it will try to show countries that are from both Asia and Europe, so th... | ```
SELECT * FROM country
WHERE Continent = 'Asia' OR Continent = 'Europe'
ORDER BY Continent DESC;
``` | Try following
```
SELECT * FROM country
WHERE Continent in ('Asia','Europe')
ORDER BY Continent DESC;
``` | SQL Show multiple columns | [
"",
"mysql",
"sql",
""
] |
I need to optimize/implement a MYSQL query wich do the following:
I need to store if an user marked an item as seen, and create a SEEN/UNSEEN button, that delete the correspondent row on the database if already exists (is marked as seen) OR insert a new row if it not (is not marked).
It means, I need a mysql query th... | You can use [stored procedure](http://dev.mysql.com/doc/refman/5.5/en/create-procedure.html) to SELECT and DELETE if exists or INSERT. But much easier would just be left the data there and update seen/unseen with [ON DUPLICATE KEY UPDATE](http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html). | You could use a third column to store an integer, ad use that value as a "toggle" to switch between seen/unseen through an UPSERT query.
Something like:
```
INSERT INTO table (userid, itemid, seen) VALUES (?,?,0) ON DUPLICATE KEY UPDATE seen = ((seen+1) MOD 2);
```
The primary key should be formed by `userid` and `i... | INSERT new row or DELETE old row IF it already exists | [
"",
"mysql",
"sql",
"insert",
"sql-delete",
"exists",
""
] |
I have a table like this in Firebird:
```
Tablename: USERNAMES
+--------+-----+
|username|code |
+--------+-----+
|a |1 |
+--------+-----+
|b |2 |
+--------+-----+
|c |3 |
+--------+-----+
|d |4 |
+--------+-----+
|e |5 |
+--------+-----+
```
and this table
```
Tablenam... | I'm not familiar with Firebird, but here's a generic SQL solution:
```
select
serviceno,
(select username
from usernames
where services.user1 = usernames.code) as user1,
(select username
from usernames
where services.user2 = usernames.code) as user2,
(select username
fr... | You should use `OUTER JOINS`:
```
SELECT serviceno,
IFF(A.USER1 = NULL,NULL,B.NAME),
IFF(A.USER2 = NULL,NULL,C.NAME),
IFF(A.USER3 = NULL,NULL,D.NAME)
FROM SERVICES A
LEFT OUTER JOIN USERNAMES B ON (A.USER1 =B.CODE)
LEFT OUTER JOIN USERNAMES C ON (A.USER2 =C.CODE)
LEFT OUTER JOIN... | Which SQL clause should be used? | [
"",
"sql",
"firebird",
"clause",
""
] |
I am trying to get highest points row along with ranks and select query without rownum=rownum+1 .I have tried the query below but I am missing something also link <http://sqlfiddle.com/#!2/fd7897/7> .
I am looking for answer like for each receiver the last entry which would also be highest points entry rankwise: I rea... | The problem is the `count(*)` in the subquery. Change it to `count(distinct receiver)`:
```
SELECT * ,
(select count(distinct receiver)
from tblA u2
where u2.points > u.points or
u2.points = u.points and u2.id <= u.id
) as rank
FROM (SELECT u.receiver, MAX(u.id) AS id
... | how about that?
```
SELECT a.*
FROM tbla a,
(SELECT receiver,
Max(points) AS m
FROM tbla
GROUP BY receiver) AS b
WHERE a.receiver = b.receiver
AND a.points = b.m
ORDER BY m DESC
``` | rank users by max id and points but (rankings are wrong) | [
"",
"mysql",
"sql",
""
] |
I want to delete rows from multiple tables, How do I do this?
I have tried
```
DELETE a.*, b.*, c.*
FROM table1 as a, table2 as b, table3 as c
WHERE a.colName = 'value'
AND b.colName = 'value'
AND a.c.colName = 'value';
```
`'value'` is same for all tables as well as `colName`.
For this query records must exist in a... | Delete with joins is a bit strange in mysql. You need something like this:
EDIT:
To allow for rows not existing on all tables
```
DELETE FROM
table1, table2, table3
USING
table1
LEFT JOIN
table2 ON table2.colName = table1.colName
LEFT JOIN
table3 ON table3.colName = table1.colName
WHERE
table1.colN... | since your actual problem is executing mutliple queries at once. the best solution for you would be to integrate mysqli extension and use [mysqli\_multi\_query()](http://www.php.net/manual/en/mysqli.multi-query.php) with these queries:
```
DELETE FROM table1 WHERE colName = 'value';
DELETE FROM table2 WHERE colName = ... | Delete row from multiple tables | [
"",
"mysql",
"sql",
""
] |
I have the following table:
```
-----------------------------------
PK integer date
-----------------------------------
1 2 03/01/01
2 1 04/01/01
3 3 02/01/01
4 3 05/01/01
5 2 01/01/01
... | You can order the query by a calculated expression, e.g., `case`:
```
SELECT *
FROM `my_table`
ORDER BY CASE `integer` WHEN 2 THEN 1 ELSE 0 END DESC, `date` ASC
``` | The easiest way to do this is subtract your `integer` by 2 and then get the absolute value of that number. Then sort on that. The absolute value of 2 - 2 will always be zero and any other calculation will be greater than zero. therefor you will be forcing `integer`s of 2 to the top of the list ([**SQL Fiddle**](http://... | MySQL Order By date column and integer column, but specify ordering rules of integer column? | [
"",
"mysql",
"sql",
"database",
"sql-order-by",
"case",
""
] |
I use a Microsoft Access 2010 front end with linked tables on an SQL Server 2012 installation. Local network.
When Access Starts, a VBA script runs which connects to the SQL server and performs some checks.
I recently upgraded from SQL Server 2008 to 2012, that's when the connection between client and Server started to... | Well it's been 7 months. Here is the solution for this problem (in my case):
My secondary DNS Server was an external Server. It could not look up my database (192.168.x.x) because this is an internal address.
When My application called the Primary DNS Server to look up the SQL Server address, it worked fine. When my p... | I do not have a direct answer to your question, but I believe you could start by exploring the IP and ports on which the SQL server is listening to...Is is possible that the machine using DHCP to assign IP for the DB server as well? In this case I guess it could happen when the IPs are refreshed.
We had a similar issu... | SQL Server does not exist or access denied (intermittently) | [
"",
"sql",
"ms-access",
"sql-server-2012",
"connection-string",
""
] |
I am working on exporting a table from my server DB which is about few thousand rows and the PHPMyadmin is unable to handle it.So I switched to the **command line option**
But I am running into this error after executing the `mysqldump` command.The error is
`Couldn't execute 'SET OPTION SQL_QUOTE_SHOW_CREATE=1': You... | An alternative to mysqldump is the SELECT ... INTO form of SELECT, which allows results to be written to a file (<http://dev.mysql.com/doc/refman/5.5/en/select-into.html>).
Some example syntax from the above help page is:
```
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED B... | Not tested, but something like this:
```
cat yourdumpfile.sql | grep -v "SET OPTION SQL_QUOTE_SHOW_CREATE" | mysql -u user -p -h host databasename
```
This inserts the dump into your database, but removes the lines containing "SET OPTION SQL\_QUOTE\_SHOW\_CREATE". The `-v` means reverting.
Couldn't find the english ... | MySQL mysqldump command error(bug in mysql 5.5) | [
"",
"sql",
"database",
"mysql",
""
] |
I have a table similar to,
```
Class City
01 xx
02 xx
03 yy
04 zz
```
And the result I want is like, (select Class and Count of City where city = xx or city = yy )
```
Class Count
01 2
02 2
03 1
04 0
```
The one I can't understand how to do is getting the mismatching... | Try below SQL:
```
SELECT t1.class, count(t2.class) AS COUNT FROM test t1
LEFT JOIN test t2 ON t1.city=t2.city AND t1.city in ('xx', 'yy')
GROUP BY t1.class, t1.city;
```
**[SQL Fiddle](http://sqlfiddle.com/#!2/2ddf07/1/0)** | This should help you:
```
create table #cc (class int ,city varchar(2))
insert into #cc values (1,'xx')
insert into #cc values (2,'xx')
insert into #cc values (3,'yy')
insert into #cc values (4,'zz')
--insert into #cc values (1,'xx')
select class,isnull(c.cnt,0)
from #cc cc
left join (select city ,count(city) as cnt... | Join two sql statements in same table | [
"",
"mysql",
"sql",
""
] |
Following query runs:
```
select foo.g from (select 'hello' as g) as foo
```
and this query runs aswell:
```
select bla.x from (select 'world' as x) as bla
```
but this one does not:
```
select * from (select foo.g from (select 'hello' as g) as foo) join (select bla.x from (select 'world' as x) as bla)
```
I get ... | Give names to you tables using `As <temp_table_name>` and you need to specify the *column* two tables are joining `ON`. Since there is no column to join `ON` i used a *tautology* (which will always result `True`) assuming that the result you expect is: *hello* , *world* in two columns
Here is the rearranged query:
``... | You need to give alias names to your tables. The below code works
```
select * from (select foo.g from (select 'hello' as g) as foo) T1
join (select bla.x from (select 'world' as x) as bla) T2 on t1.g=t2.x
``` | Join two anonymous tables with each other | [
"",
"sql",
"sql-server",
""
] |
I'm a web programmer transitioning to vb.net programming and I am in need of proper guidance. What I am trying to do is perform an SQL table join as shown in the reference [here](http://www.w3schools.com/sql/sql_join.asp). It's my understanding that it's a good practice to for OOP to create a Class Object for each "typ... | First of all, yes this question is a bit confusing, mainly because it seems you're showing objects and asking about an INNER JOIN SQL statement into an object.
That being said I thing it seems that you have 2 tables in your Database Customers and Orders. I am assuming that a customer can have many orders, but an order... | You're falling into the OO purity trap.
Don't go for that trap where you query for a collection, then iterate over the collection to do the JOIN. That's the n+1 latency trap. You'll die a slow, non-performance death doing things like that. Objects aren't buying you anything.
Databases have been optimized to do JOINs ... | SQL table join to VB.net class object | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
Need a little help solving problem. Apologies if this is vague which is why I need help. Show The title ID, title, publisher id, publisher name, and terms for all books that have never been sold. This means that there are no records in the Sales Table. Use OUTER JOIN or NOT IN against SALES table. In this case, the ter... | I believe all you need it to change the `INNER JOIN` to a `LEFT JOIN` for your sales table. Then check for `NULL` on any of the columns from the sales table.
```
SELECT titles.title_id, titles.title, publishers.pub_id, sales.payterms,
titles.price, titles.advance, titles.royalty
FROM publisher... | Well, you are using `INNER JOIN` so it will only return records that match the join condition which is not what you want. You should use `LEFT OUTER JOIN` (or `LEFT JOIN`) and check that the `sales` side is null (meaning there's no record matching).
```
SELECT titles.title_id, titles.title, publishers.pub_id, sale... | Outer Join or NOT IN | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I wanted to see if there is a better way to do this. The statement takes all rows that happened further out than 6 months and puts them into an archive table. Then it takes all the ids present in both tables and removes them from the main table. Any Ideas?
```
INSERT INTO ArchiveTable
SELECT *
FROM MainTable
... | The DELETE can be simplified:
```
DELETE FROM maintable a
WHERE EXISTS (SELECT 1
FROM archivetable b
WHERE a.id = b.id)
``` | My usual approach is to use a global temporary table to store the rowid's of the rows that I'm moving from the source table to the target table, then using that set to perform the deletes. It makes it 100% safe for such issues as an unstable initial data set.
```
insert all
into archivetable (col1, col2 ...)
value... | Insert then delete rows out of an oracle table | [
"",
"sql",
"oracle",
""
] |
I know this is a quite a basic query, but I can't find exactly the solution for my needs, so here goes...
I have a table of customers INT\_AUX\_LISTING, a table of folders in which they're contained INT\_AUX\_DIRECTORY and a joining table INT\_AUX\_DIR\_LIST.
I need to return a list of all customers who are in folder... | First, clarification on left-join and where. If you have a query that has a left-join to a table (per your example where "dl" was the right-side of the join), and then add the "dl" alias to a where clause, that in essence converts it to an INNER JOIN (unless you explicitly tested with an OR dl.listing\_ID IS NULL).
No... | Your WHERE clause is the problem; it brings back ALL rows except the one where that id is not 2, including the one where id is 40017 (since it's not equal to 2). I think you should revisit it. | Beginner SQL trouble with simple Join/Subquery | [
"",
"sql",
"sql-server",
""
] |
I am trying to extract an ID from a URL and running into some issues. The URL's will look something like this:
> <http://www.website.com/news/view.aspx?id=95>
>
> <http://www.website.com/news/view.aspx?id=20&ReturnURL=%2fnews%2fview.aspx%3fid%3d20>
I am trying to return back the number following "?id=" and nothing af... | Use `charindex` to find the position of `?id` and `stuff` to remove the characters that is before `?id`. Then you use `left` to return the characters to the next `&`
```
declare @T table
(
URL varchar(100)
);
insert into @T values
('http://www.website.com/news/view.aspx?id=95'),
('http://www.website.com/news/view.a... | Here is an option that you can use when you want to find the value of any parameter value within a URL, it also supports parsing text values that contain a URL
```
DECLARE @Param varchar(50) = 'event'
DECLARE @Data varchar(8000) = 'User Logged into https://my.website.org/default.aspx?id=3066&event=49de&event=true fro... | How to extract an ID number from a URL string in SQL? | [
"",
"sql",
"sql-server",
""
] |
While trying to insert multiple values into the table, I get a syntax error.I created table named `arts` by the following query :
```
CREATE TABLE arts( id INT NOT NULL AUTO_INCREMENT , subdir VARCHAR (255), PRIMARY KEY(id));
```
and the insert query I am using is :
```
INSERT INTO TABLE arts (id,subdir) VALUES('Aes... | ```
INSERT INTO arts (subdir) VALUES('Aesthetics'),('Literature');
```
Multiple records are seperated with `( )`. Without it, like in your case, it is trying to insert one record with two fields (not counting auto increment et cetera).
Also notice that I've removed the `id`, since you don't wanna insert it (it's `AUT... | **INSERT** multiple values in table.
Create table
```
CREATE TABLE table1(ID int IDENTITY(1,1) NOT NULL, field1 varchar(50),field2 varchar(50),field3 varchar(50));
```
method 1:
```
INSERT INTO table1 (field1,field2,field3)
VALUES('AAA','1','AAA1'),('BBB','2','BBB2'),('CCC','3','CCC3')
```
method 2:
```
INSERT ... | Getting an error while trying to insert multiple values at once. Why is that? | [
"",
"mysql",
"sql",
"database",
""
] |
How Can i get Microsoft Excel 2010 to Connect to MYSQL Server (5.6.12)
I installed MYSQL as a WAMP installation
Windows 7 Ultimate 64bit
MYSQL 5.6.12
Apache 2.4.4
PHP 5.4.16
this should be straight forward, but i've obviously missed something
Now.. When i open Excel 2010
i then go to "Data"
i then go to "From ... | I FOUND A SOLUTION...
Kudos to HongTAT for keeping me on the right path....
(Even though i did do all the initial stuff that you posted, before i actually posted the question, The Act of you Posting it, Got me Looking at it a little deeper...
One thing led to another and i found the solution... Thank you
i suspect ... | Have you done this?
<http://office.microsoft.com/en-001/excel-help/connect-to-a-mysql-database-HA104019820.aspx>
> Before you can connect to a MySQL database, you need the MySQL
> Connector on your computer. To install the MySQL Connector
> (Connector/Net), go to <http://go.microsoft.com/fwlink/?LinkId=278885>
> and ... | How do i get MS EXCEL to Connect to MYSQL Database | [
"",
"mysql",
"sql",
"excel",
""
] |
I saw this in some ASP code and didnt understand the last line, specifically all the apostrophies and quotation marks between Name= and AND. what is being appended? why do we need both?
```
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + ... | That is very simple, you have the start of a string sentence with double quotes. Double quotes indicate the start and the end or part of a string.
for example, if you have
```
sql ="SELECT * FROM USERS"
```
your sentence takes all the value; if you have:
```
sql = "SELCT * FROM USERS"
whereSentence = " WHERE id = 1... | The code is building a query that looks like this:
```
SELECT * FROM Users WHERE Name = 'foo' AND Pass = 'bar'
```
It passes in the text from the `uName` and `uPass` variables into the query string.
This is very dangerous though - it's an open door for [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection). | Can someone clarify this SQL command | [
"",
"sql",
""
] |
I want to calculate the difference between the results of 2 `count(*)`-type SELECT queries executed on 2 separate tables of my PostgreSQL database.
This what I'm currently using (however I should be able to wrap it all up into a single SELECT statement):
```
SELECT "count"(*) AS val1 FROM tab1;
SELECT "count"(*) AS v... | Try this way:
```
select
(
SELECT
"count"(*) as val1
from
tab1
) - (
SELECT
"count"(*) as val2
from
tab2
) as total_count
``` | for same table you can do this.
`select (count(abc)-count(DISTINCT xyz)) from tab;` | Calculate the difference between results of two count(*) queries based on 2 tables in PostgreSQL | [
"",
"sql",
"postgresql",
""
] |
So I am doing a homework project where I have to display the current date, and then the date for three months from now, which I have done with this:
```
SELECT CURRENT_DATE AS "Today's Date", LOWER(ADD_MONTHS(CURRENT_DATE, 3)) AS "Today, Three Months Hence" FROM dual;
```
and again with this:
```
SELECT CURRENT_DATE... | You just need to specify the display format, which you should really do anyway instead of relying on your session defaults:
```
SELECT TO_CHAR(CURRENT_DATE, 'DD/MM/YYYY') AS "Today's Date",
TO_CHAR(ADD_MONTHS(CURRENT_DATE, 3), 'YYYY-MM-DD')
AS "Today, Three Months Hence",
TO_CHAR(ADD_MONTHS(CURRENT_DATE, 3), '... | A `date` value is actually stored as a number in database, not a character string. What you see in your result is the default date format interpretation of your session.
To change the way your date fields are displayed, you need to use `to_char` function.
```
select to_char(sysdate, 'MM') from dual;
```
`'MM'` param... | How would you truncate or limit the results of a date result you are adding time to? (Oracle SQL) | [
"",
"sql",
"oracle",
"date",
""
] |
I have searched and searched for an answer to this, but the only examples I come across are for ones using the preset `date('Y-m-d')` command.
I have three fields in my database - month, day, year. These fields have values entered into them by a person, not the computer. Now, how do I figure out how to NOT show the en... | convert and cast your individual columns into a datetime, then compare it to today ... something like this??
```
SELECT *
FROM table
WHERE cast(CONCAT(year, '-', month, '-', day) as datetime) >= NOW() - INTERVAL 6 MONTH
``` | You can still use the `date` function ... just combine it with the `mktime` function.
```
// DATE IN IDF
// WILL RETURN 2013-08-12
$date_less_6_months = date("Y-m-d", mktime(0, 0, 0, date("m") - 6, date("d"), date("Y")));
// DATE BROKEN APART
$year_less_6_months = date("Y", mktime(0, 0, 0, date("m") - 6, date("d"), d... | interval 6 month but with user added dates | [
"",
"mysql",
"sql",
""
] |
I have three tables: `A`, `B`, `C`. `B` has a many-to-many relationship with `A` and `C`.
```
A >-< B >-< C
```
Assume every table has a primary key column called id, and the join tables have two columns [a\_id, b\_id] and [b\_id, c\_id].
The same row in `B` can be linked to both rows in `A` and `C`. It's fairly str... | Solution was to compare the count of an inner join of B and C with a inner join of all three tables.
```
SELECT ID
FROM C
WHERE (
SELECT COUNT(*)
FROM B_C
WHERE C_ID = C.ID
) <= (
SELECT COUNT(*)
FROM B_C INNER JOIN A_B ON B_C.B_ID = A_B.B_ID
WHERE C_ID = C.ID AND A_ID = ?
);
```
This covers:
1. If C ha... | This would yield all the id's for B that are associated with the selected A:
```
SELECT b_id FROM ab WHERE a_id = ?
```
So you need to find any C's that are related to only these B id's and not others. This can be done by excluding all C's that match other B id's:
```
SELECT c.id
FROM c
LEFT JOIN bc ON c.id = bc.c_i... | Query for rows that share a set of associations | [
"",
"mysql",
"sql",
""
] |
I have a table with a list of IDs that I need to exclude rows from. For each row, an ID can have one value in the comment\_code column. I need to exclude IDs from my results that have a combination of two specific values and keep IDs that have only one of those two values. Sorry if this isn't clear.
Table example:
``... | This approach uses aggregation to find all `id`s that have both values. This is used as an exclusion list using a `left outer join`:
```
select *
from table t left outer join
(select id
from table t
group by t.id
having sum(case when comment = 'apple' then 1 else 0 end) > 0 and
sum(... | Something like this should work.
```
select *
from yourtable
where sequence = 1
and whatever
``` | Oracle SQL: Trying to exclude rows based on a combination of column values | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
"oracle11gr2",
""
] |
I am learning triggers in PostgreSQL.
I have created a trigger function `update_name()`:
```
CREATE OR REPLACE FUNCTION update_name()
RETURNS trigger AS
$BODY$
BEGIN
NEW.name := "ankit";
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION update_name()
OWNER TO postgres;
```
My t... | This is about PostgreSQL syntax. I removed irrelevant references to pgAdmin from the question.
In Postgres, literal values (constants) are enclosed in single quotes: `'value'`.
Double quotes are reserved for identifiers but optional as long as it consists of legal, lower-case letters: `"Odd Name"` vs. `odd_name`.
T... | The ERROR has gone by changing just:
```
NEW.name := "ankit";
```
to
```
NEW.name := 'ankit';
```
Why is it so??? | Assign a constant value in a trigger function | [
"",
"sql",
"postgresql",
"syntax",
"triggers",
"quotes",
""
] |
I am facing a problem :
table1
```
C1 C2 C3 tempId
1 4 5 ab
2 6 7 fc
3 8 9 vb
```
table2
```
ids val
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
```
I want to pass the value of tempId i.e. ab and want a output like
```
valofc... | try this
```
select t2.val valofc1,t3.val valofc2,t4.val valofc3 from table1 t1
inner join table2 t2 on t1.C1 = t2.ids
inner join table2 t3 on t1.C2 = t3.ids
inner join table2 t4 on t1.C3 = t4.ids
where tempId = 'ab'
```
[**DEMO HERE**](http://sqlfiddle.com/#!2/32097/3) | Try this way:
```
select t21.val as valofc1, t22.val as valofc2, t23.val as valofc3
from table1 as t
join table2 as t21 on t21.ids = t.C1
join table2 as t22 on t22.ids = t.C2
join table2 as t23 on t23.ids = t.C3
where t.tempId = 'ab'
``` | Sql query with multiple column join | [
"",
"mysql",
"sql",
"sql-server",
"sqlite",
""
] |
I'm getting the first 50 records using this query. However, there is a flag named `read` in the same table, and I only want to return the first 50 records that are not `read` (i.e. `isread=false`). How can I achieve this? Can anybody give me ideas for the required query? I have tried using sub queries.
```
SELECT * FR... | Try adding an `AND` condition to your WHERE clause: `userID = 'email' AND flag = true`. This will only return users with true value for flag of which you can get the top 50 by your limit condition. | Since you want to get the first 50 values regardless of the IsRead condition and then filter it, you can try this but I populated the query in Sql Server.
```
SELECT * FROM (SELECT TOP 50 * FROM notification) S WHERE toUserId = 'email' and isread=false
```
This should help. You can try the same technique in MySql. | Fetching data from database and Filter Results | [
"",
"mysql",
"sql",
"database",
"database-design",
"database-schema",
""
] |
I am trying to run the following piece of code to update table summary from data in click\_summ table.
```
data temp(index=(comp=(card_number package_sk)));
set click_summ(where=(^missing(e_1st_click_dt)));
keep card_number package_sk e_1st_click_dt;
run;
data summary(drop=new_date) ;
set summary;
set temp(rename=(e_... | ```
data temp;
set click_summ(where=(^missing(e_1st_click_dt)));
keep card_number package_sk e_1st_click_dt;
run;
data summary(drop=new_date) ;
modify summary temp(rename=(e_1st_click_dt= new_date) in=a);
by card_number, package_sk;
if a then do;
e_1st_click_dt = min(e_1st_click_dt,new_date);
end;
else
_ERROR_ =... | Just change the table name from summary to something else and try..am not sure whether we can use summary as a table name since proc summary is there...not sure but try and see | Update an oracle table with data from another table in SAS | [
"",
"sql",
"sas",
""
] |
Reading about `Triggers`, `Equi-Joins` and `cross-joins` has my head spinning and unable to figure out what i need.
Basically, I have 3 tables:
```
Table 1: Users
id
username
score
Table 2: Acts
act_id
act
user_id
act_score
Table 3: Votes
vote_id
act_id
user_voter
score_g... | I would suggest to use `VIEW` to calculate scores for each `User` or `Act` as needed. That would guarantee that scores will always be correct and you would not need a lot of triggers.
**UPDATED:**
1) Remove scores from `Users` and `Acts` tables;
2) Create a view `ActsWithScore`:
```
CREATE VIEW ActsWithScore AS
SE... | A trigger is the most obvious solution but it can add a maintenance issue. If you app is not that big/complex you ill be fine.
Also I prefer to do both inserts at business layer. If you are doing a insert, why not do two inserts? It can add overhead to your application but if your app is not a doing that thousands time... | Inserting data into table automatically based on another table | [
"",
"mysql",
"sql",
"join",
"triggers",
""
] |
I would like to know if I can get in a single query, All the objects of certain model where its date's year equals the year of the Max('date') of the model. For example, using the models from the [Aggregation Django Docs](https://docs.djangoproject.com/en/dev/topics/db/aggregation/), how can I get All the `Book`s publi... | Performing statement in **a single query is no guarantee to improve performance**, this is easy to understand if you try to write an agnostic RDBMS brand SQL single sentence for yours requirements. Also, you **lost in readability**.
In my opinion, you can see and elegant solution in this approach:
1. Get last `Expo` ... | Here is how you can do something using a combination of [Annotation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/#filtering-on-annotations) and [F](https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model) object
To filter on Max date:
```
ModelClass.objects.a... | Django - Filter a queryset by Max(date) year | [
"",
"sql",
"django",
"django-queryset",
""
] |
I have two tables, related by a foreign key. I want to select a column from the child table based on some information about a row in the parent table.
The definitions of the tables are:
```
CREATE TABLE Runs(
id INTEGER,
name TEXT UNIQUE NOT NULL,
rundate TEXT NOT NULL,
PRI... | You are probably missing part of the join command where you are telling sqllite how to merge the tables, so you are getting a cartesian join.
```
SELECT direc FROM Location
INNER JOIN Runs
ON location.rid = Runs.id WHERE Runs.name = '012114';
```
This should work, assuming that location.rid is the referring to ... | When you do a `JOIN` clause, you need to specify which columns on each table to join.
For example:
```
SELECT direc
FROM Location
INNER JOIN Runs ON Runs.id = Location.rid
WHERE Runs.name = '012114';
```
Without this, you can return quite unexpected results. | Inner join of child table with parent table | [
"",
"sql",
"select",
"sqlite",
"inner-join",
""
] |
I created a table `scores` as follows.
```
student_id course score
1 math 90
1 cs 70
2 math 60
2 cs 50
```
I want to categorise all scores of a student by a scale:
```
>60 pass
<60 fail
=60 bottomline
```
Then, I wrote a select statement with a case expression as
```
select student_id, course, score =
(case score ... | ```
select student_id, course, score,
case --<-- you dont need to mention column name here
when score < 60 then 'fail'
when score = 60 then 'bottomline'
when score > 60 then 'pass'
end as 'result'
from scores
order by student_id
```
# `Sql Fiddle` | why `score = ...` ?
just:
```
select student_id, course, score,
(case score
when score > 60
then 'pass'
when score < 60
then 'fail'
else 'bottomline'
end) as 'result'
from scores
order by student_id
``` | Using a SELECT statement with a searched CASE expression | [
"",
"mysql",
"sql",
"database",
""
] |
I currently have two tables that have the same column names;
```
APPLICATION_Reference.firstName, APPLICATION_Reference.lastName
APPLICATION_Recommendation.firstName, APPLICATION_Recommendation.lastName
```
```
$all_references = mysqli_query($con, "SELECT *
FROM APPLICATION_Reference
INNER JOIN APPLICATION_Recommenda... | Use table aliases and column aliases.
In your query you can alias a whole table to make things more readable, e.g.
```
APPLICATION_Reference ref
```
Your query then becomes
```
SELECT *
FROM APPLICATION_Reference ref
INNER JOIN APPLICATION_Recommendation rec ref.referenceId = rec.referenceId
INNER JOIN Applicant ap... | you could use
```
SELECT *, table1.field AS field1, table2.field AS field2 ...
```
and then reference the fields as field1 and field2 in your output | Differentiating Between Table Names | [
"",
"mysql",
"sql",
""
] |
I have two select statements such as bellow:
```
SELECT t.name, SUM(t.number)
FROM table1 t
WHERE t.something = '1'
GROUP BY t.name
SELECT v.name, SUM(v.number2)
FROM table2 v
WHERE v.somethingElse = '2'
GROUP BY v.name
```
The result from both of these tables have the common column of 'name' I want to combine... | Create the virtual column on subqueries with values 0 and them sum them all by names using union all. Something like this
```
select name, sum(number1),sum(number2) from (
SELECT t.name, SUM(t.value) as number1 , 0 as number2
FROM table1 t
WHERE t.value = '1'
GROUP BY t.name
UNION
... | Try this way:
```
select A.Name, A.cnt1, B.cnt2
from(
SELECT t.name, SUM(t.number) cnt1
FROM table1 t
WHERE t.something = '1'
GROUP BY t.name
) A
left join (
SELECT v.name, SUM(v.number2) cnt2
FROM table2 v
WHERE v.somethingElse = '2'
... | Join 2 SELECT statements on common column | [
"",
"sql",
"oracle",
""
] |
I have tow tables with same composite key.
Following is the table
table T1
```
No | Date | S_hour
----+---------------+-------
1 | 2012-01-01 | 8
1 | 2012-01-02 | 8
1 | 2012-01-03 | 8
2 | 2012-01-01 | 8
2 | 2012-01-02 | 8
2 | 2012-01-03 | 8
```
table T2
```
No | Date ... | ```
select t1.No
, t1.Date
, t1.S_hour - t2.L_hour
from Table1 t1
join Table2 t2
on t1.No = t2.No
and t1.Date = t2.Date
``` | something like this
```
SELECT T1.No, T1.Date, s_hour - L_hour AS result
FROM T1 INNER JOIN
T2 ON t1.No = t2.No AND
T1.Date = T2.Date
``` | Two tables having same composite key | [
"",
"mysql",
"sql",
"t-sql",
"plsql",
""
] |
I want to loop through several stored procs and extract one string form each of them to use in another procedure (basically the 4-part remote server string)
So I can get the stored procs list from `SysObjects` (with Type = P) into a table, then I can loop or cursor through that table variable calling `sp_helptext` on ... | The portable way is to use the ANSI/ISO view `INFORMATION_SCHEMA.ROUTINES`, but you'll only get the first 4000 characters of the stored procedure definition:
```
declare @source_code varchar(max)
select @source_code = t.ROUTINE_DEFINITION
from information_schema.routines t
where specific_schema = 'owner-schema' ... | Nicholas Carey's third option needs some changes,
object\_definition function needs object\_id as parameter,
so the code should be
```
declare @source_code varchar(max)
declare @objectid int
select @objectid=object_id('dbo.my_stored_procedure_name')
select @source_code = object_definition(@objectid )
```
Check to t... | get the text of a stored procedure into a variable in SQL Server | [
"",
"sql",
"stored-procedures",
"sql-server-2008-r2",
""
] |
Is it possible to insert into a table based on a count condition (using just 1 statement)?
I want to do something like this:
```
insert into [table] (...) values (...) if select count(*) from [table] < 5
```
(insert into the table only if it has less than 5 entries) | try something like this:
```
insert into [table] (#FIELDS#)
select (#VALUES#) from [table]
where (select count(*) from [table]) < 5
FETCH FIRST ROW ONLY
``` | You can try like this
```
insert into [table] (...) values Select (...) from [table] Where count(*) < 5
``` | SQL conditional insert into | [
"",
"sql",
"derby",
""
] |
I have a rails/backbone single page application processing a lot of SQL queries.
Is this request:
```
SELECT * FROM `posts` WHERE `thread_id` = 1
```
faster than this one:
```
SELECT `id` FROM `posts` WHERE `thread_id` = 1
```
How big is the impact of selecting unused columns on the query execution time? | For all practical purposes, when looking for a single row, the difference is negligible. As the number of result rows increases, the difference can become more and more important, but as long as **you have an index on thread\_id** and you are not more than 10-20% of all the rows in the table, here is still not a big is... | Selecting fewer columns is generally faster. Unfortunately, it is hard to say exactly how much the time difference will be. It may depend on things like how many columns there are and what data is in them (for example, large CLOBS can take longer to fetch than simple integers), what indexes have been set up, and the ne... | Is selecting fewer SQL columns making the request faster? | [
"",
"sql",
""
] |
I have a simple property table with an id and name field. I also have a propertyPrices table whose schema and data is shown below;

So, it specifies prices for given date ranges. The price value indicates the cost for a day within that period.
When ... | I can imagine writing a stored procedure, or the other solution would be to build up an auxiliary table just containing a list of days.
If you had a table `calendar(date)` with all dates in the affected range, you could do
```
SELECT
property.name, SUM(dbo.propertyPrices.price) AS totalCost
FROM
dbo.proper... | I would do it using CTEs. First get the prices with actual date ranges, then multiply price by number of days in the range and sum it.
```
with cte as
(
select propertyID, price,
case when startDate < @startDate then @startDate else startDate end as startDate,
case when endDate > @endDate then @endDate else end... | SQL Sum of aggregated values within SELECT | [
"",
"sql",
"sql-server",
""
] |
Find the sid who have reserved a red and a green boat.
```
Table reserves
sid bid
22 101
22 102
22 103
31 103
32 104
Table Boats
Bid Color
101 blue
102 red
103 green
104 red
```
Is it possible to use and operator with sub query something like this
```
select sid from reserves wher... | You need to specify in the bin in against both subsqueries, and as you would both red and green boats (and boats can only be one colour) you are actually saying you would like the reservers that are either red or green, so OR is appropriate here.
```
select sid from reserves where
bid in (select bid from boats where ... | It works for something like this
```
select sid from reserves where bid in(select bid from boats where color='red')
and sid in
(select sid from reserves where bid in(select bid from boats where color='green'));
``` | Using And operator with subquery | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
The following SQL is not exactly what I need. In a query I am summing Line totals according to
Part# and Date.
This is an invoice history file. the user has a report that shows QTY sold by part# - but the file used there does not hold $amt. So I made a query that creates a temp file that breaks on Part# and date. Becau... | SQL is not a reporting tool. SQL is a language that asks for sets of data; typically either details or totals (GROUP BY). SQL will do totals if you specify GROUP BY WITH ROLLUP, but that doesn't apply here.
There are several approaches you can take.
1) Create a view or logical file that does the JOIN you've specified... | Nooooooooo.... *Please* don't use Query/38 (oh yeah, sorry, they renamed it to Query/400), which has been around and probably unimproved since 1982.
QM Query is a reporting tool that will help you format your reports, have multi-level breaks, allows a prompted interface similar to Query/400. You have found how to retr... | Need SQL To do summary like Query/400 | [
"",
"sql",
"ibm-midrange",
"db2-400",
""
] |
I have several fields in a table, but wish to remove some records. I'll call them duplicates, but they aren't in the true sense.
The table and some example data
```
Id1 Id2 Name1 Name2 DOB1 DOB2
123, abc, jones, smith, 19740901, 19820101
abc, 123, smith, Jones, 19820101, 19740901
def, 456, davis, short, 197... | Here is a standard SQL way of doing this:
```
delete from t
where Id1 > Id2 and
exists (select 1
from t t2
where t2.Id1 = t.Id2 and
t2.Id2 = t.Id1 and
t2.Name1 = t.Name2 and
t2.Name2 = t.Name1 and
... | You could use an `INNER JOIN` to pair up any rows with transposed `Id1` and `Id2` values, filter down to those that are actually duplicates, select all but one of the duplicate rows, and then send the results to a `DELETE`.
```
DELETE T1
FROM [TableName] T1
-- Pair up the duplicate rows
INNER JOIN [TableName] T2
O... | SQL Duplication across 2 fields | [
"",
"sql",
""
] |
Using Oracle PL/SQL, how can I populate the `bind variable :b3` with more than one value for the `IN clause`? (This code is for demo purposes only -- it may not compile but it does clarify the question if any is needed)
```
declare
type work_rec is record (
work_status varchar2(50),
work_cd ... | Better solution (at least to my issue) - don't use a bind variable but instead concatenate the string of values (code segment shown only):
```
for i in t_work_tab.first..t_work_tab.last
loop
sql_stmt := 'insert into employee_hist
select name,
employer
from tax_tabl... | When you loop through the values, keep appending the string with ' and , as required to make up the part of in. Then you can use that string as part of your sql statement.
Example
```
temp = "'"
Loop through values a,b,c,d as str
temp = temp + str + "'",
End Loop
temp = substr(temp,0,length(temp)) // this is to ... | How to put string of values with IN clause using dynamic PL/SQL? | [
"",
"sql",
"oracle",
"plsql",
""
] |
This is my table
```
create table #t(id int, amt int)
insert into #t values(1, 40), (1, 20), (1, 10), (2, 100), (2, 120), (2, 400)
```
I need output like this!
```
id amt
1 70
1 70
1 70
2 620
2 620
2 620
```
I tried
```
SELECT
id, SUM(amt)
FROM
#t
GROUP BY
id
``` | Try This !
```
select id,sum(amt) over(partition by id) as amt from #t
``` | ```
select id
, sum(amt) over (partition by id)
from #t
```
[Example at SQL Fiddle.](http://sqlfiddle.com/#!6/0ffd3/1/0) | Error querying SQL Server | [
"",
"sql",
"sql-server",
""
] |
My apologies in advance, this is probably a basic question asked and answered but I don't know how to word the search to find the right results.
I have a table that (among other columns) contains program names for a customer number. I need to identify customers that have only one specific program and no others. A simp... | In standard (ANSI/ISO) SQL, a *derived table* is your friend. Here, we join the customer table against a derived table that produces the list of customers having only 1
```
select *
from customer c
join ( select customer_id
from customer
group by customer_id
having count(program_name) = 1
) t... | Perhaps something like this:
```
select Customer_Number, Program_Name
from YourTable t1
left join (
select Customer_Number
from YourTable t2
where t2.Program_Name <> '2013BA1111'
) t3 on t1.Customer_Number = t3.Customer_Number
where
t1.Program_Name = '2013BA1111'
and t3.Customer_Number is null
```
The ou... | Select Records With Only One Value In A Column Where Multiple Are Possible | [
"",
"sql",
"teradata",
""
] |
How do I accomplish the following in the most efficient manner in SQL?
```
SELECT FIELD1, FIELD2, FIELDN ... FROM TABLE1 WHERE FIELD1 =
(the row with the max value from an aggregate query)
```
For example
```
SELECT * FROM PS_DEPT_TBL WHERE DEPTID =
...
SELECT DEPTID, COUNT(*) FROM PS_JOB GROUP BY DEPTID ORDER BY 2... | As a literal answer to your question, see the below.
However, having knowledge of peoplesoft, I question what you're trying to do with that query, because ps\_job contains effective dated rows. It will contain one row for every single change to an employee's job over time. The same employee might have 50 rows on it. S... | Order the query by the value you want to min\max by, and use `LIMIT 1` or `TOP 1`(depends on your DB). | How do I do a simple "select x where it's value of y is the max in z"? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have two tables, `room` and `message`, in a chat database :
```
CREATE TABLE room (
id serial primary key,
name varchar(50) UNIQUE NOT NULL,
private boolean NOT NULL default false,
description text NOT NULL
);
CREATE TABLE message (
id bigserial primary key,
room integer references room(id),... | Try performing the grouping in a subquery:
```
select m.id, m.number, m.last_created, r.name, r.description, r.private
from (
select m.room as id, count(*) number, max(created) last_created
from message m
where author=$1
group by room
) m
join room r
on r.id = m.id
order by m.last_created desc l... | Maybe use a join?
```
SELECT
r.id, count(*) number_of_posts,
max(m.created) last_created,
r.name, r.description, r.private
FROM room r
JOIN message m on r.id = m.room
WHERE m.author = $1
GROUP BY r.id
ORDER BY last_created desc
``` | Avoid useless subqueries or aggregations when joining and grouping | [
"",
"sql",
"postgresql",
"postgresql-9.2",
""
] |
I have big DB. It's about 1 mln strings. I need to do something like this:
```
select * from t1 WHERE id1 NOT IN (SELECT id2 FROM t2)
```
But it works very slow. I know that I can do it using "JOIN" syntax, but I can't understand how. | Try this way:
```
select *
from t1
left join t2 on t1.id1 = t2.id
where t2.id is null
``` | First of all you should optimize your indexes in both tables, and after that you should use join | How to make SQL query faster? | [
"",
"mysql",
"sql",
"performance",
"cpu-load",
""
] |
I use the following
```
select TotalCredits - TotalDebits as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
```
this returns one field with my differenc... | ```
select ISNULL(TotalCredits,0) - ISNULL(TotalDebits,0) as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
``` | Change your query to conditional aggregation and it fixes the problem:
```
select sum(case when credit = 1 then TotalAmount else -TotalAmount end) as Difference
from Journal
where memberid = 48 and (credit = 1 or debit = 1);
```
EDIT:
If you have the case where credit and debit could both be 1, then use:
```
select... | Subtracting Two Column With Null | [
"",
"sql",
"sql-server",
""
] |
Like the title already explained, I'm struggling with my `WHERE` clause in my SQL stored procedure.
I got a `SELECT` query which joins multiple tables well and at the end if got a `WHERE` clause that give specific values to search for.
My problem is that I want to expand this stored procedure for 2 different `WHERE` ... | You can do that with a CASE:
```
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN =
CASE WHEN @TEMPVAR = '' THEN 123
ELSE 456
END
```
or directly in the `WHERE` clause with an `OR`:
```
WHERE (@TEMPVAR = ''
AND man.Klant_ID=@Klant
AND (@ManID = 0 OR man.ID... | You can do this with directly logic in the `where`:
```
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 123 and @TEMPVAR = '' or
TABLE_X.FIRSTCOLUMN = 456 and @TEMPVAR <> ''
```
If `TEMPVAR` can be `NULL`, then:
```
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE... | SQL Server : Where clause inside IF .. ELSE | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have a Database with two tables:
```
subscriber_mm
uid_local | uid_foreign | uid_partner
7 |2 |0
7 |4 |0
2 |1 |0
2 |2 |0
5 |1 |0
5 |3 |0
partner_mm
u... | Here pass a value instead of 2 for your query :
```
select sum(total_count ) as total_count from
(select count(*) as total_count from subscriber_mm s where s.uid_local=2
union all
select count(*) as total_count from partner_mm m where m.uid_local=2) as a
```
or
```
select a.uid_local,sum(total_count ) as total_c... | No need of doing SUM since you need only to count the total number of rows returned from both tables for particular `uid_local`. The total rows can be obtained by using `UNION ALL` operator which clubs the resultset returned from both the tables **WITHOUT** removing the repeated records
```
Select count(*) as Result F... | Sum rows of two tables | [
"",
"sql",
"sum",
""
] |
I've been using Entity Framework 6 code first to do some simple CRUD operations on my domain model and it's performed admirably so far.
I've now come across a situation where I'm performing a reasonably complicated query which involves filtering and paging of the results. The query generated by EF 6 is pretty bad and ... | As @Jim Wooley highlighted, I do not have a full text index on the columns that I am attempting to do partial matches on. Given that the view is very large this means that every row is being compared without the aid of an index. I have not yet tested these queries on a view with text indexing enabled so cannot say for ... | I noticed in your EF query you call `ToUpper`, however you are not doing this in your manual query. If `RegNumber` is an indexed field, passing it to SQL's `UPPER` function before doing your comparison will make it unable to use that index. This is probably the reason the performance is worse.
You probably have the `T... | Options to replace slow SQL generated by Entity Framework 6 | [
"",
"sql",
"sql-server",
"performance",
"entity-framework",
""
] |
Is it possible to **"nest"** qualify statements in Teradata?
I have some data that looks like this:
```
event_id = 1:
user_id action_timestamp
971,134,265 17mar2010 20:16:56
739,071,748 17mar2010 22:19:59
919,853,934 18mar2010 15:47:49
919,853,934 18mar2010 15:55:21
919,853,934 18mar2010 16:01... | This seems to accomplish what I want:
```
SELECT *
FROM
(SELECT *
FROM table
WHERE ...
QUALIFY (MAX(action_date) OVER (PARTITION BY user_id, event_id) = action_date)
) AS a
QUALIFY (
MIN(a.action_date) OVER (PARTITION BY a.user_id) = a.action_date
)
``` | How is this query failing?
Of course you can use multiple conditions in a QUALIFY, your query is syntactically correct.
But it's logic will not return a row for the given data :-)
You probably need to rewrite it, maybe
```
QUALIFY (
RANK() OVER (PARTITION BY user_id ORDER BY event_id) = 1
)
``` | Nesting qualify statements in Teradata | [
"",
"sql",
"teradata",
""
] |
The query which i have written
```
SELECT Date_current,
COUNT(*) as'Total'
FROM Call_Register
WHERE (DATEDIFF(dd,'02/1/2014',Date_current) >=0)
AND (DATEDIFF(dd,'02/12/2014',Date_current) <=0)
GROUP BY Date_current
HAVING COUNT(*)>=(convert(int,'02/12/2014')) \
ORDER BY Date_curre... | Firstly, you should either use the culture invariant date format `yyyyMMdd`, or explicitly set the date format using `SET DATEFORMAT DMY`, or prepare to get inconsistent results.
Secondly, the following is potentially very inefficient:
```
WHERE (DATEDIFF(dd,'02/1/2014',Date_current) >=0)
AND (DATEDIFF(dd,'02/12/... | You need to Cast your String Date after that only you can proceed with Int CAST
```
CAST('02/12/2014' AS Datetime)
```
Try this
```
SELECT Date_current,COUNT(*) AS 'Total'
From Call_Register
WHERE (DATEDIFF(dd,'02/1/2014',Date_current)>=0) AND
(DATEDIFF(dd,'02/12/2014',Date_current)<=0)
Group By Date_cur... | I want output of sql Query and i already done some query part but it fails | [
"",
"sql",
"sql-server-2008",
""
] |
I created the procedure listed below:
```
CREATE procedure getdata
(
@ID int,
@frm varchar(250),
@to varchar(250)
)
AS
BEGIN
DECLARE @SQL nvarchar(500)
set @SQL = 'select'
set @SQL = @SQL + ' EmpName, Address, Salary from Emp_Tb where 1=1 '
IF (@ID <> '' and @ID is not null)
Begin
SET @s... | You are trying to concatenate a string and an integer.
You need to [cast](http://msdn.microsoft.com/en-us/library/ms187928.aspx) `@ID` as a string.
try:
```
SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))
``` | Try Using
```
CONVERT(nvarchar(10),@ID)
```
This is similar to cast but is less expensive(in terms of time consumed) | Conversion failed when converting the nvarchar value ... to data type int | [
"",
"sql",
""
] |
I tried to change precision like this:
```
ALTER Table account_invoice ALTER amount_total SET NUMERIC(5);
```
But I get syntax error, so I'm clearly doing something wrong. What is the right syntax to change precision of numeric in PostgreSQL? | Try this:
```
ALTER Table account_invoice ALTER COLUMN amount_total TYPE DECIMAL(10,5);
```
`DECIMAL(X, Y)` -> X represents full length and Y represents precision of the number. | You can use this:
```
ALTER Table account_invoice ALTER amount_total SET DATA TYPE NUMERIC(5,Y);
```
where Y is your required level of precision. | PostgreSQL - change precision of numeric? | [
"",
"sql",
"postgresql",
"postgresql-9.2",
"alter-table",
""
] |
I need some help.
Lets say i have a table
```
ID Mark Transmition
1 Ford A
2 Ford A
3 Ford M
4 BMW M
5 BMW M
6 Ford A
```
And now i need to do a case when.
```
CASE WHEN mark = 'Ford' then 'Ford'
WHEN mark = 'Ford' and Transmition = 'A' then ' including Fords with automatic transmitions'
... | Query:
```
SELECT CASE WHEN mark = 'Ford' THEN 'Ford' END AS Mark,
COUNT(*)
FROM Table1 t
WHERE mark = 'Ford'
GROUP BY mark
UNION ALL
SELECT CASE WHEN mark = 'Ford' AND Transmition = 'A'
THEN 'including Fords with automatic transmitions' END AS Mark,
COUNT(*)
FROM Table1 t
WHERE mark = 'Ford'
AND Transm... | You can do it without `CASE` like this :
```
SELECT Mark, count(1) FROM car GROUP By Mark
UNION
SELECT 'Including '||Mark||' with automatic transmitions' as MM, count(1) FROM car WHERE Transmition = 'A' GROUP By MM;
```
Result:
```
| MARK | COUNT(*) |
|-------------------------... | SQL CASE WHEN, when i want an "including" row | [
"",
"sql",
"case",
"obiee",
""
] |
The table is a big table,millions of records.
Column X represents an item etc Table, chair... ...
Column Y has values which i would like to sum up.
Column Z would place the value if the row needs to be summed.
```
Table 1
ID Column X Column Y Column Z
1 X1 5 1
2 x1 ... | Try This
```
Select ID,X,Sum(Y)Over(Partition By X) AS YY,Z
From Table
``` | Try:
```
SELECT
T1.ID,
T1.X,
(
SELECT
SUM(T2.Y*T2.Z)
FROM
Table AS T2
WHERE
T2.ID = T1.ID
) AS YY,
T1.Z
FROM Table AS T1
``` | Summing record in table based on key in row | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am writing a shell script to scp a project and part of it involves transferring some important tables in my database.
I have the following stored in the file `SQLTableTransfer`:
```
.o MyTable1.sql;
.dump MyTable1;
.o MyTable2.sql;
.dump MyTable2;
.o MyTable3.sql;
.dump MyTable3;
```
And took a chance on
```
$ ... | The parameter you give to the `sqlite3` program is the database file name.
To execute commands from a file, you must redirect the input to that file:
```
$ sqlite3 mydatabase.db < SQLTableTransfer
```
or tell it to read from that file:
```
$ sqlite3 mydatabase.db ".read SQLTableTransfer"
``` | For Windows CLI, assuming your database is loaded:
```
sqlite> .read C:\\somesubdir\\some.sql
``` | Running a Sqlite3 Script from Command Line | [
"",
"sql",
"bash",
"sqlite",
"shell",
""
] |
This request is extracted from a complex one.
In this example I have two data tables: user\_table, ref, and one association table: user\_ref\_asso.
The schema, and test query are here : <http://sqlfiddle.com/#!4/0a302/18>
I try to limit the number of USER\_TABLE results using "where rownum < X" but it limits the tot... | Use Analytical function to achieve this:
```
select user_id, ref_id, name, ref from
(SELECT u.user_id, r.ref_id, u.name, r.ref, dense_rank() over (order by u.user_id) rn
FROM user_table u
INNER JOIN user_ref_asso ur
ON ur.user_id = u.user_id
INNER JOIN REF r
ON r.ref_id = ur.ref_id
order by u.use... | The simplest solution, however not nice:) is:
```
select * from
(SELECT u.user_id, r.ref_id, u.name, r.ref
FROM (select * from user_table WHERE rownum <= 2) u
INNER JOIN user_ref_asso ur
ON ur.user_id = u.user_id
INNER JOIN REF r
ON r.ref_id = ur.ref_id
order by u.user_id, r.ref_id);
```
or in case of oracle yo... | Oracle SQL: Limit row numbers in a query with association table | [
"",
"sql",
"oracle",
"rownum",
""
] |
```
select * from table (Return 10 columns)
```
or
```
select fild_a, fild_b from table
```
That makes any difference, talking about performance? | The difference in performance Marcelo refers to is afaik true, but miniscule at best.
More to the point, using asterisks results in an unreliable result set, since any changes to the data model will be reflected in the result of the query, which may potentially break any existing code that's using that query.
Also, t... | The first Query select fild\_a, fild\_b from table is faster than
second select \* from table (Return 10 columns) Query because
There are two basic rules of querying a database table:
1. Query only the rows that you need.
2. Query only the columns that you need.
By doing "SELECT \* FROM table ", you are retreiving al... | SQL Performance on Select | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
here is my situation:
I have 3 tables:
```
A: (A_id, Name)
B: (B_id, A_id, Name)
C: (C_id, B_id, State)
```
What i want is to have the following resultset:
```
A.A_id,A.Name, C.State
```
the complicator is that i need State to have a default value when there is no B data to link.
In that case, i want
```
A.A_id... | ```
select
coalesce(c.State, 'default value')
from
a
left join b on a.id = b.A_id
left join c on b.B_id = c.B_id
```
* the best visual explanation of joins I've ever seen: [A Visual Explanation of SQL Joins](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html)
* `COALESCE()` returns the fir... | ```
SELECT A.A_id, A.Name, COASLESCE(C.State, 'Default_Value')
FROM
A LEFT JOIN
(B INNER JOIN C ON C.B_id = B.B_id)
ON B.A_id = A.A_id
```
Some information on joins: [What is the difference between "INNER JOIN" and "OUTER JOIN"?](https://stackoverflow.com/questions/38549/difference-between-inner-and-... | How to get values from tables A and C, joined by table B with default values from C when C has no key from A | [
"",
"sql",
""
] |
I have some look up tables that I don't want to do a join for, but I still want the fields value.
TABLES
Table1
```
ID Value LookupID
1 1 1
2 2 2
```
Table2
```
LookupID Result
1 Yes
2 No
```
I'd like to do something like
```
SELECT ID, Va... | Try this:
```
SELECT ID, Value, case when LoopupID =1 then 'yes' else 'no' end as result
FROM Table1
``` | Just adding a little more information here...
The case syntax will work for three or more values, as well.
Also, you can name the resultant column with an "as"
and that name will go after the "end" in the case clause.
Like this:
```
case
when LookupID = 1 then 'Yes'
when LookupID = 2 then 'Maybe'
else 'No'
end as Y... | SQL selecting specific field with defined values | [
"",
"sql",
"syntax",
""
] |
I need help to get my syntax-correct in a SQL query, I want to use `Substring` and `convert`, but in the convert I also convert the date into format 112.
```
where Substring(Convert(varchar(100),Datum,12,16,112)) = '8:00'
```
My code above.
EDIT Explanation
I've wrote a stored procedure that stores data in one plac... | Do your `CONVERT` first, then wrap that in the `SUBSTRING`
```
WHERE Substring(Convert(varchar(100),Datum,112),12,16) = '8:00'
``` | Firstly you must do Convert(varchar(100),Datum,112) and then put it in Substring. Try like this;
```
WHERE Substring(Convert(varchar(100),Datum,112),12,16) = '8:00'
``` | Convert and substring in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am writing an analytic query on a user activity log table in Postgres 9.3. It has a sign-up date, a data field (that can be summed) and a user type. I've constructed some sample data/sql for this problem and I'm hoping to get some help figuring out the last part. The SQL required to test is below - it will drop/creat... | ```
select
coalesce(sum(data), 0) as "Sum",
to_char(date_trunc('week', c.signup_date), 'YYYY-MM-DD') as test_week,
c.record_type as user_type
from
facts f
right join
(
(
select distinct record_type
from facts
) f1
cross join
(
s... | To solve this problem, create a list of all combinations of all `record_type`s and all test weeks. The left join from those combinations to the actual fact table. This will give all the records, so you should be able to get the rows where there is no data:
```
select coalesce(sum(f.data), 0) as data, rt.record_type, w... | How to get all dates in sequence for a group by query? | [
"",
"sql",
"postgresql",
"group-by",
""
] |
I have some data that I would like to split based on a delimiter that may or may not exist.
Example data:
```
John/Smith
Jane/Doe
Steve
Bob/Johnson
```
I am using the following code to split this data into First and Last names:
```
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBST... | May be this will help you.
```
SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN(myColumn)
ELSE CHARINDEX('/', myColumn) - 1
END) AS FirstName
,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN... | For those looking for answers for SQL Server 2016+. Use the built-in STRING\_SPLIT function
Eg:
```
DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'
SELECT value
FROM STRING_SPLIT(@tags, ',')
WHERE RTRIM(value) <> '';
```
Reference: <https://msdn.microsoft.com/en-nz/library/mt684588.aspx> | T-SQL split string based on delimiter | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
""
] |
I have a table like this:
Table: `activity`
```
Date Time task_name type
10-02-2014 07:00 Reporting Scheduled
10-02-2014 1200 mailing Failed
10-02-2014 16:00 Checking Scheduled
11-02-2014 10:00 DDDD Done
```
I want to update a column named `type` from `Scheduled` to... | People don't half talk some nonsense around here. Consider the following...
```
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
, type VARCHAR(12) NOT NULL
);
INSERT INTO my_table (type) VALUES
('scheduled'),('failed'),('scheduled'),('done');
UPDATE my_table x
LEF... | Because of [documented limitation](http://dev.mysql.com/doc/refman/5.5/en/subquery-errors.html) of MySQL, you cannot use the same table for both the subquery FROM clause and the update target table.
You should then do something like this:
```
DECLARE @minTime time
SELECT @minTime = MIN(time) FROM activity WHERE date=... | Update data in table setting a particular date's minimum timing activity | [
"",
"mysql",
"sql",
""
] |
We have a very old software has been created around 10 years ago and we don't have source code.
The software uses two databases, `DB01` and `DB02` on the same SQL Server 2012 instance.
There is SQL statements such as `db01..table1 join db02..table2`, but the main issue is our processes don't allow us use `db02` as a ... | Create a database with the name you want to impersonate. Re-jigg the DDL code generator to create a view for every table in the database that has the tables I need to access via the hardcoded name. Basically, each view will have a statement that looks like this..
```
CREATE VIEW schemaname.tablename as SELECT * FROM t... | I had a similar issue.
Solved with this [workaround](http://www.baud.cz/blog/database-alias-in-microsoft-sql-server), using synonyms.
**Short version:** You flood your database with a synonym of every object you'll ever need to reference. Later you re-create every synonym with the other database name. | How to create an alias of database in SQL Server | [
"",
"sql",
"sql-server",
"database",
"alias",
"synonym",
""
] |
I want a select that naturally joins 2 tables. Afer joining table A with table B the new temporary table C doesn't contain the row of table A if the primary key of this row is not used in any rows of table B. I understand why that happens, but I want the row also in table C.
Example
```
select deptno, dname, loc, cou... | Thanks a lot, it was the outer join I was looking for.
So here's the sql command that deliveres the result I was looking for:
SQL99-Syntax:
```
select deptno, dname, loc, nvl(ecount,0) empcount, nvl(round(avg(sal),2),0) avgsal
from dept left join emp using(deptno)
left join (select deptno, count(deptno) ecount
... | Use `left join` instead fo `natural join`.
```
select deptno, dname, loc, count(deptno) empcount, round(coalesce(avg(sal), 0),2) avgsal
from dept left join emp
group by deptno, dname, loc
``` | SQL join without data loss | [
"",
"sql",
"oracle",
""
] |
I have been assigned with the task of getting part numbers out of a string in our database. I know that the part will be between the first and second comma in the string but I have no idea how to go about doing this. Any one have any suggestions? This is an example of the string I will be working with LEL,SPEC2078,14 C... | assuming the partno is in a column called p and the name of your table is products:
```
select SUBSTRING(p, charindex(',',p,1)+1, case when charindex(',',p,charindex(',',p,1)+1) = 0 then len(p)-charindex(',',p,1) else charindex(',',p,charindex(',',p,1)+1) end)
from products
``` | No problem! Might be best to write a function if you have to do this for several different items inside a CSV string.
```
SELECT 'LEL,SPEC2078,14 CUT LEADS,#18 1/32'
SELECT SUBSTRING('LEL,SPEC2078,14 CUT LEADS,#18 1/32',1,CHARINDEX(',','LEL,SPEC2078,14 CUT LEADS,#18 1/32',1)-1) -- Get's the first value
SELECT SUBSTRI... | Pulling text out of a string in SQL | [
"",
"sql",
"sql-server",
""
] |
This is the code I have to optimize, I managed to get it to half of the starting cost only with indexes and changing the LIKE for a SUBSTRING sentence. My problem is now with the sub-query in the last line, and the SUM lines in the select, I believe I have to get rid of those by creating a new table or column but can't... | Can't test it right now, but I think this should work:
```
SELECT c.LastName as Customer ,
e.LastName as SalesPerson,
s.ProductID,
p.Name as ProductName,
SUM(s.Quantity) as quantity,
SUM(p.Price * s.Quantity) as amount
FROM dbo.Sales s,
JOIN dbo.Customers c
ON c.Custome... | If using SQL Server you can streamline this a little with window functions:
```
WITH cte AS ( SELECT C.LastName AS Customer
, e.LastName AS SalesPerson
, s.ProductID
, p.Name AS ProductName
, SUM(s.Quantity) AS quantity
... | Query Optimization, (subquery) (sql-transact) | [
"",
"sql",
"query-optimization",
"having",
"subquery",
""
] |
TABLE1:
```
ARTIKEL SUPPLIERID SALE_SUM_PIECES
TV SONY 7
```
TABLE2:
```
ROW_ID ARTIKEL SUPPLIERID PIECES
1 TV SONY 6
2 TV SONY 10
3 TV SONY 6
4 ... | The below solution gives the desired results. See [SqlFiddle](http://sqlfiddle.com/#!6/1454c/1)
```
1 TV SONY 922 6 110 2.50 NULL
2 TV SONY 922 10 80 1.00 13
3 TV SONY 922 6 65 1.50 7
4 TV SONY 922 14 95 1.50 0
5 TV SONY 922 18 95 1.50 NULL
6 TV SONY 922 4 ... | I'm not 100% sure what the expected calulation for VALUE\_DRILL\_DOWN is supposed to be.
You've said that for a valid row, it should be (sum of all rows at or above row) - 23
In this case the following code should work, but it gives different numbers from your expected results.
I've used a self-joining common table e... | Nested CASE in SQL | [
"",
"sql",
"sql-server",
"select",
"case",
""
] |
I'm spinning in circles trying to figure out what is likely a very simple SQL structure. My task seems simple - within the same table I need to update 3 related records with data from one master record. The master coordinates are in the record with a class of 'T', and I want to insert that record's coordinates into the... | ## Updated
Try :
```
update yourTable t1, yourTable t2 set
t1.tx_latitude = t2.tx_latitude,
t1.tx_longitude = t2.tx_longitude
where t1.class = 'R' and t2.class = 'T' and t1.callsign = t2.callsign
```
[Example](http://sqlfiddle.com/#!2/0937d/1) | You can use UPDATE...FROM statement:
```
UPDATE theTable
SET
tx_latitude = masterRecord.tx_latitude,
tx_longitude = masterRecord.tx_longitude
FROM
(SELECT tx_latitude,tx_longitude,callsign FROM theTable WHERE class='T') masterRecord
WHERE
class='R' AND callsign = masterReco... | Update SQL records with values from another record | [
"",
"mysql",
"sql",
"insert",
""
] |
I have a query to calculate a sum over last 12 months like:
```
select part_no,
count(part_no) r12
from t1
where (t1.created<=sysdate and t1.created>=add_months(sysdate,-12)
```
Is it possible to create a query that also shows rolling 6 and rolling 3 in the same query like:
```
part_no r12 r6 r3
-------... | If you just want to know `COUNT` of all items for last 12, 6 and 3 you can change your query as follows.
```
SELECT part_no
,COUNT(CASE WHEN t1.created <= sysdate
AND t1.created >= add_months(sysdate, -12) THEN 1
ELSE NULL
END) r12
,COUNT(CASE WHEN... | You probably can try something like this:
```
SELECT part_no,
SUM( IF(t1.created>=add_months(sysdate,-12), 1, 0) ) r12,
SUM( IF(t1.created>=add_months(sysdate,-6), 1, 0) ) r6,
SUM( IF(t1.created>=add_months(sysdate,-3), 1, 0) ) r3
FROM t1
WHERE t1.created<=sysdate
GROUP BY part_no
``` | Same query with different parameters | [
"",
"sql",
"oracle",
"sum",
""
] |
EDIT:
Thanks to the responses, I have further cleaned up the code to the following:
```
SELECT
AllAlerts.AlertID as AlertID,
Queues.QueueID as QueueID,
Queues.QueueName as QueueName,
AllAlerts.ConnectorID as ConnectorID,
cast( ISNULL(STUFF ( (
select cast(',' as varchar(max)) + Services.La... | To illustrate a partial solution based on my comment:
```
from [ISG_SOI ].[dbo].[Alerts] AS AllAlerts
inner join [ISG_SOI ].[dbo].[QueueAssignment] as QA on QA.[AlertID] = AllAlerts.[AlertID]
inner join [ISG_SOI ].[dbo].[AlertQueues] AS Queues on Queues.[QueueID] = QA.[QueueID]
where Queues.QueueName = 'OCC'
```
Ins... | You are using a lot of nested SELECTS, which are slow because you may be evaluating the SELECTS for each upper level row. Rather use Common Table Expressions (CTE) which enable you to do your SELECT upfront.
```
WITH MyCTE AS (
SELECT distinct Services.Label
from [ISG_SOI ].[dbo].[SecureServiceCI] as Ser... | Can I Make This T-SQL Search Better? | [
"",
"sql",
"sql-server",
""
] |
I'm struggling with this piece of SQL and I was wondering if someone could help me out.
```
INSERT INTO table_1(
rec_1,
rec_2,
rec_3
)
VALUES (
val_1,
val_2,
val_3
)
```
Now, rec\_2 and rec\_3 are clear and have absolute values.
Rec\_1 is filled with values from another table. Now I want to insert the values fro... | How about a simple `INSERT/SELECT` if `rec_2` and `rec_3` are absolute values:
```
INSERT INTO table_1 (rec_1, rec_2, rec_3)
SELECT val_1, 'val_2', 'val_3'
FROM other_table
WHERE val_1 NOT IN (SELECT rec_1 FROM table_1)
``` | ```
INSERT INTO table_1(rec_1, rec_2, rec_3)
SELECT val_1, val_2, val_3 FROM dual WHERE NOT EXISTS (SELECT rec FROM table_2)
```
You might want to check this [answer](https://stackoverflow.com/a/2513187/2450409) for further usage
Further details [here](http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-le... | SQL insert query | [
"",
"mysql",
"sql",
""
] |
I have a list of values in a column 1, now I want to get the sum of next 5 row values or 6 row values like below and populate the value in appropriate column.

for example if you see 1st row value of the column 'next-5row-value' would be the sum of v... | for example if you have this simple table:
```
sebpa=# \d numbers
Table "public.numbers"
Column | Type | Modifiers
--------+---------+------------------------------------------------------
id | integer | not null default nextval('numbers_id_seq'::regclass)
i ... | You can try something like this:
```
SELECT V,
SUM(V) OVER(ORDER BY YourOrderingField
ROWS BETWEEN 1 FOLLOWING AND 5 FOLLOWING) AS next_5row_value,
SUM(V) OVER(ORDER BY YourOrderingField
ROWS BETWEEN 1 FOLLOWING AND 6 FOLLOWING) AS next_6row_value
FROM YourTa... | Grouping by a given number of row values | [
"",
"sql",
"postgresql",
"group-by",
"postgresql-8.4",
"greenplum",
""
] |
Why does the right outer join (of the example below) not give the full dataset of the table like the left outer join does, since outer joins always retain the rows of the corresponding table?
Create Table
```
create table join_test
(id number unique not null, name varchar2(10), department varchar2(10));
```
Popu... | Right and Left joins perform the same function. What's different in your examples is the tables that you are SELECTing from.
These two queries:
```
select j2.name,j2.department
from join_test j1 left join join_test j2
on(j1.department=j2.department and j1.name<>j2.name)
```
and
```
select j1.name,j1.department
from... | This produces the correct results in SQL Fiddle (sqlfiddle.com/#!4/1e7075/2). However, I have a suspicion. The returned results are:
```
NAME DEPARTMENT
stelios sa
andros sa
stav ba
mary ba
(null) (null)
(null) (null)
```
I suspect that however you are returning the results (or looking at them), the rows ... | Self join in SQL Oracle: Why does the right outer join not retain all the values of the table | [
"",
"sql",
"oracle",
"left-join",
"self-join",
"right-join",
""
] |
I have SQL table Policy that contains column as PolicyNumber which has value 'CCL-9997-10497'
and another table PolicyImages which also has column PolicyNumber which has value 'CCL-9997-000010497'
I wanted to inner join both these table on PolicyNumber ?
How can I achieve it ? | Your two tables have different format of PolicyNumber so you need some kind of computation.
I think below query will help you
```
SELECT a.* FROM
FROM Table1 a INNER JOIN Table1 b ON a.PolicyNumber =
Replace(b.PolicyNumber,'-' + right(b.PolicyNumber,charindex('-',REverse(b.PolicyNumber))-1),
'-' + convert(varchar,Con... | This should do it:
```
SELECT *
FROM Policy
INNER JOIN PolicyImageq ON Policy.PolicyNumber = PolicyImages.PolicyNumber
``` | Inner join tables | [
"",
"sql",
"inner-join",
""
] |
IN this SQL, it is only returning rows that had data in the col from the join table
(subst\_Instructions). But we want it to display the row from main table even if there is not data in the join. Now, its' because of the where SUBST\_INSTRUCTIONS is not null presumably.
but without that, it will not show the data from ... | Make sure not to have any fields of the outer joined table in the WHERE clause. Do [STAT] and [TIER] both belong to the main table? If they belong to the outer joined table, then put the criteria in the ON clause, not in the WHERE clause. | I would use full outer join instead of left outer join. | sql query only displays rows that have a match in the join | [
"",
"sql",
""
] |
I have a table that is time and milemarkers:
```
08:00 101.2
08:45 109.8
09:15 109.8
09:30 111.0
10:00 114.6
```
I need output that looks like this:
```
08:00-08:45 101.1-109.8
08:45-09:15 109.8-109.8
09:15-09:30 109.8-111.0
09:30-10:00 111.0-114.6
```
I figure I need 2 identical recordsets and somehow tie the firs... | Other way to do it is:
[SQLFiddle](http://sqlfiddle.com/#!3/20f9d/5/0)
```
select cast(A.TIME_COL as varchar) + ' - ' + cast(B.TIME_COL as varchar),
cast(A.MILES as varchar) + ' - ' + cast(B.MILES as varchar)
from (select row_number() OVER (order by time_col) ID, * from TABLE_A) A
inner join (select row_number... | The following query will get the next values:
```
select tm.*,
(select top 1 time
from timemilemarkers tm2
where tm2.time > tm.time
order by 1 desc
) as nexttime,
(select top 1 milemarker
from timemilemarkers tm2
where tm2.time > tm.time
order by 1 d... | querying SQL Server 2005 | [
"",
"sql",
"sql-server",
""
] |
I want to display one unique row from a table which have repeated number of rows with the same value. I have tried this sql query,
```
select
table1.activityhp, table2.id, table1.sequenceno
from
ServiceDataElementsNew as table1,
VerticalsumNew as table2
where
table1.verticalsumid = table2.id
```... | ```
**add to query**
group by table1.activityhp , table2.id ,table1.sequenceno
``` | Please try using [DISTINCT](http://www.w3schools.com/sql/sql_distinct.asp) keyword, which eliminates the duplicate entries.
```
select DISTINCT
table1.activityhp,
table2.id,
table1.sequenceno
from
EthioHIMS_ServiceDataElementsNew as table1,
EthioHIMS_VerticalsumNew as table2
where table1.v... | Display one unique row from sql database | [
"",
"sql",
"unique",
""
] |
So the short end of it is this is what I want to do, but I don't know the proper syntax.
Table 1, Table 2
Name, SSN, DOB, List, Date
I want to do a left join using the SSN, but when the SSN field IS NULL I want it to join on the DOB field Where the Name matches.
I can't join on name due to the file being 19k records... | I believe that you can do what you want with a simple `LEFT JOIN` and the correct JOIN conditions. The trick in Access is that **IT DOES NOT LIKE** left joins with too few parentheses. When in doubt, add more parentheses. You will be surprised at what it makes possible in Access.
```
SELECT
T1.*,
T2.*
FROM
(T... | Perhaps:
```
SELECT *
FROM Table7
INNER JOIN Table8
ON Table7.SSN = Table8.SSN
WHERE Table8.SSN Is Not Null
UNION
SELECT *
FROM Table7
INNER JOIN Table8
ON Table7.DOB = Table8.DOB
WHERE Table8.SSN Is Null
```
Note that the result will not be editable. | When field "IS NULL" join on an alternative field - Access 2007 | [
"",
"sql",
"if-statement",
"ms-access-2007",
"left-join",
""
] |
Suppose I have 3 tables
A:
```
---------------
id | name
---------------
1 | A
---------------
2 | B
---------------
```
B:
```
-----------------------
id | val | A_id
-----------------------
1 | 10 | 1
-----------------------
2 | 20 | 2
-----------------------
3 | 30 ... | Move the calculations into subselects:
```
select tablea.id, tablea.name, B.B_val, C.C_val FROM tablea
LEFT JOIN
(select tablea.id AS id, SUM(COALESCE(tableb.val,0)) as B_val
from tablea left join tableb on tablea.id = tableb.A_id
group by tablea.id) AS B ON tablea.id = B.id
LEFT JOIN
(select tablea.id AS id, SUM(COAL... | Split the query in two and then use those subqueries as data source for a third one:
```
-- The first query (it returns the sum of b.val)
select a.id, a.name, sum(b.val) as sum_b_val
from a left join b on a.id = b.a_id
group by a.id;
-- The second query (it returns the sum of c.val)
select b.a_id, sum(c.val) as sum_c... | I want to join 3 tables and aggregate records of two columns from 2 of those tables while avoiding record duplication | [
"",
"sql",
"postgresql",
""
] |
I have 2 tables that have identical structure:
`| term (varchar(50) utf8_bin) | count (bigint(11)) |`
One table is called "big\_table" and the other one "small\_table". Big table has ~10M rows and small\_table has 75k.
I want to update small\_table, so the count column will be filled from the big\_table.
I tried thi... | I think you only need a `JOIN`:
```
UPDATE small_table b
JOIN big_table c
ON c.term = b.term
SET b.counter = c.counter ;
``` | You don't need `WHERE` part at all:
```
UPDATE
small_table b
SET
counter =
ISNULL
(
(
SELECT c.counter
FROM big_table c
WHERE c.term = b.term
),
0
)
```
Think about this way:
`UPDATE` every row in... | Using JOIN in UPDATE query | [
"",
"mysql",
"sql",
""
] |
I have some mobile numbers stored in a Oracle DB. I have a stored procedure that carries out some checks around a variety of validations. The stored procedure is launched by a front end Windows application. One basic validation example is ensuring the mobile field is not null.
I'd like to add validation for: check the... | I don't think the other answers properly answer what s/he is asking. S/He says "*If the mobile number already stored on the DB is wrong, I just want to ignore it. Not correct it or modify it in any way. Simply if it doesn't meet the criteria, skip over it.*"
The other answers **do not** ignore invalid numbers, they al... | You can use `replace` function. E.g.,
```
select replace('188 123 4567',' ','') from dual;
```
result:
```
1881234567
```
Oracle Database SQL Reference for `replace` <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions134.htm>
See also "Using Regular Expressions in Oracle Database" <http://docs.oracle.... | Check string length & ignore whitespace | [
"",
"sql",
"oracle",
"stored-procedures",
"plsql",
""
] |
I am trying to get a list of IDs and their corresponding names out of a table. Using
```
select distinct cast([ctID] as int), [ctName]
FROM [tbl_CTResults]
```
I find that the name has changed over time. I have an additional column (`[statdate]`) that will allow me to know which is the latest name.
I tried using s... | You can do this using `row_number()`:
```
select cdid, ctName
from (select cast([ctID] as int) as ctid, [ctName],
row_number() over (partition by ctID order by startdate desc) as seqnum
FROM [tbl_CTResults]
) t
where seqnum = 1;
``` | ```
select *
from
(
select cast([ctID] as int), [ctName],
row_number() over (partition by ctID order by statdate desc) as rn
FROM [tbl_CTResults]
) as dt
where rn = 1
``` | selecting last used name | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
We have a table ta\_service with following data
## Ref\_id seq desc
2340 1 Service 1
2340 2 Offer 1
2340 3 Service 2
2340 4 Offer 2
2340 ... | ASE doesn't support UNION in any subqueries.
You can refer the [Sybase Documentation](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1510/html/iqrefbb/Convert.htm "example") | Here is the link to sybase manual which says UNION is not supported in subqueries:
<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36272.1570/html/commands/X56548.htm>
However I noticed that if we have the union clause within a derived table expression, then, it works fine. Here is the link... | Getting syntax error with Union sub query in Sybase DB | [
"",
"sql",
"union",
"sybase",
""
] |
I'm using MySQL 5.1 and I have two tables, projects and employee. There is a foreign key in employee (number\_project) that is the primary key of projects(code\_project).
---> Exactly: [SQL Fiddle](http://sqlfiddle.com/#!2/f54cd/3/0)
I'm trying get the SUM of the projects by department with this query:
```
SELECT em... | Use a subquery to create a list of unique `(department, project)` combinations:
```
select e.department_emp
, sum(p.price)
from (
select distinct department_emp
, number_project
from Employee
) e
join Projects p
on p.code_project = e.number_project
group by
... | SELECT emp.department\_emp AS Department, SUM( pro.price ) AS total\_department
FROM(SELECT DISTINCT \*
FROM employee AS emp, projects AS pro
WHERE emp.number\_project = pro.code\_project
) AS P
GROUP BY emp.department\_emp | MySQL - Group By SUM with two tables | [
"",
"mysql",
"sql",
"group-by",
"sum",
""
] |
I have a table named `A` that contains a column named `x`. What I'm trying to do is to count the number of items that belong to a certain subset of A (more precisely, the ones that satisfy the `x > 4` condition) via a single SELECT query, for example:
```
SELECT COUNT(*)
FROM A
WHERE x > 4;
```
From thereon, I'd like... | My server is down, not able to get sure of the answer below:
```
SELECT count(case when x > 4 then x else null end) / COUNT(*) FROM A;
```
Is a slight better because its just a count, not a sum (nulls ill not be accounted)
but i prefer to do:
```
select (SELECT count(*) FROM A where x > 4)/(SELECT count(*) FROM A);... | You want conditional aggregation:
```
SELECT sum(case when x > 4 then 1 else 0 end) / COUNT(*)
FROM A;
``` | Get ratio between the length of a table and one of its subsets via SQL | [
"",
"sql",
"postgresql",
""
] |
I have 2 tables - actual and proposed - as follows:
```
ACTUAL
Id|desc|Allocation|changeBit
1|X|20||
2|y|30||
PROPOSED
Id|desc|Allocation|changeBit
1|X|30|U|
3|z|40|I|
```
The sought result is as follows:
```
1|X|30|U|
2|y|30||
3|z|40|I|
```
A 'U' bit causes the reco... | I would be inclined to approach this with `union all` and `not exists`. I find the `coalesce()` or `isnull()` on the columns in the `full outer join` approach to be inelegant.
```
select Id, desc, Allocation, changeBit
from proposed
union all
select Id, desc, Allocation, changeBit
from actual a
where not exists (selec... | You should join both tables using a `full outer join`, and then use `coalesce` to get the actual value only when a proposed value does not exist:
```
SELECT COALESCE (p.id, a.id) AS id,
COALESCE (p.desc, a.desc) AS desc,
COALESCE (p.allocation, a.allocation) AS allocation,
... | Table join with overrides | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have 2 tables A and B with the same structure. I need to get each row from table A that are not present in table B, then insert them into a 3rd #temp table C.
Each table has 2 columns that need to be compared, Type and Step, the remaining columns are RowID, CreatedDate, CreatedUserID, ModifiedDate and ModifiedUserID... | SQL 2012 has the EXCEPT statement. Here's a trivial example.
```
CREATE TABLE #TmpA (
Col Varchar(10),
Irrelevant Int );
CREATE TABLE #TmpB (
Col Varchar(10) );
CREATE TABLE #TmpC (
Col Varchar(10) );
INSERT INTO #TmpA
SELECT 'A', 0 UNION ALL
SELECT 'B', 7 UNION ALL
SELECT 'C', 5 ;
INSERT INTO #TmpB
SEL... | ```
insert into #temp3 (Type, Step, RowID ..)
select #temp1.Type, #temp1.Step, #temp1.RowID
from #temp1
left outer join #temp2
on #temp1.Type = #temp2.Type
and #temp1.Step = #temp2.Step
where #temp2.Type is null
``` | SQL Compare 2 #temp tables and insert the differences into a 3rd #temp table | [
"",
"sql",
"t-sql",
"compare",
"sql-server-2012",
""
] |
For example I have 2 tables:
users
```
+----+
| id |
+----+
| 0 |
| 1 |
| 2 |
| 3 |
+----+
```
payments
```
+---------+--------+------+
| user_id | amount | case |
+---------+--------+------+
| 0 | 10 | 1 |
| 0 | 1 | 2 |
| 2 | 5 | 1 |
| 2 | 4 | 1 |
| 2 ... | Try this
```
SELECT
u.id AS user_id,
SUM(CASE WHEN p.`case` = 1 THEN p.amount ELSE 0 END) AS total_amount_case_1,
SUM(CASE WHEN p.`case` = 2 THEN p.amount ELSE 0 END) AS total_amount_case_2
FROM
users u
LEFT JOIN payments p ON u.id = p.user_id
GROUP BY u.user_id
ORDER BY u.user_id ;
``` | You can do this with conditional aggregation -- using the `case` statement in an aggregation function:
```
SELECT u.id AS user_id,
SUM(case when p.`case` = 1 then p.amount else 0 end) AS total_amount_case1,
SUM(case when p.`case` = 2 then p.amount else 0 end) AS total_amount_case2
FROM users u LEFT JOIN ... | SQL SUMed up data with clause | [
"",
"mysql",
"sql",
""
] |
I am working with visitor log data and need to summarize it by IP address. The data looks like this:
```
id | ip_address | type | message | ...
----------+----------------+----------+----------------
1 | 1.2.3.4 | purchase | ...
2 | 1.2.3.4 | visit | ...
3 | 3.3... | I think this should be what you need:
```
SELECT yourtable.*
FROM
yourtable INNER JOIN (
SELECT ip_address,
MAX(CASE WHEN type='purchase' THEN id END) max_purchase,
MAX(CASE WHEN type='visit' THEN id END) max_visit
FROM yourtable
GROUP BY ip_address) m
ON yourtable.id = ... | The following query gets the most recent `id` based on your rules by using a correlated subquery:
```
select t.ip_adddress,
(select t2.id
from table t2
where t2.ip_address = t1.ip_address
order by type = 'purchase' desc, id desc
limit 1
) as mostrecent
from (select distinc... | SQL group by with multiple conditions | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.