Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I don't understand why this query doesn't work.
I have a table which is full of rows where 3 of the column values are set to `NULL`.
But when I run the following query, it returns 0 (it should return 96)
```
SELECT COUNT(*) FROM SEAT WHERE BOOKED=null;
```
Do you know what I am doing wrong? | It depends on your database settings and the specific RDBMS you are using, but if you are using ANSI NULL syntax you cannot directly compare a value to NULL with an equality test (`=`) -- it will always fail.
Use `WHERE BOOKED IS NULL` instead. | You have to use `IS NULL` instead of `= null`
Since null technically isn't a value, you can't compare null using the `=` operator. | Checking tables for null returns 0 regardless | [
"",
"sql",
""
] |
I have a column in a table containing gene names. Example of gene names are dnaA, BN\_001,BN\_0023 etc...
I want to have all genes names that do not contain the underscore. The statement I used was this:
```
SELECT Gene from cds WHERE Gene NOT LIKE '%_%';
```
However, this does not return the correct names of ge... | The problem is that `_` is a placeholder in ther `like` statement of any single character.
Instead you can use
```
SELECT Gene from cds
WHERE instr(Gene, '_') = 0
``` | You should write
```
LIKE '%\_%' ESCAPE '\'
```
because \_ mean something in SQL, so you have to escape this by \ | SQL LIKE statement not working | [
"",
"mysql",
"sql",
""
] |
I am trying to write a Breeze query for the Northwind database to show orders that contain all three products that a user specifies. So if a user selects ProductID 41, 51, and 65 from drop downs, the query would return order id 10250.
This is just a sample scenario that I am looking to base another query on in a proje... | If you're still interested in doing this on the client, you can try the following Breeze query.
```
var listOfProductIds = [41, 51, 65];
var preds = listOfProductIds.map(function (id) {
return Predicate.create("OrderDetails", "any", "ProductID", "==", id);
});
var whereClause = Predicate.and(preds);
var query = En... | Sorry in my comment I said look at the `and()` method but in actuality for your use you needed to look at the `or()` method -
```
var p1 = breeze.Predicate("Product.ProductID", "==", 41);
var p2 = breeze.Predicate("Product.ProductID", "==", 51);
var p3 = breeze.Predicate("Product.ProductID", "==", 65);
var newPred = b... | Breeze - Writing complex query with multiple parameters from client | [
"",
"sql",
"entity-framework",
"breeze",
""
] |
I have two tables `trackings` and `responses`. I am running the query below to join the two tables based on the case/code\_2 columns.
Because there will sometimes be multiple records in the `response` table for every record in the `trackings` table, I only wanted one row returned, not duplicates for each row in the re... | You may do this with an awful subquery (not as performant, but)...
```
SELECT
T0.timestamp AS 'Creation Date',
T0.ipaddress, T0.code_1 AS 'Alias',
T0.code_2 AS 'Case ID',
COUNT(T0.ipaddress) AS each_amount,
T0.first,
(SELECT r.res_id from responses r
where r.case = T0.code_2
order by r.timestamp desc
... | This is untested, but moving the `responses` join into a Derived Table should work:
```
SELECT T0.timestamp AS 'Creation Date', T0.ipaddress, T0.code_1 AS 'Alias', T0.code_2 AS 'Case ID', COUNT(T0.ipaddress) AS each_amount, T0.first, MAX(T1.res_id) AS 'responses'
FROM `trackings` AS T0
LEFT JOIN
(
SELECT T1.cas... | Limiting rows returned in a left join in MySQL issue | [
"",
"mysql",
"sql",
"join",
"left-join",
""
] |
I have 2 tables (USERS and ACCOUNTS) with the following data in them:
**USERS**
```
UserID Name Account_Number
10 John Smith 13
20 Alex Brown 14
30 Mary Wade 34
```
**ACCOUNTS**
```
Account number Amount
13 40
34 30
14 ... | Please try:
```
select
Account_Number,
Name,
(select SUM(Amount) from ACOUNTS b where b.[Account number]=a.Account_Number) Total
from USERS a
order by Account_Number
``` | Remove your subquery.. It is returning more than one row..
```
SELECT U.USERID, U.NAME, SUM(A.AMOUNT) AS TOTAL_AMOUNT
FROM USERS U
INNER JOIN ACCOUNT A on U.ACCOUNT_NUMBER=A.ACCOUNT_NUMBER
GROUP BY A.ACCOUNT_NUMBER,U.USERID, U.NAME
ORDER BY SUM(A.AMOUNT) DESC;
```
[Fiddle](http://sqlfiddle.com/#!6/620d7/3) | ORA-01427: single-row subquery returns more than one row error | [
"",
"sql",
"oracle",
""
] |
How to get two values from string in PL/SQL, like this:
```
DECLARE
context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
paramA VARCHAR(50);
paramB VARCHAR(50);
BEGIN
paramA = ... -- expected value: Value1
paramB = ... -- expected value: Value2,Value3
dbms_output.put_line(context);
... | You can use something like:
```
DECLARE
context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
paramA VARCHAR(50);
paramB VARCHAR(50);
BEGIN
paramA := SUBSTR('param_a=Value1;param_b=Value2,Value3;',instr('param_a=Value1;param_b=Value2,Value3;','=',1,1)+1,instr('param_a=V... | ```
Hi Better way to do this kind of separation is by using REGEX(Regular Expressions).
PLease try this code it may help plus it will reduce the coding length too.
SET serveroutput ON;
DECLARE
context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
paramA VARCHAR(50);
paramB VARCHAR(50);
BEGIN
FOR ... | Splitting two semicolons separated params | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a database wherein I have the following columns:
```
id
name
date
time
item1
item2
item3
```
There are many 'names' but different 'id'. For each 'name', there are different 'date'. The 'date' may also duplicate. Under each 'date', there are different 'time'.
So an example data in the database is like this:
`... | Try
```
SELECT name, date, MAX(time) FROM mytable
GROUP BY name, date
ORDER BY name,date
```
Demo at <http://sqlfiddle.com/#!3/470ce/5/0> | ```
SELECT
`name`, `date`, MAX(`time`) AS last_checked
FROM your_table
GROUP BY `name`, `date`
``` | SQL Query how to get data | [
"",
"sql",
""
] |
Simple SQL query:
```
(select e.lastName as Name, count(o.orderid) as numOrd from
Employees e join Orders o on e.employeeid=o.employeeid
group by e.lastName)
```
and result
Buchanan 42
Callahan 104
Davolio 123
Dodsworth 43
My question is how to achieve in SQL something like that:
```
let queryResult =
(sele... | yes, but why not just something like:
```
select count(o.orderid) / count (distinct e.employeeid) AvgNumOrder
from orders
```
Derived tables, CTEs, Subqueries, Temp tables, tables variable all do what you ask, but none are needed. | Look at the [SQL Server Views](http://technet.microsoft.com/en-us/library/ms187956.aspx)
You can define view as
```
create view queryResult as
select e.lastName as Name, count(o.orderid) as numOrd from
Employees e join Orders o on e.employeeid=o.employeeid
group by e.lastName;
``` | Is it possible to encapsulate sql-select result? | [
"",
"sql",
"sql-server",
"select",
""
] |
I have the following SQL statement:
```
SELECT name, SUM(growth) AS sum_buy_price, SUM(recovery) AS sum_msrp, SUM(growth)+SUM(recovery) AS total
FROM orders
WHERE id = ?
GROUP BY name
```
My data is coming from a CSV file that I have no control over and either 'growth' or 'recovery' can be NULL in the data, but no... | ISNULL returns whether the argument passed is null (i.e., it is analogous to true or false). I suppose, what you need is IFNULL:
```
SELECT
name,
SUM(IFNULL(growth, 0)) AS sum_buy_price,
SUM(IFNULL(recovery, 0)) AS sum_msrp,
SUM(IFNULL(growth, 0))+SUM(IFNULL(recove... | The `SUM()` function ignores `NULL` values, so you don't need to change a `NULL` to a `0` in order for it to work properly.
If however, all values that you're aggregating are `NULL` and you want to return a `0` instead of `NULL` you can use `IFNULL()` or the more common `COALESCE()` to show `0` as the sum instead of `... | NULL to zero with ISNULL | [
"",
"mysql",
"sql",
""
] |
I have the following column, `date_period2` in my query which displays date in `yyyy-mm` format but as a string.
```
date_period2
201304
201305
201306
201307
```
How can i convert that to a DATE format so I can use it to get the working days of the specific month. So for example, `201304` would be converted to `04-20... | Just put the string in an unambiguous date format like `yyyy-mm-dd`:
```
SELECT
CONVERT(DATETIME,
SUBSTRING(date_period2,1,4) + '-'
+ SUBSTRING(date_period2,5,2) + '-01')
```
That will convert `201304` into `2013-04-01` which will convert directly to a `DateTime`.
**EDIT**
Since your source colum... | You can convert date\_period2 to a datetime data type with following logic.
Please change as per your need.
```
declare @i int
select @i = CONCAT('201305','01')
select CONVERT (datetime,convert(char(8),@i))
```
In `CONCAT('201305','01')` '01' will be constant, only '201305' will change. | How to convert a string into date format | [
"",
"sql",
"sql-server",
"date",
"ssms",
""
] |
```
st.executeUpdate("insert into groupperformance (Date,Gid,GName) values('"+yourDate+"',select Gid,GroupName from grouping)");
```
I use the above query for insert table values.In this table variable yourDate having the Current system Date.And I copy the data's from the table grouping.With out yourDate variable quer... | ```
st.executeUpdate(
"insert into groupperformance (Date,Gid,GName)
select '" + yourDate + "', Gid,GroupName from grouping"
);
```
But, make sure that `yourDate` string is in valid MySQL date format `YYYY-MM-DD`.
And, if you want to insert current date from the database server, you can use `now()` or ... | You can use `SELECT GETDATE() AS CurrentDateTime`, which will return `2008-11-11 12:45:34.243`
OR
something like this:
```
CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)
``` | Inserting Current Date as default in MySQL table | [
"",
"mysql",
"sql",
""
] |
I have this table with this data
```
DECLARE @tbl TABLE
(
IDX INTEGER,
VAL VARCHAR(50)
)
--Inserted values for testing
INSERT INTO @tbl(IDX, VAL) VALUES(1,'A')
INSERT INTO @tbl(IDX, VAL) VALUES(2,'A')
INSERT INTO @tbl(IDX, VAL) VALUES(3,'A')
INSERT INTO @tbl(IDX, VAL) VALUES(4,'B')
INSERT INTO @tbl(IDX, VAL) ... | If the `idx` values are guaranteed to be sequential, then try this:
```
Select f.val, f.idx first, l.idx last
From @tbl f
join @tbl l
on l.val = f.val
and l.idx > f.idx
and not exists
(Select * from @tbl
Where val = f.val
and idx = l.idx +... | A way to do it - at least for SQL Server 2008 without using special functionality would be to introduce a helper table and helper variable.
Now whether that's actually possible for you as is (due to many other requirements) I don't know - but it might lead you on a solution path, but it does look to solve your current... | Pull out first index record in each REPEATING group ordered by index | [
"",
"sql",
"sql-server",
"group-by",
"gaps-and-islands",
""
] |
I have pored over numerous questions and answers but can't seem to find a solution that works for me. Here is what I am trying to do:
Say I have table called "Store" that holds Store IDs, store names, and the annual sales of that store. The business wants each store to increase it's sales by 50% over the next year, an... | In `Sql` you really should try to *avoid using loops*. Instead, you should use a set-based approach. [This post](https://stackoverflow.com/questions/5912346/type-of-loops-in-sql-server) (first answer) has a good link on why you shouldn't do it, then an example that could help you do it. Take a look at using a [CURSOR](... | The T-SQL below shows how to really easily get the sales targets for each store for each month. I've included two columns here: one called 'salesTargetYourExample' where we have a pattern like 1042, 1084, ... for sales targets and one called 'linearGrowthSales' where we have the new annual sales target (e.g. 1500 for t... | How can I do loop within a loop in SQL, similar to a for-each loop? | [
"",
"sql",
"loops",
"t-sql",
"database-cursor",
""
] |
I need to remove some attributes from a json type column.
The Table:
```
CREATE TABLE my_table( id VARCHAR(80), data json);
INSERT INTO my_table (id, data) VALUES (
'A',
'{"attrA":1,"attrB":true,"attrC":["a", "b", "c"]}'
);
```
Now, I need to remove `attrB` from column `data`.
Something like `alter table my_ta... | **Update**: for 9.5+, there are explicit operators you can use with `jsonb` (if you have a `json` typed column, you can use casts to apply a modification):
Deleting a key (or an index) from a JSON object (or, from an array) can be done with the `-` operator:
```
SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb... | This has gotten much easier with PostgreSQL 9.5 using the JSONB type. See JSONB operators documented [here](http://www.postgresql.org/docs/9.5/static/functions-json.html#FUNCTIONS-JSONB-OP-TABLE).
You can remove a top-level attribute with the "-" operator.
```
SELECT '{"a": {"key":"value"}, "b": 2, "c": true}'::jsonb... | PostgreSQL: Remove attribute from JSON column | [
"",
"sql",
"json",
"postgresql",
"postgresql-json",
""
] |
I'm not even sure how exactly to ask this question so bear with me.
I have two tables, meets and locations, they are linked by the meet's 'loc' and the location's 'id'
I'm using this query:
```
$query = "SELECT * FROM meets LEFT JOIN locations ON locations.id=meets.loc ORDER BY date DESC";
$meets = mysqli_query(... | do not select \*, select the columns you need and rename them using the `as` key word like so
```
SELECT locations.id as loc_id, meets.id as meets_id, ... FROM meets LEFT JOIN locations ON locations.id=meets.loc ORDER BY date DESC
```
replacing `...` with other columns you would like to select and possible renames of... | You could alias the locations.id with a query like:
```
SELECT meets.*, locations.id AS loc_id FROM meets LEFT JOIN locations ON locations.id=meets.loc ORDER BY date DESC
```
You could add any other columns from `locations` that you might also need. You could further only select explicit columns from `meet` rather th... | Losing data when joining two tables in mysql? | [
"",
"mysql",
"sql",
""
] |
I've not posted here before so forgive me if this is incorrect or needs altering.
I'm currently trying to work on a way to split one table into two seperate tables after a certain row count.
So for example I have 2 columns of data with 2000 rows, I'd like to split that into two tables where the first table has the sa... | using ROWNUMER()
with FIDDLE <http://sqlfiddle.com/#!3/6230e/3>
```
-- First 1000
select * from
(SELECT ROW_NUMBER() OVER(ORDER BY Col1 asc) AS Row,
Col1, Col2
FROM ur_table)d
where d.Row between 1 and 1000
-- Last 1000
select * from
(SELECT ROW_NUMBER() OVER(ORDER BY Col1 asc) AS Row,
Col1, Col2
FROM u... | I might use this approach. Please comment if you need explanation of any of the operations.
```
CREATE TABLE #TableA (Col1 INT)
CREATE TABLE #TableB (Col1 INT)
INSERT INTO #TableA (Col1)
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5
DELETE #TableA
OUTPU... | Split Table rows over two Tables | [
"",
"sql",
"sql-server",
""
] |
I'm using Rails 4.0.4 with Ruby 2.1 and Thin 1.6.2 on Ubuntu 14.04 through my terminal "Terminator" and my shell "Fish Shell".
When I'm launching my Rails server in development mode I don't have the SQL queries in my logs only the JS and HTML files are loaded.
I'm searching for something like that:
```
User Load (3.... | the rails console never writes to the log file, but you can achieve it quite easily, for example, if you execute following after starting the rails console
```
ActiveRecord::Base.logger = Logger.new STDOUT
```
rails will log all SQL statements to stdout, thus display them in your terminal. and since Logger.new accept... | Set `config.log_level` in config/environments/development.rb to `:debug` and restart your local server, console:
```
config.log_level = :debug
``` | Display SQL queries in log with Rails 4 | [
"",
"sql",
"ruby-on-rails",
"ruby-on-rails-4",
""
] |
I am new to SQL Server/used to MySQL databases and I am running into an issue that I never ran into with MySQL. I am looking to pull all current policy numbers, the name of the company/person it belongs to, their total premium, and whether or not they have what we call 'equipment breakdown' coverage. This is all pretty... | You'll need an aggregate function on the fields you don't want to group by. A simple one to use is `MAX` which works with most types;
```
SELECT pol_num as policy_number,
MAX(insd_name) as insureds_name,
SUM(amt) as 'total_premium',
(SELECT
CASE
WHEN MAX(cvg_desc) = 'Equipment Breakdown'
THE... | MySQL doesn't require all non-aggregate fields to be included in the `GROUP BY` clause, even though not doing so can yield unexpected results. SQL Server requires this, so you are forced to decide how you want to handle multiple `insd_name` values for a given `pol_num`, you can use `MAX()`, `MIN()`, or if the values ar... | Group by T-SQL vs. MySQL (single column) | [
"",
"sql",
"sql-server",
"t-sql",
"group-by",
"aggregate",
""
] |
I need to search for and display a part of a string field. The string value from record to record may be different. For example:
---
Record #1
String Value:
```
IA_UnsafesclchOffense0IA_ReceivedEdServDuringExp0IA_SeriousBodilyInjuryN
```
---
Record #2
String Value:
```
IA_ReasonForRemovalTIA_Beh_Inc_Num1392137... | This would work:
```
SELECT
CASE WHEN instr(value, 'IA_Beh_Inc_Num') > 0
THEN substr(substr(value, instr(value, 'IA_Beh_Inc_Num'), 25),15,10)
ELSE 'not found'
END AS result
FROM example
```
See this [SQL Fiddle](http://sqlfiddle.com/#!4/b9c0ed/9/0). | This should be easy with a Regular Expression: find a search string and check if it's followed by 10 digits:
```
REGEXP_SUBSTR(col, '(?<=IA_Beh_Inc_Num)([0-9]{10})')
```
but Oracle doesn't seem to support RegEx *lookahead*, so it's bit more complicated:
```
REGEXP_SUBSTR(value, '(IA_Beh_Inc_Num)([0-9]{10})',1,1,'i',... | Search for substring, return another substring | [
"",
"sql",
"oracle",
"substr",
""
] |
Ok so I have searched for an answer to this on Technet, to no avail.
I just want to print an integer variable concatenated with two String variables.
This is my code, that doesn't run:
```
print 'There are ' + @Number + ' alias combinations did not match a record'
```
It seems like such a basic feature, I couldn't ... | ```
declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */
``` | If you don't want to manually cast types, you can use the [`CONCAT`-function](https://learn.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql) for this.
```
PRINT CONCAT('There are ', @Number, ' alias combinations did not match a record')
``` | Printing integer variable and string on same line in SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Assume I have two tables:
1. users

2. sells

I need to alter this query: **Show top three users who bought copies of software**
My SQL is this:
```
select u.name, u.age... | Try this
```
select u.usrid, u.name, count(s.sellid)
from users u left join sells s on u.usrid=s.selluid
group by u.usrid, u.name order by count(s.sellid) desc;
``` | ```
SELECT x.*
FROM (
SELECT u.name
, u.age
, u.sex
, u.email
, s.selluid
, COUNT(*) as t
FROM users u JOIN sells s ON u.usrid = s.selluid
GROUP BY u.name
ORDER BY COUNT(*) DESC
) x
WHERE ROWNUM <= 3
``` | max(count(*)) Error: single-group group function | [
"",
"sql",
"database",
"oracle",
"group-by",
"oracle10g",
""
] |
Given these 2 table:
Users:
```
Name UserId
-----------
Pump 1 1
Pump 1 2
Pump 1 3
Pump 2 4
Pump 2 5
Pump 2 6
```
Posts:
```
PostId UserId Score
1 3 5
2 1 8
3 3 3
4 1 2
5 2 8
6 2 1
```
How do I get ... | Query:
**[SQLFIDDLEExample](http://sqlfiddle.com/#!2/62a4fb/6)**
```
SELECT u.Name,
u.UserId,
p.PostId,
p.Score
FROM Users u
JOIN Posts p
ON p.UserId = u.UserId
LEFT JOIN Posts p1
ON p1.UserId = p.UserId
AND p1.Score > p.Score
WHERE p1.Score is null
```
Result:
```
| NAME | US... | If you're using SQL-Server you can use a ranking function like `ROW_NUMBER` or `DENSE_RANK`:
```
WITH CTE AS
(
SELECT u.UserId as UserID, p.PostId as PostsID, p.Score,
RN = ROW_NUMBER() OVER (PARTITION BY u.UserId ORDER BY Score DESC)
FROM dbo.Users u
INNER JOIN dbo.Posts p on p.UserId = u.UserId
)
SEL... | Get the Post with highest score for each user | [
"",
"mysql",
"sql",
"sql-server",
"database",
""
] |
As I can understand [documentation](https://www.postgresql.org/docs/current/indexes-unique.html) the following definitions are equivalent:
```
create table foo (
id serial primary key,
code integer,
label text,
constraint foo_uq unique (code, label));
create table foo (
id serial primary key,
... | I had some doubts about this basic but important issue, so I decided to learn by example.
Let's create test table *master* with two columns, *con\_id* with unique constraint and *ind\_id* indexed by unique index.
```
create table master (
con_id integer unique,
ind_id integer
);
create unique index master_uni... | One more advantage of using `UNIQUE INDEX` vs. `UNIQUE CONSTRAINT` is that you can easily `DROP`/`CREATE` an index [`CONCURRENTLY`](http://www.postgresql.org/docs/9.3/static/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY), whereas with a constraint you can't. | Postgres unique constraint vs index | [
"",
"sql",
"postgresql",
"indexing",
"unique",
""
] |
I have two tables. An account table and a transactions table. I want to list all accounts with their **last transaction**. Need a left join since cases may exist with no transaction.
I have something like
```
select * from Account ac left join Transaction trans on ac.id = trans.acc_id
```
But that will list all the ... | the first left join gets you the last\max transaction ID for the account. The second left join gets you all the transaction information for that last ID.
```
select ac.*, lasttrans.*
from Account ac
left join (select acc_id, max(id) as id from Transaction group by acc_id) transmax
on ac.id = transmax.acc_id
lef... | You can try by joining the Account table with only those acc\_ids of your Transaction table that correspond to the maximum ID per acc\_id:
```
select ac.*, t.* from Account ac left join (select acc_id, max(id) from Transaction group by acc_id) trans on ac.id = trans.acc_id left join Transaction t on trans.id=t.i... | SQL Left Outer Join with a One to Many Row | [
"",
"sql",
"oracle",
""
] |
I have created an user defined functions in SQL server. Is it possible to call these function in select statement, just like any other built-in function?
```
Create function [dbo].[TIME_TO_SEC](@inputTime time)
returns INT
As
Begin
DECLARE @secDiff INT = datediff(second, '00:00:00', @inputTime)
return @secDif... | It's possible, but you need to reference the function by the user's schema
```
select dbo.TIME_TO_SEC('01:00:00') from TimeTable
``` | if you get an issue with your function, try to add "WITH EXECUTE AS CALLER"
```
Create function [dbo].[TIME_TO_SEC](@inputTime time)
Returns int
WITH EXECUTE AS CALLER
As
Begin
DECLARE @secDiff INT = datediff(second, '00:00:00', @inputTime)
return @secDiff;
end
```
then call the function with select
```
sel... | Call User defined function as System Function in SQL server | [
"",
"sql",
"sql-server",
"sql-function",
""
] |
I have a table `OrderUser`
```
UserName | OrderNo
-----------------------
User1 | 1
User1 | 2
User1 | 3
User2 | 4
User2 | 5
```
I need the only the `userID` with min rows, meaning `user2` in this case.
Simple T-Sql statement is required because I will use the code in a `SqlCommand` i... | ```
SELECT TOP 1 UserName, COUNT(*)
FROM myTable
GROUP BY UserName
ORDER BY COUNT(*) ASC
``` | Try the following code. Its *derived table* (inner `select`)
* summarizes the data by user name
* orders it by `count(*)` in ascending sequence
* then assigns each discrete frequency value a rank (1-N) based on that ordering
The outer `select` then keeps only the row or rows with a rank of 1 (meaning those with the l... | How to find lowest count of rows for a value in SQL Server 2005 | [
"",
"sql",
"sql-server",
""
] |
I have Query:
```
SELECT Stage1
,Stage2
,Stage3
FROM dbo.Cases
WHERE Number='6913'
```
result:
```
Stage1 Stage2 Stage3
==========================
NULL Settlement Stage1
```
But when i try:
```
SELECT COALESCE(Stage1 ,Stage2 ,Stage3) AS [Exit]
FROM dbo.Cases
WHERE Number = '6913'
``... | The only explanation I can think of for that is that you have the string value of NULL in your Stage1 field. See if this query returns your row to determine if that is the case:
```
SELECT Stage1
,Stage2
,Stage3
FROM dbo.Cases
WHERE Number='6913'
AND Stage1 = 'NULL'
```
If it is a string value of N... | Check that the value is an actual NULL and not the varchar value 'NULL'.
You can do this with:
```
SELECT * FROM dbo.Cases WHERE Stage1 IS NULL
SELECT * FROM dbo.Cases WHERE Stage1 = 'NULL'
```
And see what comes back. | why my coalesce function not working | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
Let's imagine we have a small MySQL database:
**Women:**
* id\_woman
* name
* surname
**women\_shoes:**
* id\_woman (FK)
* id\_shoe (FK)
**Shoes:**
* id\_shoe
* name
**woman\_handbags:**
* id\_woman (FK)
* id\_handbag (FK)
**Handbags:**
* id\_handbag
* name
There are 2 relations many-to-many. What I want to ... | Maybe something like this? if i understand your question correctly.
```
SELECT
r.*
FROM recipe r
JOIN recipe_ingredients ri ON ri.id_recipe = r.id_recipe
JOIN ingredients i ON i.id_ingredient = ri.id_ingredient
JOIN recipes_tags rt ON rt.id_recipe = r.id_recipe
JOIN tags t ON t.id_tag = rt.id_tag
WHERE i.name = ... | Since the 2nd criteria only has 1 handbag you don't really need to select from a subquery but I figured it might change to multiple handbags.
```
SELECT
w.*
FROM women w
JOIN
(
SELECT
id_woman
FROM woman_shoes ws
JOIN shoes s ON ws.id_shoe = s.id_shoe
WHERE s.name IN ('puma','nike','mang... | Select in many to many relations in MySQL with multiple conditions | [
"",
"mysql",
"sql",
"many-to-many",
""
] |
It's my task to count the total number of absent days for each employee.
i've written the following query
```
SELECT name
,surname
,absentdays
FROM (
SELECT name
,surname
,DATEDIFF("d", fromdate, todate) AS absentdays
FROM DiseaseReport D
, Employees E
WHERE E.number = D.em... | There's nothing wrong with applying a function (in your case, `sum`) to a "generated" column:
```
SELECT name,
surname,
SUM(absentdays) AS total_absent_days
FROM (SELECT name,
surname,
DATEDIFF("d", fromdate, todate) AS absentdays
FROM DiseaseRepor... | Why have a redundant select statement when you can just use your inner select?
Just delete everything other than
```
SELECT name
,surname
,DATEDIFF("d", fromdate, todate) AS absentdays
FROM DiseaseReport D
, Employees E
WHERE E.number = D.empnumber ;
``` | SQL SUM on 'generated' column | [
"",
"mysql",
"sql",
"select",
"sum",
""
] |
I have a table with a `varchar` column, PaymentRef, containing a variety of text and numeric data. Furthermore, there's a column, CurrencyAmount of datatype `float`:
```
PaymentRef CurrencyAmount
---------- --------------
EUR 100,00 100
EUR 50,00 50
USD 25,00 ... | here's a workaround as described in my comment
```
WITH CTE AS (
SELECT case when LEFT(PaymentRef, 3) IN ('EUR', 'USD', 'SEK')
then CAST(REPLACE(SUBSTRING(PaymentRef, 5, 100), ',', '.') AS FLOAT)
else null
end AS PaymentRefNumeric,
CurrencyAmount
FROM #t... | can't you change the where condition of the CTE to
```
WHERE CurrencyAmount IS NOT NULL
```
? your sample data looks like that would be ok ... the query works with the changed condition ...
you could also change the other where condition to
```
WHERE currencyamount is not null and PaymentRefNumeric <> CurrencyAmoun... | Error converting to float ignoring WHERE filter | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
There is a table `likes`:
```
like_user_id | like_post_id | like_date
----------------------------------------
1 | 2 | 1399274149
5 | 2 | 1399271149
....
1 | 3 | 1399270129
```
I need to make **one** `SELECT` query and count records for specific `like_... | I have a created a query for Oracle syntax please change it according to your db
```
select '1_Day' as period , count(*) as Total
from likes
where like_date>(sysdate-1)
union
select '7_days' , count(*)
from likes
where like_date>(sysdate-7)
union
select '1_month' , count(*)
from likes
where like_date>(sysdate-30)
un... | This code shows how to build a cross-tab style query that you will likely need. This aggregates by like\_post\_id and you may want to put restrictions on it. Further, in terms of last month I don't know whether you mean month to date, last 30 days or last calendar month so I've left that to you.
```
SELECT
like_post_i... | Is it possible to group by a few different date periods in mysql? | [
"",
"mysql",
"sql",
"database",
""
] |
I have a table like this
```
id code text
100 1 short description 100
100 2 long descr 100
101 1 short description 101
```
Now I want to fetch data from `text` field depending on value in `code` field. if the co... | Try this:
```
SELECT id,
MAX(CASE WHEN code=1 THEN text END) as shortdescription,
MAX(CASE WHEN code=2 THEN text END) as longdescription
FROM TableName
GROUP BY id
```
Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/42181/1).
This query is same as:
```
SELECT id,MAX(shortdescription) ... | I think the simplest approach is to treat this as conditional aggregation . . . put the `case` statement as an argument to the `max()` function:
```
select id,
max(case when code = 1 then text end) as ShortDescription,
max(case when code = 2 then text end) as LongDescription
from table t
group by id;
``` | Get Value from column depending on another column value in SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have database on Sql Server 2008 R2.
On that database a delete query on 400 Million records, has been running for 4 days , but I need to reboot the machine. How can I force it to commit whatever is deleted so far? I want to reject that data which is deleted by running query so far.
But problem is that query is still ... | There is no way to stop SQL Server from trying to bring the database into a transactionally consistent state. Every single statement is implicitly a transaction itself (if not part of an outer transaction) and is executing either all or nothing. So if you either cancel the query or disconnect or reboot the server, SQL ... | If you are deleting that many rows you may have a better time with truncate. Truncate deletes all rows from the table very efficiently. However, I'm assuming that you would like to keep some of the records in the table. The stored procedure below backs up the data you would like to keep into a temp table then truncates... | How to force a running t-sql query (half done) to commit? | [
"",
"sql",
"sql-server",
""
] |
In a SQL Server table with `Item`, `Supplier`, `Value` and `Date` columns where are records of all item purchases, I need records, by item, with minimum value of the last 180 days only.
A sample table with only one Item:
```
Item | Supplier | Value | Date
---------------------------------------
123 | ... | Use a ranking function like `Row_Number`:
```
WITH CTE AS
(
SELECT Item, Supplier,Value, Date,
RN = ROW_NUMBER() OVER (PARTITION BY Item
ORDER BY Supplier DESC)
FROM dbo.TableName
WHERE DATEDIFF(day, Date, GetDate()) <= 180
)
SELECT Item, Supplier,Value, Date
FROM CTE
W... | Another simple way of achieving this:
```
SELECT TOP 1 * FROM TableName
WHERE DATEDIFF(day, Date, GetDate()) <= 180
ORDER BY VALUE
```
[Demo](http://sqlfiddle.com/#!6/6b3bc/20) | Multiple aggregate functions | [
"",
"sql",
"sql-server",
""
] |
I'm beyond stuck with some SQL questions on my Bsc. CS revision exam paper - I know you all dislike answering academic questions but this is my last resort (and revision for Monday's exam) and I have no idea how to go about it.
I have 2 tables:
```
Department (deptId: string, deptName: string, managerId: string)
Emp... | The fisrt thing you must clear out is what and how the 2 tables are connected with?
If you deep in the table structure:
```
Department
(deptId: string, deptName: string, managerId: string)
Employee
(empId: string, empName: string, jobName: string, salary: integer, deptId: string)
```
you can see that `deptId` is... | # 1
Use [Rank](https://stackoverflow.com/questions/1466698/how-should-i-handle-ranked-x-out-of-y-data-in-postgresql) and just determine who is = 1. For simplicity, try creating a sub query: group by Department ID and get a count of employees.
# 2 - yes, you need having
```
Select
d.deptid, d.deptName, Average(e.... | SQL Join technique | [
"",
"sql",
"postgresql",
""
] |
I have a table that contains color options for a product. The color options include a hex color code, which is used to generate the UI (HTML).
I would like to sort the rows so that the colors in the UI look like a rainbow, instead of the current order that sorts based off of the Name of the color (not very useful).
H... | You want to sort hex codes by wavelength, this roughly maps onto the hue-value. Given a hexcode as a six character string: `RRGGBB`.
You just need to make a function that takes in a hexcode string and outputs the hue value, here's the formula [from this Math.SO answer](https://math.stackexchange.com/questions/556341/r... | This is based on the [answer by @dliff](https://stackoverflow.com/questions/23397594/sql-order-by-color-hex-code/23620824#23620824). I initially edited it, but it turns out my edit [was rejected](https://stackoverflow.com/review/suggested-edits/14009328) saying "*it should have been written as a comment or an answer*".... | ORDER BY Color with Hex Code as a criterio in MySQL | [
"",
"mysql",
"sql",
"sql-order-by",
"similarity",
""
] |
I have a PostgreSQL database and want to insert the same value for multiple records based on record IDs I have.
Is there a way to make a `WHERE` condition in the `INSERT` statement? For example:
```
insert into Customers (new-customer) values ('t') where customer_id in (list)
``` | Yes, you can do something like:
```
INSERT INTO customers(customer_id, customer_name)
select 13524, 'a customer name'
where 13524 = ANY ('{13524,5578,79654,5920}'::BIGINT[])
```
Here, a customer with id: `13524` will be added because it's ID is in the list: `{13524,5578,79654,5920}`
I hope that what you are lo... | To insert a row for every id in your list, you can use [`unnest()`](http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE) to produce a set of rows:
```
INSERT INTO customers(customer_id, column1)
SELECT id, 't'
FROM unnest ('{123,456,789}'::int[]) id;
```
If you misspoke and... | Insert same values for multiple records based on list of ids | [
"",
"sql",
"postgresql",
"sql-insert",
"unnest",
""
] |
I have a table that manage conversations of a chat between users, the structure is the following.
```
id | user_id | conversation_id
```
let's say that on the conversation with ID 1 there are 3 people to chat and the conversation with ID 2, 2 people as well
Conversations\_users table will look like this
```
id |... | Here is one method:
```
select uc.conversation_id
from UserConversions uc
where uc.user_id in (3, 4)
group by uc.conversation_id
having count(*) = 2;
```
If the table could have duplicates, you'll want: `having count(distinct user_id) = 2`.
EDIT:
If you want a specific list, just move the `where` condition to the `... | to get all the users in the conversations that user 3 and 4 are part of you could use this:
```
select distinct(user_id) from conversation_table where conversation_id in (select distinct(conversation_id) from conversation_table where user_id in (3,4));
```
it won't be very fast though
to get their actual conversatio... | select rows in mysql having another column with same value | [
"",
"mysql",
"sql",
""
] |
I have a database, with a table for venues and bookings. The relationship is 1:M.
I want to select all venues, that doesn't have a booking on a specific date. The date field is called booking\_date and is present on the bookings table. I'm not the strongest in SQL, but i found the NOT EXISTS, but that seems to give me ... | `NOT EXISTS` sounds exactly what you need:
```
SELECT *
FROM Venues V
WHERE NOT EXISTS(SELECT 1 FROM bookings
WHERE booking_date = 'SomeDate'
AND venue_id = V.venue_id)
``` | I would take care of this in the WHERE (making some assumptions on your tables):
```
DECLARE @DateCheck date = '2014-05-09';
SELECT
*
FROM
Venues
WHERE
VenueId NOT IN
(
SELECT
VenueId
FROM
Bookings
WHERE
BookingDate = @DateCheck
)... | SQL: Selecting all from a table, where related table, doesn't have a specified field value | [
"",
"sql",
"select",
"relationship",
""
] |
I'm trying to count many different values in one column in one table, all in one query.
**EDIT:** Query now works with suggestions by @Red Edit to move the aliases outside of each select and by @dnoeth to move the 'from' line- thanks! I have one more question, which I will add a comment for.
```
select
m... | After adding the expected result set it's easier to understand :-)
To get a single row you don't need the `FROM`or `GROUP BY`, so simply remove the `m1.mods_in_study,`and the `from dbo.study as m1
group by m1.mods_in_study`
But as you always use the same conditions on the same table this can be simplified to
```
SEL... | Not having a terminal at hand where I can test MSSQL but reading through the query it would seem like you are just missing a comma. | SQL Server : multiple select statements on one column | [
"",
"sql",
"sql-server",
"count",
""
] |
```
SELECT account_name ,sum(total_balance) from transaction
where account_name IN('cash','a/r','supplies','prepaid','land','gold')
AS total_assets
ORDER BY account_name
```
> 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '... | You have an alias in the wrong place.
```
SELECT account_name ,sum(total_balance) from transaction
where account_name IN('cash','a/r','supplies','prepaid','land','gold')
AS total_assets
ORDER BY account_name
```
should be
```
SELECT account_name ,sum(total_balance) AS total_assets
from transaction
where account_na... | remove `AS total_assets`
```
SELECT account_name ,sum(total_balance) from transaction
where account_name IN('cash','a/r','supplies','prepaid','land','gold')
ORDER BY account_name
``` | how can i fix this syntax error in sql? | [
"",
"mysql",
"sql",
"syntax-error",
""
] |
I think this is mostly a terminology issue, where I'm having a hard time articulating a problem.
I've got a table with a couple columns that manage some historical log data. The two columns I'm interested in are timestamp(or Id, as the id is generated sequentially) and terminalID.
I'd like to supply a list of termina... | I think you're on the right track with `GROUP BY`. Sounds like you want:
```
SELECT TerminalID, MAX(Timestamp) AS LastTimestamp
FROM [Table_Name]
WHERE TerminalID IN (.., .., .., ..)
GROUP BY TerminalID
``` | use the `TOP` keyword:
```
SELECT TOP 1 ID, terminalID FROM MyTable WHERE <your condition> ORDER BY <something that orders it like you need so that the correct top row is returned>.
``` | Getting a single row based on unique column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to write a query to insert dynamic values if they or NOT present therein already. So far I have tried this.
```
INSERT MTB_AML..tb_aml_codes (aml_code, aml_desc)
SELECT 'NRA', 'Non-Resident Alien'
UNION
SELECT 'DOM', 'Resident Alien'
FROM MTB_AML..tb_aml_codes t1
WHERE t1.aml_code NOT IN (S... | I think that the problem you're having is that in your version the WHERE clause was only applying to the last Select in the UNION clause
TAke the records you want
```
SELECT 'NRA' AS aml_code, 'Non-Resident Alien' AS aml_desc
UNION
SELECT 'DOM' AS aml_code, 'Resident Alien' AS aml_desc
```
And then wrap them ... | You are HARDCODING the values of the resultset, wrapping quotes means a literal value, you must want the COLUMN name.
```
SELECT 'DOM', 'Resident Alien'
```
You need to have your SELECT like this:
```
SELECT T1.ColName, T1.AndAnotherColName
....
``` | How to avoid duplicate insert of dynamic values in SQL server | [
"",
"sql",
"sql-server",
"select",
"duplicates",
"notin",
""
] |
So Im trying to find the total amount spent on Cuts and Products by each Customer
I don't know if my Query is Wrong or my entire Database Schema any ideas?
**My Query**
```
`Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A, cuts B, products C, customers D
Where A.Customer_ID= D.Customer_ID
AND A.Cut_ID = ... | You should `GROUP BY` to `SUM` by each customer :
```
Select D.First_Name
, SUM(B.Cost)
, SUM(C.Cost)
FROM bookings A LEFT JOIN cuts B ON A.Cut_ID = B.Cut_ID
JOIN products C ON A.Product_ID = C.Product_ID
JOIN customers D ON A.Customer_ID = D.Customer_ID
GROUP BY D.First_Name;... | Start using recommended `JOIN / ON` syntax for joining instead of using `WHERE` clause . You also need a `GROUP BY` clause
```
Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A
INNER JOIN cuts B
ON A.Cut_ID = B.Cut_ID
INNER JOIN products C
ON A.Product_ID= C.Product_ID
INNER JOIN customers D
ON A.Custom... | SQL Query or Table Error? | [
"",
"sql",
"database",
"sqlite",
""
] |
I have an `sql` statement below which do group based on country names.
```
SELECT COUNTRY,count(*) FROM DRUG_SEIZURE WHERE COUNTRY IS NOT NULL GROUP BY COUNTRY
```
**Result Sample:**
```
Country Count
------- -----
America 20
Saudi Arabia 28
China 10
Japan 1... | Depending on what RDBMS you are using:
***SQL SERVER:***
```
SELECT TOP 3 COUNTRY, count(*)
FROM DRUG_SEIZURE
WHERE COUNTRY IS NOT NULL
GROUP BY COUNTRY
ORDER BY count(*) DESC
```
***MySQL:***
```
SELECT COUNTRY, count(*)
FROM DRUG_SEIZURE
WHERE COUNTRY IS NOT NULL
GROUP BY COUNTRY
ORDER BY count(*) DESC
LIMI... | ```
SELECT *
FROM (SELECT COUNTRY,count(*)
FROM DRUG_SEIZURE
WHERE COUNTRY IS NOT NULL
GROUP BY COUNTRY
ORDER BY 2 DESC)
WHERE rownum <= 3;
``` | Select top 3 most count group by - SQL | [
"",
"mysql",
"sql",
"sql-server",
"oracle",
"subquery",
""
] |
Products are made up of one or many components and components have individual price.
The cost of the product are calculated adding the cost of components used in that product.
Should I add a column named cost in Product table as they are not dynamic or Should I calculate everytime when a product is purchased?
Which ... | Unless you are absolutely sure the cost will never change, calculate it dynamically | None of the answers so far really seem to address the issue. Price is generally a slowly changing dimension. That means that the same price for a component can be different at different points of time. When bringing up slowly changing dimensions, I usually recommend Ralph Kimball's book "The Data Warehouse Toolkit", wh... | SQL - Optimization Priority, Which of these apply? | [
"",
"sql",
"database",
""
] |
I have the following code which is connecting to my database and retrieving some data from a table:
```
string connectionString = "Data Provider=SQLOLEDB;Data Source=myserver;Initial Catalog=Db;Integrated Security=FALSE;user=zh;pwd=zh12;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
... | After much troubleshooting, I was able to figure out why it wasn't working. I rewrote the string like this:
```
string cString = "Provider=sqloledb;Data Source=myserver;Initial Catalog=mydatabase;User Id=myid;Password=mypassword;";
```
That worked like a charm, in case someone else is having the same issue. | Don't use "Integrated Security" when you are supplying the user ID and password. | Why connecting to an OLEDB is giving me an connection error | [
"",
"sql",
"sql-server",
"oledb",
""
] |
I’m using MS SQL Server 2012 and I need to bulk update varchar data in a single column based on a text pattern.
Basically my single column contains comma separated variable length text data (see below) and I need to strip out the some of the data based on a pattern. For example, I have “ProductA-106, ProductB-107” and... | This is a perfect example why you don't want to have a database design like that.
It can be solved, but it is not easy, pretty or fast:
Create this function:
```
CREATE function dbo.f_cleanup (@a varchar(max))
returns varchar(max)
as
BEGIN
WHILE @a like '%-%'
SELECT @a = STUFF(@a, dash, comma - dash, '')
FROM
(
... | This would be much easier if your data was structured correctly - ie: your products in a single table, and related to your other table by IDs in a separate join table.
```
update yourtable
set yourfield = replace (yourfield, '-', '')
update yourtable
set yourfield = replace (yourfield, '0', '')
update yourtable
set ... | How can I bulk update varchar data based on a pattern in a MS SQL 2012 database? | [
"",
"sql",
"sql-server",
""
] |
I found a bizarre snippet which is confusing me so I thought I'll ask the experts.
Let assume a tableA got following columns with data:
```
"START_TIME":1399075198
"END_TIME":1399075200
"START_DATE":"02-MAY-14"
"END_DATE":"03-MAY-14"
```
Now query 1:
```
SELECT MIN(start_date) INTO sdate FROM tableA;
```
query 2:... | The expression:
```
TRUNC(sdate, 'HH24')
```
cuts off everything from a date that is smaller than an hour, i.e. the minutes and seconds. For the specific date:
```
TRUNC('02-MAY-14','HH24')
```
it returns the date unchanged. It only makes sense if the Oracle date contains a time component.
Possibly, your SQL tool ... | In Oracle the date datatype inherently store the time as well.
Try executing the below query. It should clear things up a bit:
SELECT TO\_CHAR(SYSDATE,'DD-MON-YYYY HH:MI:SS'), TO\_CHAR(TRUNC(SYSDATE,'HH24'),'DD-MON-YYYY HH:MI:SS') FROM DUAL; | What should be the outcome of TRUNC('02-MAY-14','HH24')? | [
"",
"sql",
"oracle",
"plsql",
"oracle11g",
""
] |
Hi I'm fairly new to SQL and have been learning by trial and error but I have walked into a wall with this issue. I hope someone could give me an advice.
1) Check if table already exist in database, if it does drops it [works]
```
IF OBJECT_ID (N'PWC_L6_Daily',N'U') IS NOT NULL
DROP TABLE PWC_L6_Daily
```
2) Create ... | How can you tell if data is in the order you want? The statement:
```
select *
from table t
```
Returns the data *as an unordered* result set. The only way you can impose an ordering is with `order by`. You do *not* get data in insert order in SQL Server. This is ANSI-compliant behavior and consistent with how almost... | Order by is only for presenting purpose. When used to insert data, it takes no effect. THINK TABLE AS SET. | ORDER BY clause won't work in table created with SELECT INTO | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have 2 similar tables that contain campaign names. I know I can do an union all to combine the tables, but I was wondering if there was a way to do this using form of Join instead? I want to create a table Z with campaign names for table A plus campaign names from table B (which are not in A). Can I do this with a jo... | UNION is the easier and correct way to do that. Purely for the exercise you can do it with a JOIN but it is a lot more complex, unreadable, and the perf will be way worse... | ```
SELECT * INTO TABLEZ
FROM
(
SELECT Column1, Column2, Column3.... FROM TABLEA
UNION ALL
SELECT Column1, Column2, Column3.... FROM TABLEB
)Q
``` | Join or Union All To Combine Records? | [
"",
"sql",
"sql-server",
""
] |
How do I convert a table to an atom? I have a 1x1 table with a header. I want to get rid of the header and just have the number so that I do things like anotherTable\*thisNumber and so on.
I've tried:
```
(raze raze tableName)
```
but this gives me: enlist 10.5, how do I get 10.5 (as a number)? | ```
q)t:([] head:enlist 1)
q)t
head
----
1
q)first exec head from t
1
q) // or the shortest way
q)t[`head]0
1
q)type first exec head from t
-7h
q)100*first exec head from t
100
q)first t`head
1
q)raze/[t]0
1
``` | Think you can use `over` and indexing to do this:
```
q)raze/[([]a:1#1)]0
1
``` | kdb: convert 1x1 table to an atom | [
"",
"sql",
"kdb",
""
] |
My actual table structures are much more complex but following are two simplified table definitions:
Table `invoice`
```
CREATE TABLE invoice (
id integer NOT NULL,
create_datetime timestamp with time zone NOT NULL,
total numeric(22,10) NOT NULL
);
id create_datetime total
----------------------------
... | You need a single row per invoice, so aggregate `payment_invoice` first - best before you join.
When the whole table is selected, it's typically fastest to [*aggregate first* and *join later*](https://stackoverflow.com/questions/16018237/aggregate-a-single-column-in-query-with-many-columns/16023336#16023336):
```
SE... | See [sqlFiddle](http://sqlfiddle.com/#!15/d2524/4)
```
SELECT TO_CHAR(invoice.create_datetime, 'MM/YYYY') as month,
COUNT(invoice.create_datetime) as total_invoice_count,
invoice.total - payments.sum_amount as outstanding_balance
FROM invoice
JOIN
(
SELECT invoice_id, SUM(amount) AS sum_amount
F... | Using a column in sql join without adding it to group by clause | [
"",
"sql",
"postgresql",
"aggregate-functions",
""
] |
I have a table with sample data below:
```
ID | RecordID | Time | Start/End
1 1111 09:00:10
5 1111 09:00:12
13 1111 09:01:10
24 1111 09:02:30
27 9999 10:00:10
29 9999 10:01:22
30 9999 10:03:10... | Query:
**[SQLFIDDLEEXample](http://sqlfiddle.com/#!3/bce28/1)**
```
UPDATE t
SET [Start/End] = CASE WHEN t1.ID is null or t2.ID is null
THEN 1
WHEN t.RecordID <> t1.RecordID OR t.RecordID <> t2.RecordID
THEN 1 END
FROM Table1 t
LEFT JOIN Table1 t1
ON t1.ID = t.ID - 1
LEFT JOIN Table1 t2
ON t2.ID =... | Edited My answer:
Well, you can use below update queries:
`UPDATE t SET t.Start/End = 1 FROM table t INNER JOIN (SELECT MIN(Id) IdMin,MIN(Time) FROM table GROUP BY RecordId) t1 ON t.Id = t1.IdMin`
`UPDATE t SET t.Start/End = 1 FROM table t INNER JOIN (SELECT NAX(Id) IdMax,MAX(Time) FROM table WHERE Start/End IS NULL... | Update 1 column based on changing values in another column | [
"",
"sql",
"sql-server-2008",
"t-sql",
"reportbuilder3.0",
""
] |
Question1:
Do i have to use to\_date while inserting date?
```
INSERT INTO some_table (date1, date2)
VALUES (to_date('2012-10-24','YYYY-MM-DD'), to_date('2012-10-24','YYYY-MM-DD'));
```
Or can just insert as string? Will everything be OK this way too? I've tried and it worked.
```
INSERT INTO some_table (date1,... | 1 seems to only work with the 'YYYY-MM-DD' format:
<http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#SQLRF51049> says
> You can specify a DATE value as a string literal ... to specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal... The ANSI da... | You could even do it like this one:
```
ALTER SESSION SET NLS_DATE_FORMAT = 'MM:YYYY:DD';
INSERT INTO some_table (date1) VALUES ('05:2014:10');
```
...but doing it like this is not recommended. Use `TO_DATE` or DATE Literal, e.g. `DATE '2014-05-10'` instead. It makes your life easier. | SQL oracle beginner questions | [
"",
"sql",
"oracle",
""
] |
Here is the example SQL in question; The SQL should run on any Oracle DBMS (I'm running 11.2.0.2.0).
Note how the UUID values are different (one has 898 the other has 899) in the resultset despite being built from within the inline view/with clause. Further below you can see how DBMS\_RANDOM.RANDOM() does not have thi... | The [documentation gives a reason](http://docs.oracle.com/cd/E16655_01/appdev.121/e17620/adfns_packages.htm#ADFNS00908) as to why you may see a discrepancy (emphasis mine):
> **Caution:**
>
> Because SQL is a declarative language, rather than an imperative (or procedural) one, **you cannot know how many times a functi... | The NO\_MERGE hint "fixes" it. Prevents Oracle from re-writing the inline view.
```
WITH data AS (SELECT /*+ NO_MERGE */
SYS_GUID () uuid FROM DUAL)
SELECT uuid, uuid
FROM data
```
[From the docs:](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements006.htm#SQLRF50507)
> The NO\_M... | Oracle SQL: Understanding the behavior of SYS_GUID() when present in an inline view? | [
"",
"sql",
"oracle",
""
] |
Running MS SQL Server 2008
I have this query:
```
select count(*) from dbo.study
where study_datetime >= (GETDATE() -1)
```
that comes back with all of yesterdays exams written to my study table. How would I make it come back with everything done 'today' up to the current time I asked for it? For example I would eve... | To get everything that strictly happened today, just use:
```
select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)
and study_datetime < cast(DATEADD(day,1,getdate()) as Date)
```
When you're working with continuous data, it's almost always better to switch to using semi-open intervals, to en... | unfortunately there is no trunc() like in oracle, but since you have the 2008 version you can use:
`select count(*) from dbo.study
where study_datetime >= cast(getDate() As Date)` | mssql select GETDATE - all day from 00:00 - 23:59 | [
"",
"sql",
"sql-server",
""
] |
i want to insert the scholar's id to the tblinbox. Here is my query:
```
$sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";
```
my p... | `INSERT ... SELECT` syntax does not allow for `VALUES` declaration. The values ARE the results returned from the `SELECT`.
See the documentation here: <http://dev.mysql.com/doc/refman/5.6/en/insert-select.html>
I honestly am not fully sure what you are trying to do with your insert. If you are trying to insert the sa... | considering id is the first column in your insert statement, try this
```
$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";
``` | INSERT ... SELECT(insert many rows) | [
"",
"mysql",
"sql",
""
] |
I have a query that returns a date. eg 2013-10-12.
I want to check if the date is between June 1st of the year and the last day of the year.
If it is between these dates increase the year by 1 else leave the year as it is.
So, taking the example above `2013-10-12` the result I want is 2014.
If it was `2013-01-12` th... | ```
Declare @Yourdate datetime = '2013-10-13'
SELECT CASE WHEN
(@Yourdate between '2013-06-01' and DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1) )
THEN YEAR(@Yourdate) + 1 ELSE (YEAR(@Yourdate) ) END AS [YEAR]
``` | ```
declare @arg datetime
set @arg = '01/12/2013'
select
case when month(@arg) > 5 then year(@arg) + 1 else year(@arg) end
``` | Check if date is between the start of May this year and the end of May next year | [
"",
"sql",
"sql-server",
"date",
""
] |
I have stored procedure in asp.net application as following:
```
CREATE PROCEDURE [dbo].[step2-e]
@PI varchar(50),
@Balance int output ,
@Shipment_status varchar(50) output,
@ETA varchar(50) output,
@Forwarder varchar(50) output,
@Transit_time Time output,
@Shipping_date date output,
@S... | As you posted it, there's a comma missing between the first two elements in your `SELECT`:
```
select
@Advance_payment = [advance_payment] @Balance = [Balance],
^^^^
|
here there should be a comm... | This error is due to the fact that Build Action is set To Build inside the Properties. Set it to None and it should work fine. [](https://i.stack.imgur.com/AlRJl.png) | Error SQL70001: This statement is not recognized in this context | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have created the following 3 tables for a database:
```
CREATE TABLE [dbo].[Buyer] (
[Buyer_Id] INT IDENTITY (1, 1) NOT NULL,
[Last_Name] NVARCHAR (50) NOT NULL,
[First_Name] NVARCHAR (50) NOT NULL,
[Social_No] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[User_I... | The usual: User is a [reserved word in T-SQL](http://technet.microsoft.com/en-us/library/ms189822.aspx). So you got to quote it:
```
insert into [User] (User_Name,Pass,Type_Id)
``` | There are a number of issues with your procedure. Yes what VMai has mentioned is very important and you also have the following errors.
```
CREATE PROCEDURE [dbo].[InsertCustomer]
@Buyer_Id int output,
@Last_Name varchar(50),
@Fist_Name varchar(50),
@Social_No varchar(50),
@Phone varchar(50),
@... | Incorect syntax near table when trying to save a stored procedure in C# | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I am trying to do a multi query but I don't want to use sub queries i.e:
```
SELECT column1
FROM table1
WHERE
EXISTS (SELECT column1 FROM table2 WHERE table1.column1 = table2.column1);)
```
I thought of using a `JOIN` but so far my best result was this:
```
SELECT *
FROM table1
JOIN table2 ON table1.t1id = ... | Is this what you're looking for?
```
select a.id, a.column1, b.column2
from table1 a
left join table2 b on a.id = b.otherid;
``` | You can't change the column list of a query based on the values it returns. It just isn't the way that SQL is designed to operate. At best, you can return all of the columns from the second table and ignore the ones that aren't relevant based on other values in that row.
I'm not even sure how a variable column list wo... | Is there a way to do a multi table query and get result just from specific tables? | [
"",
"sql",
"join",
""
] |
I have an invoice table in my database into which new invoices are inserted. Recently we have upgraded our services and have many users inserting invoices into the table. I have written a function that calculates the next invoice number in the sequence (the sequence isn't just sequential numbering).
```
MAX(CAST(SUBST... | dont know if this is helpful
```
begin tran
declare @nextInvoiceNumber int = dbo.NextInvoiceNumber(@Prefix)
INSERT INTO [Invoice]
([InvoicedTo]
,[InvoiceNumber]
,[InvoiceDate]
,[Description]
,[Amount])
VALUES
(@InvoicedTo
,@nextInvoiceNumber
,@InvoiceDate
,@Description
,@Amount)
commit
```
another thing you... | No, it doesn't guarantee uniqueness.
You should wrap the call inside a `serializable transaction`. | Using SQL Functions inside Insert Statements | [
"",
"sql",
"sql-server",
"function",
""
] |
i am new to SQL.
I have used "order by" to sort two large tables on SQL, netezza of IBM.
The table is:
```
col1 INT
col2 INT
col3 INT
col4 DOUBLE PRECISION
INSERT INTO mytable
SELECT *
FROM table1 AS t1
ORDER BY t1.col1 , t1.col2, t1.col3, t1.col4 ASC
```
After sorting, I check the top 100 rows:
```
... | The order in which you insert data into the table is meaningless. Running a query has absolutely no guarantee on the order rows are returned, unless you explicitly specify it using the `order by` clause. Since there's no guarantee on the order of rows, there's no guarantee what the "top 100" are, and hence you may very... | The sequence is not guaranteed, although it may match the order in which the data was inserted. If you need it in a particular sequence, use ORDER BY. | SQL check top 100 rows different everytime running the SQL query? | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"netezza",
""
] |
I am trying to get only the first row from this query. The query does not return the top row. Here is the query.
```
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
AND ROWNUM <= 1
ORDER BY age DESC;
```
When I run the query it returns `Chirs |35`.
Withou... | I think the best way to get this is to use a subquery as the rownum is being looked at before the order by so:
```
select * from (
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
ORDER BY age DESC
) where ROWNUM <= 1;
```
For a longer read look at <ht... | Try to use `ROWID` rather than `ROWNUM` like this:
```
SELECT * FROM TABLE_NAME WHERE ROWID = (SELECT MIN(ROWID) FROM TABLE_NAME)
``` | Get first row in Oracle Sql | [
"",
"sql",
"oracle",
""
] |
I *THINK* I'm having some trouble.
I'm trying to query 2 tables for customers that haven't been used on the table for the last 3 Years. The data consists of data ranging for 7+ years, so customers are used multiple times.
I think the issue with my current query: It's finding data of customers not used in the last 3 y... | The core problem with the initial query is that, for no imports (which will happen for "no order" customers) the condition
```
DateAdd("yyyy", 3, ImportDate) < Now()
--> DateAdd("yyyy", 3, NULL) < Now()
--> NULL < Now()
--> NULL (or not true)
```
is not true. A simple fix is to add a guard
```
([Table1].[ImportD... | ```
SELECT DISTINCT
tbl_Customer.CustomerID,
tbl_Customer.CustomerName,
Table1.ImportDate,
Table2.ImportDate
FROM (tbl_Customer
LEFT JOIN Table1
ON tbl_Customer.CustomerName = Table1.CustomerName)
LEFT JOIN Table2
ON tbl_Customer.CustomerName = Table2.CustomerName
WHERE DateAdd("yyyy",3,... | SQL Query For Customers Not Used For Last 3 Years | [
"",
"sql",
"ms-access",
""
] |
I have scenario like
```
Account_Number | Ins1 |Ins2 | Ins3
8923647324 | 3 | 1 | 5
128736244 | 5 | 2 | 6
9238475323 | 6 | 3 | 7
```
I wanted to achieve something like
```
8923647324 | 3
8923647324 | 1
8923647324 | 5
128736244 | 5
12873624... | There are many ways to do this:
Using `UNION`
```
SELECT Account_Number,
Ins1 AS Ins
FROM YourTable
UNION ALL
SELECT Account_Number,
Ins2
FROM YourTable
UNION ALL
SELECT Account_Number,
Ins3
FROM YourTable
```
Using `CROSS APPLY`:
```
SELECT t.Accoun_Number,
x.Ins
FROM YourTable ... | You can use `UNPIVOT`
```
SELECT Account_Number, Ins
FROM tbl
UNPIVOT
(
Ins FOR Val IN (Ins1, Ins2, Ins3)
) as unp
``` | transverse column to rows like matrix in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query where data is coming from front end into IN condition. Now the value is coming as comma separated for eg: 002,003 or 002q, 4335f, 123d, shd4 or yuw98
My query takes value as `select * from tbl1 where userid in ('002,004')` where as it should be `userid in ('002','004')`
I tried below query to replace t... | For those who were looking for solution, I found one.
`WHERE INSTRC('001, 002'), userid, 1, 1) > 0` | If you have a query like this:
```
select * from tbl1 where userid in ('002,004')
```
And, for some reason, you *have* to represent the list of values as a string (assuming you want to search for two values in this case), then you can use `like` to find matches:
```
where ','||userid||',' like ','||'002,004'||','
`... | Oracle Query - Replace not working | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
Table name: RANKTITLE,RANK
```
//RANKTITLE
TITLE
--------------
TEST1
TEST2
TEST3
TEST4
//RANK
TITLE SALARY
---------------------
TEST1 4500000
TEST2 80000
TEST3 26000
TEST4 1800000
```
So i want to display all the title except the rank with the highest salary
Output will b... | Test this:
```
SELECT r.TITLE, r.SALARY
FROM RANKTITLE r
WHERE r.SALARY < (SELECT MAX(s.SALARY) FROM RANK s)
``` | ```
SELECT r.TITLE, salary FROM RANK r WHERE
salary not in (SELECT MAX(SALARY) FROM RANK);
```
If you have only one record with highest rank, only it will be exluded.
If you have more than one record with highest rank, all will be exluded.
```
select title from (
SELECT TITLE, rownum rnum FROM RANK
ORDER by salary ... | SELECT clause with exist condition | [
"",
"sql",
"oracle",
""
] |
Im having a slight issue merging the following statements
```
declare @From DATE
SET @From = '01/01/2014'
declare @To DATE
SET @To = '31/01/2014'
--ISSUED SB
SELECT
COUNT(pm.DateAppIssued) AS Issued,
pm.Lender,
pm.AmountRequested,
p.CaseTypeID
FROM BPS.dbo.tbl_Profile_Mortgage AS pm
... | I'm fairly certain in this case the query can be written without the use of any `CASE` statements, actually:
```
DECLARE @From DATE = '20140101'
declare @To DATE = '20140201'
SELECT Mortgage.lender, Mortgage.amountRequested, Profile.caseTypeId,
COUNT(Issue.issued) as issued,
COUNT(Pass.passed) as passed... | You could either as Dan Bracuk states use a union, or you could use a case-statement.
```
declare @From DATE = '01/01/2014'
declare @To DATE = '31/01/2014'
select
sum(case when (CONVERT(DATE,DateAppIssued, 103) Between CONVERT(DATE,@From,103) and CONVERT(DATE,@To,103)) then 1 else 0 end) as Issued
, sum(case when ... | SQL Merging 4 Queries to one | [
"",
"sql",
"sql-server",
"merge",
""
] |
Iam little stucked with this sql query. I have got two tables
```
TbleName - usrs TbleName - idtb
name | cid cname | cid
------------- ----------------
james | 1100 IT | 1100
john | 1200 HR | 13... | As you want to print all `cname` but counting `usrs` this is the query you need:
```
select a.cname, count(b.name)
from idtb a left join usrs b on (a.cid = b.cid)
group by a.cname
```
If you want to add a filter for some of then, just add the where clause.
See it here on fiddle: <http://sqlfiddle.com/#!2/0acec/2> | ```
SELECT COUNT(*) as 'Total', idtb.cname
FROM idtb LEFT JOIN usrs
ON usrs.cid=idtb.cid
WHERE usrs.cid=1100
GROUP BY idtb.cname
``` | Count (*) on two tables | [
"",
"mysql",
"sql",
""
] |
I am trying to do a wildcard search on a value from a joined item. Ie.
```
SELECT
(
SELECT
count(*)
FROM
user_contacts e
WHERE
ece.user = 1 AND
(
e.name LIKE '%u.lastname%'
OR
e.name LIKE '%u.f... | You could concatenate it.
```
e.name LIKE CONCAT('%', u.lastname, '%')
``` | You just need to use the right syntax for concatenation for MySQL:
```
SELECT (SELECT count(*)
FROM user_contacts e
WHERE e.user = 1 AND
(e.name LIKE concat('%', u.lastname, '%') or
e.name LIKE concat('%', u.firstname, '%')
)
) as friends_cou... | Wilcard Search LIKE %e.name% from INNER JOIN | [
"",
"mysql",
"sql",
""
] |
I sort of understand how this works but need more help
original question:
Use a correlated subquery to return one row per customer, representing the customer’s oldest order (the one with the earliest date). Each row should include these
three columns: email\_address, order\_id, and order\_date.
My Answer:
```
selec... | so along with the responses from everyone, I figured this would be helpful to understand the OP's question `I don't understand how having the subquery return a single tuple allows me to get more than one tuple in my final result.`
think of it like this... you have multiple orders on one date.
```
+-------+-----------... | Here is a break down of what is happening.
These are the columns of data you wish to get:
select email\_address, order\_id, order\_date
selecting data from the customers table:
from customers as T
matching only customers who have made an order:
natural join orders
the above could have been better represented like t... | Understanding this MySQL Query | [
"",
"mysql",
"sql",
""
] |
For the below query, the MAX function seems to be completely ignored. The MAX function has no effect on the result of the query
```
SELECT alarm_severity_id
FROM alarm_notification
WHERE alarm_life_cycle_id = 25
having MAX(event_timestamp);
``` | This is your query:
```
SELECT alarm_severity_id
FROM alarm_notification
WHERE alarm_life_cycle_id = 25
HAVING MAX(event_timestamp);
```
Your `HAVING` clause is saying: take the maximum of the timestamp. If the maximum is not equal to zero or NULL, then everything is fine. This is exactly equivalent:
```
HAVING MAX(... | 1. There should be correct condition like `having MAX(event_timestamp) > 100`
2. There should be `group by` if you use `MAX`
3. Or do as @Gordon Linoff said (with `order by` + `limit 1`). | SQL Function calls ignored with "HAVING" clause | [
"",
"mysql",
"sql",
""
] |
Table B have the following column: `Email Address`
and Table A have the following column: `email`
How do I update Table A `newsletter` to = 0 where A.`Email Address` = B.`email`?
I've tried with the following which seems to fail:
```
UPDATE TableA
SET TableA.newsletter = 0
FROM TableB, TableA
WHERE TableA.email = T... | This is how the query should look like while updating data joining 2 tables with a key
```
update
TableA t1
inner join TableB t2 on t2.`Email Address` = t1.email
set t1.newsletter = 0
``` | You're just missing backticks for the TableB.Email Address column, anytime you have special characters or spaces you will need to add backticks for columns\tablenames\schemas.
```
UPDATE
TableA A, TableB B
SET A.newsletter = 0
WHERE A.email = B.`Email Address`
``` | update a certain column in table A when table A email equals to table B email | [
"",
"mysql",
"sql",
""
] |
For example . i having these 2 table
```
//DEPARTMENT
DNAME CITY
--------------------
RESEARCH BOSTON
IT CITY
SCIENCE DALLAS
RESEARCH DALLAS
```
So i using this statement
```
(SELECT DNAME FROM DEPARTMENT WHERE CITY='BOSTON')
UNION
(SELECT DNAME FROM DEPARTMENT WHERE CITY='DAL... | You should use `INTERSECT` and `MINUS` (for Oracle):
```
-- At least at Boston or at Dallas
(SELECT DNAME
FROM DEPARTMENT
WHERE CITY = 'DALLAS'
UNION
SELECT DNAME
FROM DEPARTMENT
WHERE CITY = 'BOSTON')
MINUS
-- At Boston and at Dallas
(SELECT DNAME
FROM DEPARTMENT
WHERE CITY = 'DALLAS'
INTE... | You can filter out the dnames first and then use group by to select only those dnames that are present in one city only.
```
select dname
from department
where city in ('BOSTON', 'DALLAS')
group by dname
having count(city) = 1;
``` | SELECT using UNION Clause | [
"",
"sql",
"oracle",
""
] |
I have a SQL database that it is possible to update. As the sql (will be server based) i only want to update values as i need to. So if only one column changes, only one column updates.
I have a mechanism that detects if values have changed and currently i have a messy function that constructs the SQL syntax and then ... | Basically no, there is no "magic" value you can bind that will leave col2 unchanged.
Binding the old value (ie updating with the same value col2 already has) will give the desired effect but requires you to update a single row at a time and know the old value for each row.
Rebuilding the SQL to not include `col2` is ... | Get all column values in some variables...say col1,col2.(for that specific row)
> If column1 is changed you may update variable col1 value.
>
> Similarly,If column2 is changed you may update variable col2 value.
and a single UPDATE QUERY you mentioned above should do the required updation. | best way to update an SQL row | [
"",
"sql",
"objective-c",
""
] |
I am trying to select some values from a database table and then convert them to human readable words. I am getting many errors in the third case statement. Can somebody tell me were am going wrong?
Errors
> Msg 156, Level 15, State 1, Line 10
> Incorrect syntax near the keyword 'or'.
> Msg 156, Level 15, State 1... | For Multiple options in one `CASE` statement use more `WHEN` conditions
So Try
```
SELECT P.id AS Ref,
CASE
WHEN P.listed = 1 THEN 'Yes'
ELSE 'No'
END AS Listed,
CONVERT(DATE,... | Try this if it works
```
SELECT P.id AS Ref,
CASE
WHEN P.listed = 1 THEN 'Yes'
ELSE 'No'
END AS Listed,
CONVERT(DATE, CONVERT(VARCHAR, P.listeddate, 12)) AS DateListed,
... | Case statement in SQL Server causing error | [
"",
"sql",
"sql-server",
"database",
""
] |
I have the following tables:
## MOVIES
```
MOVIE_ID TITLE
---------- -----------------------------
1 The Shawshank Redemption
2 The Godfather
3 The Godfather: Part II
4 The Dark Knight
5 Pulp Fiction
6 The Good, the Bad and the Ugly
7 Schindler's List
... | This is one way to achieve this, viz to group, filter and then count the directors:
```
SELECT m.title
FROM Movie m
INNER JOIN Direct md
on md.movie_id = m.movie_id
INNER JOIN Directors d
on md.director_id = d.director_id
WHERE
d.name IN('Clint Eastwood', 'Al Pachino')
GROUP BY m.title
HAVIN... | With the IN operator, your query returns movies that have *any* of these directors.
You have to check for each director separately:
```
SELECT *
FROM Movie
WHERE movie_id IN (SELECT movie_id
FROM Direct
WHERE director_id = (SELECT director_id
... | SQL query records containing all items in list | [
"",
"mysql",
"sql",
"oracle",
"sqlite",
"relational-division",
""
] |
I have a complex select that - when simplified - looks like this:
```
select m.ID,
(select sum(AMOUNT) from A where M_ID = m.ID) sumA,
(select sum(AMOUNT) from B where M_ID = m.ID) sumB,
.....
from M;
```
The tables A,B,... have a foreign key M\_ID pointing into table M.
The problem is that this select is very ... | Yes, this is a typical problem. I like your original query for its clarity. However, if running in performence issues, one has to think of other options.
Here is one option. As A and B get multiplied you could simply divide the sum by the related count. Well, admittedly this looks kind of strange though.
```
select m... | This should work
```
select m.ID,
a.aamount,
b.bamount
from M
inner join
(
select M_ID,sum(AMOUNT) as aamount
from A group by M_ID
) a
on a.M_ID = m.ID
inner join
(
select M_ID,sum(AMOUNT) as bamount
from B group by M_ID
) b
on b.M_ID = m.ID;
``` | 4:**Count/sum rows in multiple related tables | [
"",
"sql",
"oracle11g",
""
] |
I have these two tables (the names have been pluralized for the sake of the example):
Table `Locations`:
```
idlocation varchar(12)
name varchar(50)
```
Table `Answers`:
```
idlocation varchar(6)
question_number varchar(3)
answer_text1 varchar(300)
answer_text2 varchar(300)
```
This table can hold answ... | This is an unfortunate result of how the SQL Server query processor/optimizer works. In my opinion, the SQL standard prohibits the calculation of SELECT list expressions before the rows that will contribute to the result set have been identified, but the optimizer considers plans that violate this prohibition.
What yo... | Your query appears correct enough, which means you have a Question 05 record with a datetime in either the `answer_text1` or `answer_text2` field.
Give this a shot to figure out which row has a date:
```
select *
from Answers
where question_number='05'
and (isdate(answer_text1) = 1 or isdate(answer_text2) = 1)
```... | Filter on a nested aggregate SUM function not working | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Shortly, I am using `JDBC` and I am trying to write a query that will return some values from an SQL developer db table.
So far i have this:
```
#Query for getting data
sql <- paste("select *
FROM GRID Z
where Z.LAT = Xlat AND Z.LON = Xlon")
fun <- dbGetQuery(jdbcConnection, sql)
attach(fun)
``... | Are you looking for this?
```
sql <- paste0("select *
FROM GRID Z
where Z.LAT ='", Xlat,"' AND Z.LON = '", Xlon,"'")
```
I assumed that your variables are character. In case the above is running behind a web server, there are options for URL encode and escape to avoid code injections... like [t... | [gsubfn](http://gsubfn.googlecode.com)'s `fn$` operator supports a quasi-perl sort of string interpolation like this:
```
library(gsubfn)
sql0 <- "select * FROM GRID Z where Z.LAT = $Xlat AND Z.LON = $Xlon"
fun <- fn$dbGetQuery(jdbcConnection, sql0)
```
or like this to allow examination of `sql` after substitution:
... | Use R variables to an SQL query | [
"",
"sql",
"r",
"oracle",
"jdbc",
""
] |
Can someone tell me why I'm getting an Incorrect Syntax error at the last ELSE statement.
```
SELECT
CASE WHEN PolType = 'PKG' THEN
CASE WHEN PkgDef & 1 = 1 THEN 'BA ' ELSE
CASE WHEN PkgDef & 2 = 2 THEN 'BAT' ELSE
CASE WHEN PkgDef & 4 = 4 THEN 'GS ' ELSE
CASE WHEN PkgDef & 8 = 8 THEN 'DLR' ELSE
... | If you are using Microsoft SQL Server then you might be trying to do this:
```
SELECT
CASE
WHEN PolType = 'PKG' THEN
CASE
WHEN PkgDef & 1 = 1 THEN 'BA '
WHEN PkgDef & 2 = 2 THEN 'BAT'
WHEN PkgDef & 4 = 4 THEN 'GS '
WHEN PkgDef & 8 = 8 THEN 'DLR'
... | Not testet, but try:
```
SELECT CASE WHEN PolType <> 'PKG' THEN poltype
WHEN PkgDef & 1 = 1 THEN 'BA '
WHEN PkgDef & 2 = 2 THEN 'BAT'
WHEN PkgDef & 4 = 4 THEN 'GS '
WHEN PkgDef & 8 = 8 THEN 'DLR'
ELSE 'ERR'
END AS 'PolType'
FROM Parallel_Test.dbo.PolicyG
WHERE rowid = (SELECT MAX(rowid) FROM Parallel_Test.dbo.policyg... | Nested CASE ELSE END Syntax Error | [
"",
"sql",
"sql-server",
""
] |
Say I have a table with columns: `id, group_id, type, val`
Some example data from the select:
`1, 1, 'budget', 100`
`2, 1, 'budget adjustment', 10`
`3, 2, 'budget', 500`
`4, 2, 'budget adjustment', 30`
I want the result to look like
`1, 1, 'budget', 100`
`2, 1, 'budget adjustment', 10`
`5, 1, 'budget t... | As @Serpiton suggested, it seems the functionality you're really looking for is the ability to add sub-totals to your result set, which indicates that `rollup` is what you need. The usage would be something like this:
```
SELECT id,
group_id,
coalesce(type, 'budget total') as type,
sum(val... | This will get the you two added lines desired, but not the values for ID and type that you want.
Oracle examples: <http://docs.oracle.com/cd/B19306_01/server.102/b14223/aggreg.htm>
```
Select id, group_id, type as myType, sum(val) as sumVal
FROM Table name
Group by Grouping sets ((id, group_id, type, val), (group_ID)... | Oracle SQL: Adding row to select result | [
"",
"sql",
"oracle",
""
] |
Here is my challenge:
I have a log table which every time a record is changed adds a new record but puts a NULL value for each non-changed value in each record. In other words only the changed value is set, the rest unchanged fields in each row simply has a NULL value.
Now I would like to replace each NULL value with t... | One the new windowed function of SQLServer 2012 is `FIRST_VALUE`, wich have quite a direct name, it can be partitioned through the `OVER` clause, before using it is necessary to divide every column in data block, a block for a column begin when a value is found.
```
With Block As (
Select ID
, Owner
, ... | As I mentioned in my comment, I would try to fix the process that is creating the records rather than fixing the junk data. If that is not an option, the code below should get you pointed in the right direction.
```
UPDATE t1
set t1.owner = COALESCE(t1.owner, t2.owner),
t1.Status = COALESCE(t1.status, ... | Replace NULL with values | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am attempting to calculate the average of a percentage that needs to take into account percentages that are zero.
I am currently using the following formula to exclude those that will ultimately end up as zero, but this is skewing the figures.
```
SET Average = (SELECT ROUND(AVG((CAST(Figure1 AS FLOAT)/CAST(F... | The problem would be dividing by zero - so only `figure2` is relevant which is the divident.
Use a `case` statement to set a static value for that specific case (I chose `0`):
```
SET Average = (SELECT ROUND(AVG(case when Figure2 = 0
then 0
els... | While the answer of
```
SET Average = (SELECT ROUND(AVG(case when Figure2 = 0
then 0
else CAST(Figure1 AS FLOAT) / CAST(Figure2 AS FLOAT)
end * 100)
,2)
FROM [Schema].[Table] m)
```
is good... | Include zero figures in calculation without getting divide by zero errors | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an SQL statement I run for my website that inserts data into an access database. Is there a way during the insert to replace a space " " if one of the date textboxes contains a space? I need to do this because it throws off my date queries if there is a space in one of the columns?
```
INSERT INTO tblOpen (Date... | You should use the 'datetime' type for your DateColumn. It solves all your problem. It is good to use proper variable for proper field. | If you mean heading and trailing spaces, then:
```
myString = myString.Trim()
```
in your vb.net code will be fine. Even though I would follow Steve's suggestion and converting to date. | SQL Insert and Replace? | [
"",
"asp.net",
"sql",
"vb.net",
"ms-access",
""
] |
Can't seem to get this working. If the count is null I want to set it to zero... else set it to the count. I am adding multiple counts in another part of my code so I cannot have null values when I do this.
$table = "
...
```
LEFT JOIN
(SELECT user_id, IF(count(user_id) = '(null)',0,count(user_id)) as t1count
... | In the outer query, you can replace a `NULL` with a zero using the **`IFNULL()`** function, e.g.
```
SELECT ...
, IFNULL(v.t1count,0) AS t1count
FROM ...
LEFT
JOIN ( SELECT ... AS t1count
...
) v
ON ...
```
---
The NULL you are getting returned by the outer query isn't from the ... | The aggregate COUNT() will always return a value.
Reference: [Does COUNT(\*) always return a result?](https://stackoverflow.com/questions/2552086/does-count-always-return-a-result) | if count value is null set it to zero - sql select statement | [
"",
"mysql",
"sql",
"count",
""
] |
I'm trying to calculate the average time a person is a member, before he/she becomes a paying member.
I'm trying to select the ID-Date of creation - Date of first payment - time between creation and first payment - Average of the time between creation and first payment:
```
SELECT C.CompanyId, C.CreatedDate, CO.Creat... | Didn't know how to mark my question as answered.
But I found the solution:
I used DATEDIFF <http://www.w3schools.com/sql/func_datediff.asp>
DATEDIFF(DAY,C.CreatedDate, CO.CreatedDate) in order to remove the different datetime values, and get the difference and used AVG around it: AVG(DATEDIFF(DAY, C.CreatedDate,CO.Cr... | You have to group by some values to let the database know where the `avg` is applied to:
```
SELECT C.CompanyId
, AVG(CAST(CO.CreatedDate - C.CreatedDate as int)) AS Average
FROM XXX.Company C
GROUP
BY C.CompanyId
```
Also, you average and diff are conflicting, so you have to disable the cast then.
If you... | Get AVG() of CAST() | [
"",
"sql",
"sql-server-2008",
""
] |
I have to find a composition of data stored in a database to fullfill a input value using sql.
Table first
```
ID| Value |
1 | 8 |
2 | 10 |
3 | 12 |
4 | 14 |
```
Table values
```
ID| Value |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
5 | 6 |
```
If the input value is 8, i have to f... | If you are looking for pairs, you do a join with a condition:
```
select t1.Value, t2.Value
from table t1 join
table t2
on t1.Value + t2.Value = 8;
```
EDIT:
If you actually want to get 1 and 5 but not 5 and 1, then you need to use distinct and another condition in the `on` clause:
```
select distinct t1.... | You can do a self-`CROSS JOIN` and check against the total. The `<=` condition is to prevent duplicates arising from the recipical:
```
SELECT t1.ID, t2.ID
FROM tbl t1 CROSS JOIN tbl t2
WHERE t1.value + t2.value = 8
AND t1.ID <= t2.ID
``` | SQL query composition search | [
"",
"mysql",
"sql",
""
] |
So in a facebook like wall we have the entities:
WallPost. (id, user\_id, message)
User. (id, name)
Connections. (user1\_id, user2\_id)
I want with one SQL query to get all the wall posts of a user with id: x (example 5)
I tried:
```
select wallPost.* from
wallPost, Connections
Where
wallPost.user_id = x
or
(Conne... | You only want records from `wallPost`. I would suggest that you remove `Connections` table in the `from` clause and put the logic in subqueries using `exists`:
```
select wp.*
from wallPost wp
where wp.user_id = x or
exists (select 1 from Connections c where c.user1_id = x and wp.user_id = c.user2_id) or
... | Why cant you do this?
```
SELECT WP.* FROM [WallPost] WP WITH (NOLOCK)
LEFT JOIN [Connections] CN WITH (NOLOCK)
ON ((WP.[User_Id] = CN.[User1_Id]) OR (WP.[User_Id] = CN.[User2_Id))
WHERE (WP.[User_Id] = X)
```
The LEFT JOIN will take care of users who have no connections. | Is there a way to improve this SQL query with 3 entities? | [
"",
"sql",
"join",
""
] |
I've been tasked with writing a query to display report assignments from our company's database. There are three tables I need to query: REPORT, which contains the top-level information of the report, PROCEDURE, which can contain multiple results per report on the individual report procedures, and TECHNICIAN, which can... | Here is the query.
```
SELECT
rep.RPT_ID
,tech.TECH_ID
,proc.PROC_ID
FROM REPORT rep
LEFT JOIN TECHNICIAN tech ON tech.RPT_ID = rep.RPT_ID
LEFT JOIN PROCEDURE proc ON proc.RPT_ID = rep.RPT_ID AND proc.PROC_ID = tech.PROC_ID
WHERE rep.LAB_ID in ('test_lab');
``` | The problem is that you have `and proc.PROD_ID = tech.PROD_ID` in the `WHERE` clause.
You should move this into the `LEFT JOIN` of proc
`LEFT JOIN PROCEDURE proc ON proc.RPT_ID = rep.RPT_ID and proc.PROD_ID = tech.PROD_ID`
Think of it this way, if your query, the SQL joins the tables using the join criteria and then... | How to return null value if no record found on joined table | [
"",
"sql",
"sql-server",
"t-sql",
"left-join",
""
] |
For example, my table data looks like this:
```
ID intValue date
1 5 1/1/1
1 10 22/22/22
```
What I want to do is multiply the `intValue` column by 5, 10, and 15 for each instance of intValue.
So my result set would like like:
```
ID intValue date
1 25 ... | Leverage CROSS JOIN and Values
```
SELECT ID, table1.intValue * Val.N, date
FROM table1
CROSS JOIN (VALUES (5), (10), (15)) Val(N)
``` | This solution only uses a single `union`, rather than unioning the table to itself:
```
WITH numbers
AS ( SELECT 5 AS n
UNION ALL
SELECT n + 5
FROM numbers
WHERE n + 5 <= 15
)
SELECT id ,
intValue + n AS i... | Apply Computation And Return As Another Row Without Union | [
"",
"sql",
"sql-server",
"row",
""
] |
In Oracle SQL, you can easily do an update based on a NOT EXISTS condition in a correlated subquery. This is useful for doing updates based on another query or list of ids.
The mechanism for subqueries is different in Postgres... how can I achieve the same goal?
<http://sqlfiddle.com/#!1/1dbb8/55>
**How you would do ... | Sqlfiddle does regenerate the db contents for each time you "run script", apparently. Run the select in the same script as the update.
Your Oracle query from sqlfiddle almost works, but You forgot to alias the userid parameter. Correct query:
```
/* How you would do it on Oracle */
UPDATE UserInfo
SET username = 'not... | ```
UPDATE UserInfo a
SET username = 'not found'
WHERE NOT EXISTS (
SELECT 'X'
FROM UserOrder b
WHERE b.userid = a.userid
)
AND a.userid in (1,2,3)
;
```
Should definitely work in Postgres. | Postgres: correlated subquery with NOT EXISTS | [
"",
"sql",
"oracle",
"postgresql",
""
] |
I'm trying to add a column in where clause in SQL Server 2005, but issue is I have to add it for a given condition like
```
where condition 1
and condition 2
if(@val !=null and @val = 'test')
begin
and condition 3
end
```
but when I try this SQL Server gives me error:
```
Incorrect syntax near the keyword 'and'. Se... | Thanks for all to answer the question, but I used a little trick to solve the problem in this way
```
if(@spm='David')
begin
select *
from Tables with joins
where ac_jd_date_closed >= convert(VARCHAR(10),dateadd(dd, -@period, getdate()), 101)
and ac_jd_date_closed <= convert(VARCHAR(10),dateadd(dd, 0, get... | You can remove the `CASE` statement and substitute `AND (@Val<> 'test' OR (@Val = 'test' AND condition 3))`:
```
WHERE <condition 1>
AND <condition 2>
AND (@Val<> 'test' OR (@Val = 'test' AND <condition 3>))
``` | using if/case in sql server where clause | [
"",
"sql",
"sql-server",
""
] |
If i have the string:
```
[30.345, -97.345, 4],[30.345, -97.345, 5],[30.345, -97.345, 6],[30.345, -97.345, 7]
```
How would i remove every third comma, so that the string would look like this?
```
[30.345, -97.345, 4][30.345, -97.345, 5][30.345, -97.345, 6][30.345, -97.345, 7] ?
```
Thanks in advance. | how about replacing `],[` with `][`
```
SELECT REPLACE('[30.345, -97.345, 4],[30.345, -97.345, 5],[30.345, -97.345, 6],[30.345, -97.345, 7].','],[','][');
``` | sql is to general, need more info.
Here is ORACLE:
select replace('your string', '],[', '][') from dual | Removing commas from a string using SQL | [
"",
"sql",
""
] |
SQL is not my strong point and I am struggling to find a solution to this issue. I am trying to figure out how I can get a result set based on the following logic. Select record A when A is not in B OR select B if the record appears in B and A. I tried the following union which returns me all the records that match fro... | You can do a left outer join, and use a ISNULL or CASE statement in the select to return the required values.
I'll demonstrate:
```
SELECT
CASE WHEN b.iPurchaseOrderLineId IS NOT NULL THEN 'b' ELSE 'a' END AS [Source],
a.iPurchaseOrderLineId,
ISNULL(b.sProductDescription, a.sProductDescription) AS [sProd... | Hope This will help You: Just an example similar to you.
```
create table A(id int , name char(12))
go
create table B(id int , name char(12))
go
insert into A values (1,'ABC'),(3,'WXY')
insert into B values (1,'ABC'),(2,'AAA')
SELECT a.id,a.name FROM A EXCEPT SELECT * FROM B
UNION
SELECT a.id,a.name FROM A inn... | SQL: Select A when in A and not B or select B when in A and B | [
"",
"sql",
"sql-server",
""
] |
I have following data:
```
Id: 1 Name: apple ForeignKey: 10
Id: 2 Name: apple ForeignKey: 10
Id: 3 Name: apple ForeignKey: 15
Id: 4 Name: peach ForeignKey: 11
Id: 5 Name: peach ForeignKey: 12
```
Rows with same Name and ForeignKey are duplicates in... | The answer if database specific, but here is how you can do it joining the table to itself:
```
delete t1
from yourtable t1
join yourtable t2 on t1.id > t2.id
and t1.name = t2.name
and t1.foreignkey = t2.foreignkey
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/7c122/1) | You can also do it with a CTE & window function, deleting the duplicate rows by counting the number of rows that are the same, and then deleting all but one.
[SQL Fiddle demo](http://www.sqlfiddle.com/#!3/fc217/2)
```
;WITH myvals
AS (
SELECT [id]
,[name]
,[foreignkey]
,ROW_NUMBER() OVER (... | How to delete duplicate rows in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a pivot table on one sheet that is coming from a Microsoft Query MySQL datafeed on another one of my sheets.
Consider the information from the datafeed to be like so:
```
date | order | SKU | Quantity
-----------------------------------
5/1/14 123456 11111 1
5/1/14 234567 22222 1
5/1/14 ... | The solution was that the "quantity" column in the MySQL database was VARCHAR. Once the column was changed to INT and the datafeed was refreshed, the pivot table worked fine. | I am guessing that your query returns these numbers as text. If you input three 1's in cells preceded by an apostrophe to signal Excel that you want them to be considered strings and then use SUM() over that range it will yield zero. Consider converting your column to numbers. | SUM function in Pivot Table Not Working | [
"",
"mysql",
"sql",
"excel",
"pivot-table",
"ms-query",
""
] |
I am trying to create a query that returns the **accountservice\_id** with the MAX **fromdate** for each **service\_id**. Each **service\_id** can have multiple **accountservice\_id**'s tied to it and unfortunantly the MAX **accountservice\_id** doesn't always have the MAX **fromdate**.
For example:
```
service_id ... | You can do subqueries to get the data. Use one query to get the maximum fromdate for the service\_id, then join that to a search for the accountservice\_id that matches the service\_id and max fromdate.
```
SELECT maxfromdate.service_id, correct_account.accountservice_id, maxfromdate.maxfromdate
FROM (SELECT
Serv... | CTE + `ROW_NUMBER()` is a winning combo.
```
;with cte as (
SELECT service_id,
accountservice_id,
max_date_rank = row_number()
over(partition by service_id
order by fromdate desc)
FROM service
)
SELECT *
FROM cte
WHERE max_date_r... | Choose row based on MAX date (multiple tables) | [
"",
"sql",
"sql-server",
"reporting-services",
"greatest-n-per-group",
"ssrs-2008-r2",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.