Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How can I use my query to find data which are only equal to today and future? Which mean any data with date that pass today, will not shown. I have this query, but my syntax might be wrong. Please assist me:
```
strSQL = "SELECT * FROM kiosk_directory.tbldetails where start_date='" & today & "' andalso start_date!<='"... | ```
SELECT * FROM kiosk_directory.tbldetails where start_date >= Cast(Now() As Date)
```
Or any Date in accepted MySql Formats I usually go with 'YYYY-MM-DD' cause for whatever reason I don't mix up the days/months (I grew up learning both MM-DD and DD-MM).
```
SELECT * FROM kiosk_directory.tbldetails where start_dat... | You haven't said which RDBMS you're using, but this would be the query in mysql:
`SELECT * FROM kiosk_directory.tbldetails where TO_DAYS(start_date) >= TO_DAYS(NOW())`
I'm using TO\_DAYS assuming start\_date is a timestamp. If it only contains dates without a time component, then it's not necessary to use TO\_DAYS() | SQL statement for starting date and over | [
"",
"mysql",
"sql",
""
] |
I have the following query:
```
SELECT
p.CategoryID
,p.Category_Name
,p.IsParent
,p.ParentID
,p.Sort_Order
,p.Active
,p.CategoryID AS sequence
FROM tbl_Category p
WHERE p.IsParent = 1
UNION
SELECT
c.CategoryID
,' - ' + c.Category_Name AS Category_Name
,c.IsParent
,c.ParentID
,c.Sort_Order
,c.Active
,c... | This is how I would do it, assuming the tree that the parent-child relationship represents is only two levels deep.
```
SELECT *
FROM
(
SELECT p.CategoryID
, p.Category_Name
, p.IsParent
, p.ParentID
, p.Active
, p.Sort_Order as Primary_Sort_Order
, NULL as Secondary_Sort_Or... | After a lot of searches I have come with a solution for the problems like this It can resolve your Issue.
Here I have another sort order column which selects the same sort order of its parent records. Using this Secondary SortOrder Order the record first, then group the child records under Parent
```
CASE WHEN ParentI... | SQL Order by, parent, child, and sort order | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I found a weird behaviour from Active Record Pluck.
My query is
```
Friend.joins('INNER JOIN users ON friends.friend_id = users.id').where("user_id=? AND (status=? or status=?)", 4,"true","").pluck("users.first_name, users.last_name")
```
It is to join with friends with users and get users first name and last name
... | config/initializers/pluck\_all.rb
```
module ActiveRecord
class Relation
def pluck_all(*args)
args.map! do |column_name|
if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
"#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
else
column_... | If you're using rails 4 you can do
Instead of
```
.pluck("users.first_name, users.last_name")
```
Try
```
.pluck("users.first_name", "users.last_name")
```
In rails 3 you'll want to use select to select those specific fields
```
.select("users.first_name", "users.last_name")
``` | Retrieving multiple Records,columns using Joins and pluck | [
"",
"sql",
"ruby-on-rails",
"activerecord",
"join",
"pluck",
""
] |
I am asking your help about a join I have to do.
I have a field **Date** as DD/MM/YYYY.
I have to join it on an other table with a field with data like **A14**, for year 2014 for example.
Do you know how can I get only the two last characters from field **Date**, add to it the character **A**, to to the join with my ... | If your datefield is of date data-type, then
```
SELECT 'A' || TO_CHAR (DATEFIELD, 'YY') FROM MY_TABLE;
```
**Example:**
```
SELECT 'A' || TO_CHAR (SYSDATE, 'YY') FROM MY_TABLE;
```
But I assume from your example, DATE is a string in format DD/MM/YYYY
You can probably try something like,
1. Convert the String to D... | As an alternative to concatenation, and if your date field is actually a `DATE` not a string, you can include fixed values in a date format model if they're in double-quotes:
```
select to_char(sysdate, '"A"YY') from dual;
TO_
---
A14
```
So to join with that you could do:
```
select <columns>
from my_table
join ot... | SQL Oracle - YY from date and add character | [
"",
"sql",
"oracle",
"join",
""
] |
i want to display `department_id`'s along with count,and count should be more than 5, and i want to have employees who are not hired in January.
i tried the below query
```
SELECT * FROM EMPLOYEES
WHERE DEPARTMENT_ID IN
(
SELECT DEPARTMENT_ID
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
HAVING COUNT(*)>5
)
... | ```
SELECT department_ID, count(employee_id) as '# of Employees' FROM EMPLOYEES
WHERE DEPARTMENT_ID IN
(
SELECT DEPARTMENT_ID
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
HAVING COUNT(*)>5
)
AND HIRE_DATE NOT LIKE '%JAN%'
group by department_ID;
```
This query returns the department\_id and because I group b... | If you want the dept id and count of employees (where employee hire date is not in Jan) then something like the following should work. I say "something like the following" because I suspect the WHERE hire\_date NOT LIKE '%JAN%' could be improved, but it would just depend on the format of that column.
```
SELECT
... | employee department wise and count of employees more than 5 | [
"",
"sql",
"oracle",
""
] |
I need to set `CONTEXT_INFO` variable in SQL Server to user session unique identifier, GUID of user's session to be exact.
But I cannot perform this operation in more or less short and clean one-liner. I'm obligatory to create new binary variable and only than assign it to the `CONTEXT_INFO`.
It looks like this:
```... | According to:
<http://msdn.microsoft.com/en-us/library/ms187768.aspx>
"SET CONTEXT\_INFO does not accept expressions other than constants or variable names. To set the context information to the result of a function call, you must first include the result of the function call in a binary or varbinary variable. " | Transact-SQL is a *very* simple language. In most modern languages, you'd expect to be able to supply an arbitrary expression in most locations where a simple value was valid - but that's not the case with T-SQL. So, if we look at the syntax diagram for [`SET CONTEXT_INFO`](http://msdn.microsoft.com/en-us/library/ms187... | Why I cannot set T-SQL CONTXT_INFO variable in one line statement? | [
"",
"sql",
"sql-server",
""
] |
I want to check if table A has any entry THEN ONLY check table A column value is present in table B. If there is no data in TableA then just get data from TableB.
I want to have Exists clause for TableB select query if and only if there is data in TablaA else it will be just plain select query for TableB
Inner join w... | ```
select b.* from tableB b, tableA A
Where b.id = a.id
```
a simple join is enough for this.
Other way is using `EXISTS`. And put your conditions inside it.
```
select * from tableB b
Where exists
(Select 'x' from tableA a
Where a.id=b.id)
```
**EDIT:**
hope you need this.
```
/* first part returns result onl... | ```
select b.id
from table_a a
, table_b b
where a.col = b.id
and a.col_val = 'XXX';
``` | SQL : If condition in where clause | [
"",
"sql",
"oracle",
""
] |
I have a `users` table
```
Table "public.users"
Column | Type | Modifiers
--------+---------+-----------
user_id | integer |
style | boolean |
id | integer |
```
and an `access_rights` table
```
Table "public.access_rights"
Column | Type | Modifiers
--------+---------+-----------
user_id | integer... | If you are interested in the number of users that have *at least* 1 row with (`style IS TRUE`) in `access_rights`, aggregate `access_rights` before you join:
```
SELECT count(style OR NULL) AS style_ct
FROM users
JOIN (
SELECT user_id, bool_or(style) AS style
FROM access_rights
GROUP BY 1
) u USING (... | You could do this:
Try something like this (per [the documentation](http://www.postgresql.org/docs/7.4/static/datatype-boolean.html))
```
select sum( case style when TRUE then 1 else 0 end ) as style_count
from public.users u
join public.access_rights ar on ar.user_id = u.user_id
```
Or, considering your pro... | SQL counting unique true values on join table | [
"",
"sql",
"postgresql",
"join",
"count",
"aggregate-functions",
""
] |
There is a procedure which tries to fetch details of project/s from PROJECTS table.
The snippet goes here:
```
PROCEDURE GET_PROJECTS (
P_PROJECT_ID_LIKE IN VARCHAR2 DEFAULT '%',
P_SEPARATOR IN VARCHAR2 DEFAULT '-=-' )
AS
CURSOR PROJECTS_CURSOR IS
.....
WHERE
... | An implicit type conversion will take place. Notice `1 - filter(TO_CHAR("N") LIKE 'asdf%')` in predicate information section.
```
15:13:51 (133)LKU@sandbox> create table t (n number);
Table created.
Elapsed: 00:00:00.10 ... | As @be here now suggested an implicit conversion will take place. This will work 99% of the times but there are some cavets when reaching big numbers.
Take this scenario for example,
```
SQL> select to_char(power(2,140)) from dual;
TO_CHAR(POWER(2,140))
----------------------------------------
1.39379657490816394634... | Is it allowed to use LIKE for NUMBER datatype? | [
"",
"sql",
"oracle",
"sql-like",
""
] |
I made a silly mistake at work once on one of our in house test databases. I was updating a record I just added because I made a typo but it resulted in many records being updated because in the where clause I used the foreign key instead of the unique id for the particular record I just added
One of our senior develo... | First assume you will make a mistake when updating a db so never do it unless you know how to recover, if you don't don't run the code until you do,
The most important idea is it is a dev database expect it to be messed up - so make sure you have a quick way to reload it.
The do a select first is always a good idea t... | It seems to me that you just need to get into the habit of opening a transaction:
```
BEGIN TRANSACTION;
UPDATE [TABLENAME]
SET [Col1] = 'something', [Col2] = '..'
OUTPUT DELETED.*, INSERTED.* -- So you can see what your update did
WHERE ....;
ROLLBACK;
```
Than you just run again after seeing the results, ch... | How to test your query first before running it sql server | [
"",
"sql",
"sql-server",
""
] |
I'm not sure if what I'm looking to do is possible with a union, or if I need to use a nested query and join of some sort.
```
select c1,c2 from t1
union
select c1,c2 from t2
// with some sort of condition where t1.c1 = t2.c1
```
Example:
```
t1
| 100 | regular |
| 200 | regular |
| 300 | regular |
| 400 | regular |... | Try:
```
select c1, c2
from t1
where c1 in (select c1 from t2)
union all
select c1, c2
from t2
where c1 in (select c1 from t1)
```
Based on edit, try the below:
MySQL doesn't have the WITH clause which would allow you to refer to your t1 and t2 subs multiple times. You might want to create both t1 and t2 as a ... | An `UNION` is okay.
You want to run the same join **twice**. Except that the first time over you get the left side, and the second time the right side.
```
SELECT t1.* FROM t1 JOIN t2 USING (c1)
UNION
SELECT t2.* FROM t1 JOIN t2 USING (c1)
```
Of course, if at all possible, you could run a single query and save the ... | Adding conditions to a UNION in MySQL | [
"",
"mysql",
"sql",
""
] |
Having executed a DB deploy (from a VS SQL Server database project) on a local database, which failed, the database has been left in a state where it has single user mode left on (the deploy runs as single user mode).
When I connect to it from SSMS and try something like the following:
```
ALTER DATABASE MyDatabase
S... | In first run following query in master database
```
exec sp_who
```
If you can't find the culprit, try
```
SELECT request_session_id FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID('YourDatabase')
```
Then kill all process that use your database with following query:
```
KILL spid
```
Then run followin... | Try the below commands
First run these three commands
```
USE [master]
SET DEADLOCK_PRIORITY HIGH
exec sp_dboption MyDBName, 'single user', 'FALSE';
```
Second run these two commands
```
ALTER DATABASE MyDBName SET MULTI_USER WITH NO_WAIT
ALTER DATABASE MyDBName SET MULTI_USER WITH ROLLBACK IMMEDIATE
``` | SQL Server 2008 R2 Stuck in Single User Mode | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"database-deployment",
""
] |
I want to update 1 column only for all rows in my table with the total calculation of :
The data of column multiply with random number between 0.9 to 1.2..
```
UPDATE TABLE
SET ABC = (SELECT ABC*(RAND()*((1.2-0.9)+0.9)) FROM TABLE)
```
Well idk how to write it in a proper T-SQL. I didn't get the expected result in SQ... | ```
SET NOCOUNT ON
DECLARE
@ABC_ID AS INT,
@RANDOM_GEN_NO AS VARCHAR(50),
@TEMP AS VARCHAR(50)
DECLARE ABC_CURSOR CURSOR FOR
SELECT @ABC_ID, RANDOM_GEN_NO FROM ABCTABLE FOR UPDATE OF RANDOM_GEN_NO
OPEN ABC_CURSOR
FETCH NEXT FROM ABC_CURSOR
INTO @EMP_ID, @R... | Think you have a problem of parenthesis (for the rand "range"), than the way to write the query (if I understood well)
```
update table
set abc = abc * (RAND() * (1.2-0.9) + 0.9)
```
**CAUTION**
the "random" multiplicator will be the same for all the rows updated by this statement, as noticed by Damien\_The\_Unbelie... | How to update 1 column only but to all rows with a calculation? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a field in Oracle that has a blank character at the end so instead of it reading "12345" it reads "12345 "
The length of this field differs on different records but may also have a blank at the end. How may I write in SQL to identify those records that have a blank at the end? | try this
```
Select ColumnName from tablename where columnname like '% '
``` | this untested query should do what you want:
```
select * from tabler where length(col)>length(rtrim(col));
```
This query compares the length of the string including trailing blanks with the length after trailing blanks have been removed by the RTRIM function, and only returns rows where these two lengths differ. | SQL fields with blank space at end of fields | [
"",
"sql",
"oracle",
""
] |
I have four tables in Access 2010, each with the same primary key. I'd like to join all the data in all four tables into one table with columns for each value tied to the primary key over all the tables. So, for example:
```
Table1
ID Value1
1 10
2 7
3 4
4 12
Table 2
ID Value2
1 33
2 ... | How about this?
```
SELECT id
, max(v1) as value1
, max(v2) as value2
, max(v3) as value3
FROM
(
select id
, value1 as v1
, iif(true,null,value1) as v2
, iif(true,null,value1) as v3
from Table1
union
select id, null , value2 , null from Table2
union
select id, null , null ,... | Create an union of all the ids from all tables, this way you get the id column in table4. Then encapsulate this union in a subselect (ids) and create left joins between this subselect (the parent join) and table1, table2, table3 (the childs join). Then select what you need...
```
SELECT
ids.id,
t1.Value1,
t2.Value2... | SQL Joins and MS Access - How to combine multiple tables into one? | [
"",
"sql",
"ms-access",
"join",
"ms-access-2010",
""
] |
I have a table in which I store a log of every request to a web site. Every time a page is requested, a record is inserted. I now want to analyze the data in the log to detect possible automated (non-human) requests. The criteria I need to use is x number of requests within y seconds by an individual user.
So, the dat... | Here is the query which you are looking for:
```
SELECT
T1.Page,
T1.UserId,
T1.Date,
MIN(T2.Date) AS Date2,
DATEDIFF(minute, T1.Date, MIN(T2.Date)) AS DaysDiff,
COUNT(*) RequestCount
FROM
[STO24541450] T1 LEFT JOIN [STO24541450] T2
ON T1.UserId = T2.UserId AND T2.Date > T1.Date
GROU... | I would probably group by the time range and UserId and grab any with a count greater than 5.
```
select count(*),
UserId,
dateadd(SECOND, DATEDIFF(SECOND, '01-jan-1970', [date])/5*5, '01-jan-1970')
from [LogTable]
group by UserId, DATEDIFF(SECOND, '01-jan-1970', [date])/5
having count(1) > 5
```
The... | How to query for records that have a certain count within a timespan | [
"",
"sql",
"sql-server",
""
] |
I have been trying to run debugging within SQl server management studio and for some reason the debugger has just stopped working.
This is the message I get:
> Unable to start the Transact-SQL debugger, could not connect to the
> database engine instance 'server-sql'. Make sure you have enabled the
> debugging firewa... | In the end I was able to start it by right clicking and selecting run as administrator. | I encountered this issue while connected to SQL using a SQL Server Authenticated user. Once I tried using a Windows Authenticated user I was able to debug without issue. That user must also be assigned the sysadmin role. | Unable to start the Transact-SQL debugger, could not connect to the database engine instance | [
"",
"sql",
"t-sql",
"debugging",
""
] |
I'm trying to find an intuitive way of enforcing mutual uniqueness across two columns in a table. I am not looking for composite uniqueness, where duplicate *combinations* of keys are disallowed; rather, I want a rule where any of the keys cannot appear again in *either* column. Take the following example:
```
CREATE ... | You could create an "external" constraint in the form of an indexed view:
```
CREATE VIEW dbo.OccupiedRooms
WITH SCHEMABINDING
AS
SELECT r.Id
FROM dbo.Occupants AS o
INNER JOIN dbo.Rooms AS r ON r.Id IN (o.LivingRoomId, o.DiningRoomId)
;
GO
CREATE UNIQUE CLUSTERED INDEX UQ_1 ON dbo.OccupiedRooms (Id);
```
The view... | I think the only way to do this is to use constraint and a Function.
Pseudo code (haven't done this for a long time):
```
CREATE FUNCTION CheckExlusiveRoom
RETURNS bit
declare @retval bit
set @retval = 0
select retval = 1
from Occupants as Primary
join Occupants as Secondary
on Primary.Living... | Enforcing mutual uniqueness across multiple columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am new to server side programming and am trying to understand relational databases a little better. Whenever I read about MYSQL vs SQLite people always talk about SQLite not being able to have multiple users. However, when I program with the Django Framework I am able to create multiple users on the sqlitedb. Can som... | When people talk about multiple users in this context, they are talking about simultaneous connections to the database. The users in this case are threads in the web server that are accessing the database.
Different databases have different solutions for handling multiple connections working with the database at once.... | As you can read [here](https://stackoverflow.com/a/5102105/2108339), sqlite supports multi users, but lock the whole db.
Sqlite is used for development ussualy, buy Mysql is a better sql for production, because it has a better support for concurrency access and write, but sqlite dont.
Hope helps | What is the difference between MYSQL and SQLite multi-user functionality? | [
"",
"mysql",
"sql",
"database",
"sqlite",
""
] |
im trying to make a method that return the value from the database and im getting CursorIndexOutOfBounds:
(The Line 94 is : String count = c.getString(1);)
```
public String getCount() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_COUNT };
Cursor c = our... | move `c.moveToFirst()` inside the if statement. if that returns false then the cursor is empty and would get that error
```
if (c != null && c.moveToFirst())
``` | cursor starts from '0' use this:
```
String count = c.getString(0);
``` | Cursor Index Out Of Bounds while trying to get a value from the database | [
"",
"android",
"sql",
""
] |
With this schema:
```
CREATE TABLE BAR (id INT PRIMARY KEY);
CREATE TABLE FOO (id INT PRIMARY KEY, rank INT UNIQUE, fk INT, FOREIGN KEY (fk) REFERENCES Bar(id));
INSERT INTO BAR (id) VALUES (1);
INSERT INTO BAR (id) VALUES (2);
-- sample values
INSERT INTO FOO (id, rank, fk) VALUES (1, 10, 1);
INSERT INTO FOO (id, r... | It doesn't like the subquery inside the temporary table. The trick is to left join all the secondary rows with `rank` less than the target's `rank`, then use the WHERE clause to filter out all but the max while being sure not to filter out target rows with no secondary.
```
select F1.id as TARGET_ID, F1.rank as TARGET... | You need [Analytic Functions](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm)
```
select id,
lead(rank) over (partition by fk order by rank) next_rank
lag(rank) over (partition by fk order by rank) prev_rank
from foo
```
It is more efficient than self joins.
But if you want to torture your ... | How can I reference an outer table in a subquery for a self left join? | [
"",
"sql",
"oracle",
"self-join",
"correlated-subquery",
""
] |
I have table like:
**Items**
* ID(int)
* Name(varchar)
* Date(DateTime)
* Value(int)
I would like to write SQL Command which will update only these values, which are not null
Pseudo code of what I would like to do:
```
UPDATE Items
SET
IF @NewName IS NOT NULL
{
Items.Name = @NewName
}
IF @NewDate IS N... | ```
UPDATE Items
SET Name = ISNULL(@NewName,Name),
[Date] = ISNULL(@NewDate,[Date]),
Value = ISNULL(@NewValue,Value)
WHERE ID = @ID
``` | You cannt use if statement in update you can use below query for update on condition
```
'UPDATE Items
SET
Items.Name = (case when @NewName is not null then @NewName else end) ,
Items.Date = (case when @NewDate is not null then @newDate else end ),
Items.Valie = (case when @Valie is not null then @Valie else end ... | SQL Update command with various variables | [
"",
"sql",
"sql-server",
"t-sql",
"sql-update",
""
] |
I have following requirement for writing a query in oracle.
I need to fetch all the records from a Table T1 (it has two date columns D1 and D2)based on two dynamic values V1 and V2. These V1 and V2 are passed dynamically from application.
The possible values for V1 are 'Less than' or 'Greater than'. The possible value... | You could write this as:
```
select *
from t1
where (v1 = 'Less Than' and D1 - D2 < v2) or
(v1 = 'Greater Than' and D1 - D2 > v2)
```
A `case` statement isn't needed. | Try this:
```
select *
from T1
where case when V1 = 'LESS THAN' THEN D1 - D2 < V2 ELSE D1 - D2 > V2
```
This assume if V1 is not LESS THAN the only other value is greater than. If necessary you can use more than one case statement but this should get you started. | SQL query with decoding and comparison in where clause | [
"",
"sql",
"oracle",
""
] |
Probably the wrong title, but I can't summarise what I'm trying to do nicely. Which is probably why my googling hasn't helped.
I have a list of `Discounts`, and a list of `TeamExclusiveDiscounts` (`DiscountId, TeamId`)
I call a stored procedure passing in `@TeamID (int)`.
What I want is all `Discounts` except if the... | ```
SELECT D.DiscountID FROM Discounts D
LEFT JOIN TeamExclusiveDiscount T
ON D.DiscountID=T.DiscountID
WHERE T.TeamID=@TeamID OR T.TeamID IS NULL
```
[SQLFIDDLE for TEST](http://www.sqlfiddle.com/#!3/5beff/14) | Can you try this - it only selects records where there is a teamdiscount record with the team or no teamdiscount record at all.
```
SELECT * FROM Discounts D
WHERE
EXISTS (
SELECT 1
FROM TeamExclusiveDiscount T
WHERE T.DiscountID = D.DiscountID
AND TeamID = @TeamID
)
OR
NOT EXISTS (
SELECT 1
... | SQL Server - tsql join/filtering issue | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am working on automating the SMS sending part in my web application.
[**SQL Fiddle Link**](http://sqlfiddle.com/#!3/a18de/2)
**DurationType** table stores whether the sms should be sent out an interval of Hours, Days, Weeks, Months. Referred in SMSConfiguration
```
CREATE TABLE [dbo].[DurationType](
[Id] [int] NOT... | Try the simplified version [**FIDDLE**](http://sqlfiddle.com/#!3/24708/65) , removed Union and used OR conditions
**LIST FOR HOURS - RUN Every 15 mins**
```
DECLARE @currentTime smalldatetime = '2014-07-12 11:15:00'
SELECT B.Id AS BookingId, C.Id, C.Name,
B.StartTime AS BookingStartTime,@currentTime As Cu... | You seem to have forgotten to pick some columns to return.
```
DECLARE @currentTime smalldatetime = '2014-07-12 09:15:00';
SELECT [col1], [col2], [etcetera]
FROM
Bookings B
INNER JOIN SMSConfiguration SMS ON SMS.CategoryId=B.CategoryId
WHERE DATEDIFF(hour,B.StartTime,@currentTime)=1
``` | Get records based on Current Date and Configured Data | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"datediff",
""
] |
I have table online\_users\_changes where I store whenever user go online/idle/offline.
```
CREATE TABLE online_users_changes(id INT PRIMARY KEY AUTO_INCREMENT, user_id INT, timestamp TIMESTAMP, status TEXT);
INSERT INTO online_users_changes(user_id, timestamp, status) VALUES
(1, "2014-07-05 9:00", "idle"),
(1, "2014... | You could try this (very similar to bitsm post):
```
select user_id, Max(timestamp) as timestamp, status
FROM online_users_changes
WHERE timestamp < "2014-07-05 11:00"
group by user_id, status
union all
SELECT user_id, timestamp, status
FROM online_users_changes
WHERE timestamp BETWEEN "2014-07-05 11:00" and... | "the most recent event before a given date" = "the first event that took place before a given date, when sorting events in reverse chronological order" =
```
SELECT * FROM online_users_changes
WHERE timestamp < "your date and time here"
ORDER BY timestamp DESC
LIMIT 1
```
Then `UNION` this row with the main query.
B... | How to get the first row before specific date for each user and the rows after in one query? | [
"",
"mysql",
"sql",
"fetch",
"mariadb",
""
] |
I have a column that is a maximum size of 9 characters and I want to do a query that will look at all rows which are less than 9. This:
```
SELECT *
FROM tEmpCourseAssoc
WHERE ({ fn LENGTH(EmployeeID) } < 9)
```
Now I want to add zeros to the front of the column EmployeeID if it's less than 9 characters so it adds up... | You can try this
```
UPDATE tEmpCourseAssoc SET
EmployeeID= RIGHT(REPLICATE('0',9) + EmployeeID, 9)
WHERE LEN(EmployeeID) < 9
``` | ```
SELECT RIGHT(REPLICATE('0', 9) + EmployeeID, 9) AS Expr1
FROM tEmpCourseAssoc
WHERE ({ fn LENGTH(EmployeeID) } < 9)
``` | Add zeros to front of column | [
"",
"sql",
"sql-server",
""
] |
In my `info` DB i have 4 tables, from which TWO are named as `girls` & `boys` and both have `id` column. `boys` contain 12 `id`(12 records) and`girls` contain 8 `id`. when i apply this query:
```
SELECT * FROM
boys
NATURAL JOIN
girls
```
i get output as
```
Empty Set
```
How could this happen? (both `id` column is ... | `NATURAL JOIN` is shorthand for an INNER JOIN with equality predicates on columns of the same name.
For example, given two tables "m" and "f", which have columns named "id" and "name" in common, a NATURAL JOIN like this
```
SELECT ...
FROM m
NATURAL
JOIN f
```
Is equivalent to:
```
SELECT ...
FROM m
JOIN... | Natural join will only work if the same named columns' values are same. ie if ID and Name both are same in both the tables.
If you need result like this :

Then you must name the 'name' col different in both the tables.
If you want a set of all boys and girls, you should ... | why natural join give output as empty set in following situation? | [
"",
"mysql",
"sql",
""
] |
I have a table with a large number of records ( > 300,000). The most relevant fields in the table are:
* CREATE\_DATE
* MOD\_DATE
Those are updated every time a record is added or updated.
I now need to query this table to find the date of the record that was modified last. I'm currently using
```
SELECT mod_date F... | The most efficient way for this query would be to use an index for the column `MOD_DATE`.
From [How MySQL Uses Indexes](http://dev.mysql.com/doc/refman/5.6/en/mysql-indexes.html)
> **8.3.1 How MySQL Uses Indexes**
> Indexes are used to find rows with specific column values quickly.
> Without an index, MySQL must begi... | Make sure that both of those fields are indexed.
Then I would just run -
```
select max(mod_date) from table
```
or create\_date, whichever one.
Make sure to create 2 indexes, one on each date field, not a compound index on both.
As for a discussion of the difference between this and using limit, see [MIN/MAX vs O... | Most efficient query to get last modified record in large table | [
"",
"mysql",
"sql",
""
] |
Let me start first with description of the table I have.
One column is a company id column (integer value), another column is a date in format yyyymmdd (integer value). These two columns taken together uniquely identify the entries in my table. The table (the way I think of it at least) is ordered by Company\_id, Date... | You can use `lead` and `lag`.
```
with C
(
select *,
lag(mycolumn) over(partition by company_id order by Date) as lagmycolumn,
lead(mycolumn) over(partition by company_id order by Date) as leadmycolumn
from YourTable
)
select company_id, Date, mycolumn
from C
where mycolumn <> lagmycolumn or
... | Try this:
```
select company_id, mycolumn, max(date) from
tableName
group by company_id, mycolumn
```
Cheers !! | Select all rows from a table where value on a column differs from previous value on that column | [
"",
"sql",
"sql-server",
""
] |
I have a table named grades. A column named Students, Practical, Written. I am trying to figure out the top 5 students by total score on the test. Here are the queries that I have not sure how to join them correctly. I am using oracle 11g.
This get's me the total sums from each student:
```
SELECT Student, Practical, ... | The approach I prefer is data-centric, rather than row-position centric:
```
SELECT g.Student, g.Practical, g.Written, (g.Practical+g.Written) AS SumColumn
FROM Grades g
LEFT JOIN Grades g2 on g2.Practical+g2.Written > g.Practical+g.Written
GROUP BY g.Student, g.Practical, g.Written, (g.Practical+g.Written) AS SumCol... | You can easily include the projection of the first query in the sub-query of the second.
```
SELECT Student
, Practical
, Written
, tot_score
FROM (
SELECT Student
, Practical
, Written
, (Practical+Written) AS tot_score
, DENSE_RANK() OVER (ORDER ... | Trying to figure out how to join these queries | [
"",
"sql",
"oracle",
"top-n",
""
] |
I have requirement where in I am creating a table dynamically(number of columns may change based on input parameter to my procedure through which I am creating this table) with data in the table like below.
```
PK col1 col2 col3
A null 1-2 3-4
B null null 4-5
C null 5-6 null
```
Now the requirement is I want to... | I used num\_nulls from all\_tab\_cols and achieved result as per my requirement. Thank you. | This won't be very efficient I suspect, but you can use COUNT() to determine if there are any only NULLS in a column because COUNT(column\_here) will only add 1 for each non-null value. Hence if the count is zero that column is only NULLs.
This can then be combined into a query to generate a valid select statement and... | Customize SQL query | [
"",
"sql",
"oracle",
""
] |
There are data in a date column like:
> '2014-03-01', '2014-05-01', '2014-07-01' ...
I want to get distinct years with the IF clause.
For example, if the date is in 'YEAR-07-01' ~ '(YEAR+1)-06-30', then it returns YEAR, else it returns YEAR-1.
For Example, if the data of the date column is like:
> '2000-06-01', '2... | It appears to me you're doing a calculation based on a fiscal year ending 6/30 and starting 7/1.
Try this:
```
select distinct
case when Month(t.DATE) >=7 then Year(t.DATE) else Year(t.DATE)-1 end as FiscalYear
from THE_TABLE t
order by FiscalYear desc
``` | Even better would be to create and use a calendar table. Not only is it easier to work with it can then be flexible across different years.
Take a look at this article. <http://www.sqlservercentral.com/articles/T-SQL/70482/> | Get value with the clause IF and IN | [
"",
"sql",
"sql-server",
""
] |
I have 2 tables right now and they look like the following:
The `points` table looks like the following:
```
id country points
1 4 1
2 7 5
3 8 4
```
The `sample` table looks like the following:
```
id iso pts
1 UK 100
2 US 300
3 AU 7... | You will have to join to the `sample` table twice in order to get the information you are after ([**SQL FIDDLE**](http://sqlfiddle.com/#!2/114ec/4/0)):
```
SELECT p.id, s1.iso AS country, s2.pts AS points
FROM points p
INNER JOIN sample s1 ON p.country = s1.id
INNER JOIN sample s2 ON p.points = s2.id
``` | with the help of left join or any join you can do it
```
select t1.id,t1.country,t1.points from table1 as t1 left join table2 as t2 on t1.id=t2.country
``` | How to SELECT multiple columns with MySQL based on multiple records? | [
"",
"mysql",
"sql",
"join",
""
] |
I have three tables as following
Table a (id,name) as primary key
Table b (id,name,country) as primary key,c\_id as foreign key
Table c (id) as primary key, another column is type
I would like to select id,name,type from these tables, where country='CA'
MY database is MySQL, I wrote the SQL as following:
```
sele... | You have to use AND for multiple criteria joins, not a comma.
```
select n.activity_date,n.advertiser_id,c.type as type
from a
JOIN b as n on a.id=n.id AND a.name=n.name
JOIN c on n.c_id=c.id
where n.country='CA'
limit 10;
``` | Your query should be
```
select n.activity_date,n.advertiser_id,c.type as type
from a JOIN b as n
-- because of the alias name you've got to reference table b as n
-- and you've omitted the AND operator
on (a.id=n.id AND a.name=n.name)
JOIN c
on n.c_id=c.id
where n.country='CA' -- you've got to... | How to join three tables with multiple primary key | [
"",
"mysql",
"sql",
""
] |
When I run the following mysql statement, I get **127 rows** returned:
```
SELECT t.strat_id, t.candle_id, t.spot_entry, t.spot_close, t.f,t.fa,t.b,t.we,t.direct,t.date_created,t.date_closed,t.notes,t.results
FROM cp_user_trades AS t
INNER JOIN candles2 AS c
ON t.candle_id = ... | assuming c.ID is the primary key for the candles2 table:
Use a Left Join and add where c.Id is null | To find ids between to tables, I use `union all` and `group by`:
```
select in_cut, in_c2, count(*) as cnt, min(candle_id), max(candle_id)
from (select candle_id, sum(in_cut) as in_cut, sum(in_c2) as in_c2
from ((select candle_id, 1 as in_cut, 0 as in_c2
from cp_user_trades
) union all
... | Find missing ids between mysql tables | [
"",
"mysql",
"sql",
""
] |
For now I have following query:
```
SELECT "type" AS "modifiedType"
FROM "Table"
WHERE "type" = 'type1' OR "type" = 'type2'
```
What I want is to return `modifiedType` like this:
```
if "type" = 'type1' then 'modifiedType1'
else if "type" = 'type2' then 'modifiedType2'
```
So I just want to modify column value wit... | Use a `CASE` statement:
```
select type,
case
when type = 'type1' then 'modifiedType1'
when type = 'type2' then 'modifiedType2'
else type
end as modifiedType
from the_table
WHERE type in ('type1', 'type2')
```
Btw: `type` is not a good name for a column | A [**simple `CASE`**](http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-CASE#) is more efficient with multiple alternatives for a single condition:
```
SELECT CASE type
WHEN 'type1' THEN 'modifiedType1'
WHEN 'type2' THEN 'modifiedType2'
ELSE type
... | How to transform SELECT output column to arbitrary value based on this column? | [
"",
"sql",
"postgresql",
""
] |
I am trying to count same column for different condition , but I am getting the later count result for the other conditions also.
For this sql :
```
select count(eqa.ID) as gold_yes from EC_SECTION_ANSWER esa , EC_QUESTION_ANSWER eqa
where esa.SC_NUMBER = 1079 and esa.ID = eqa.SC_ID and eqa.QU_ANSWER = 'Yes' and ... | The `WHERE` condition in your query are the problem: you can't have both `eqa.QU_ANSWER = 'Yes'` and `eqa.QU_ANSWER = 'No'`, so the query return 0 rows, and the count of the values of 0 rows is also 0.
You can change the condition to `OR`, or you can take the same condition in the `COUNT`, while doing that you should ... | Put your conditions from the `where` clause into a `case` and sum it up
```
select sum(case when esa.SC_NUMBER = 1079
and eqa.QU_ANSWER = 'Yes'
and eqa.QU_TYPE = 'abc'
then 1
else 0
end) as gold_yes
...
from EC_SECTION_ANSWER esa
jo... | SQL count from same column but different conditions fetching later count result for all | [
"",
"sql",
""
] |
I have data like this:
```
a b c
-------|--------|--------
100 | 3 | 50
100 | 4 | 60
101 | 3 | 70
102 | 3 | 70
102 | 4 | 80
102 | 5 | 90
```
`a` : key
`b` : sub\_id
`c` : value
I want to NULL the `c` row for each element which has non-max `a... | Updated after the requirement was changed to "update the table":
```
with max_values as (
select a,
b,
max(c) over (partition by a) as max_c
from the_table
)
update the_table
set c = null
from max_values mv
where mv.a = the_table.a
and mv.b = the_table.b
and mv.max_c <> the_ta... | ```
DECLARE @TAB TABLE (A INT,B INT,C INT)
INSERT INTO @TAB VALUES
(100,3,50),
(100,4,60),
(101,3,70),
(102,3,70),
(102,4,80),
(102,5,90)
UPDATE X
SET C = NULL
FROM @TAB X
LEFT JOIN (
SELECT A,MAX(C) C
FROM @TAB
GROUP BY A) LU ON X.A = LU.A AND X.C = LU... | Discard rows which is not MAX in that group | [
"",
"sql",
"database",
"postgresql",
""
] |
I am creating a stored procedure (with Sql Server) involving a single table.
I'd like to apply the conditions in my WHERE clause to a pair of columns. i.e. I would like something like this:
```
CREATE PROCEDURE afficherCreationLuns (@start DATE, @end DATE)
AS
SELECT dateMin = M... | You can replace `NOT IN` with `NOT EXISTS`, like this:
```
SELECT
dateMin = MIN(t1.dateCollecte)
, t1.displayName
, t1.label
, date = DATEADD(day, -1, MIN(t1.dateCollecte))
, capacityInKB = MIN(t1.capacityInKB)
FROM Vsp t1
WHERE t1.dateCollecte > @start
AND t1.dateCollecte <= @end
AND NOT EXISTS (
... | You could concatenate the two columns together? Like so:
```
SELECT *
FROM [TABLE]
WHERE COLUMN1+' '+COLUMN2
NOT IN (
SELECT COLUMN1+' '+COLUMN2
FROM [OTHER-TABLE])
```
Thanks. | Can we use NOT IN on multiple columns? | [
"",
"sql",
"sql-server",
"stored-procedures",
"where-clause",
""
] |
If I have two tables like this:
```
CREATE TABLE Director
(
`DirectorNr` INTEGER NOT NULL,
`First Name` VARCHAR (20),
`Last Name` VARCHAR (30),
`Age` INTEGER,
`Movies` INTEGER,
PRIMARY KEY(DirectorNr)
);
CREATE TABLE Movies
(
`MovieNr` INTEGER NOT NULL,
`Title` VARCHAR (100),
`Genre` VARCH... | Join the `director` table and specify the relation in the `on` condition
```
SELECT m.title, d.`First Name`, d.`Last Name`
FROM Movies m
JOIN Director d ON m.Director = d.DirectorNr
```
Beware: With that design you can only have a single director for a movie.
And to escape table or column names use backticks only ar... | ```
SELECT d.`First Name`, d.`Last Name` FROM Director d
WHERE DirectorNr IN (SELECT Director FROM Movies WHERE Director=value );
``` | Get values of a foreign key reference | [
"",
"mysql",
"sql",
""
] |
I have 3 drop-down lists on my page and a data-list. All of them are populated from SQL database based on selected item from previous drop-down.
AutoPostBack is set to true on all three dropdowns, and on first page load they are displayed correctly i.e. on all three dropdowns first item is selected and the result is ... | Withoug looking at your code it is difficult to answer the question. But by looking at the description of your question, it looks like you are setting AutoPostBack=true, but not handling the OnSelectedIndexChanged event.
First of all you should add OnSelectedIndexChanged event for all the three dropdowns like below.
... | To get the data-list updated when the first drop-down is changed, you must fire the post-back event manually(for the second and 3rd drop-downs)!
Assuming the data on the 3rd drop-down is based on the selection from the 2nd,on the client Page in JavaScript : Try to have the first item or a default item selected. This w... | Dependent dropdowns populated by sql database in ASP.NET | [
"",
"asp.net",
"sql",
""
] |
I have a mysql table `mysql_table`. There is a column `Cid` for category id.
I already uploaded many data in that table.
```
In first row, i upload ~1~2~3~ in Cid
In second row, i upload ~3~5~ in Cid
In third row , I upload ~1~ in Cid
```
Now i want to update column Cid of table mysql\_table without affecting existin... | You can use **[concat](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat)** to update the existing column as
```
update mysql_table set Cid = concat(Cid,'15~');
``` | Try using [**CONCAT**](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat) function.
```
UPDATE `mysql_table` set Cid = concat(Cid,'15~');
``` | How to update mysql table without deleting existing content | [
"",
"mysql",
"sql",
""
] |
I have a table that contains an even number of rows.
The rows form pairs with the same information but the content
of the first two columns swapped. Here is an example with three columns:
```
1 2 3
=======
A B W
B A W
C D X
D C X
E F Y
H G Z
F E Y
G H Z
```
My actual table has many more columns, bu... | For Me the below code is working
```
DECLARE @TEST TABLE
(A CHAR(1),B CHAR(1),C CHAR(1))
INSERT INTO @TEST VALUES
('A','B','W'),
('B','A','W'),
('C','D','X'),
('D','C','X'),
('E','F','Y'),
('H','G','Z'),
('F','E','Y'),
('G','H','Z')
SELECT MIN(A) [1],
MAX(A) [2],
C [3]
FROM @TEST
... | If every row has a counterpart where c1 and c2 are swapped then just select rows where c1 and c2 are in a certain order (i.e. c1 < c2).
The `EXISTS` part makes sure that only rows that have a counterpart are shown. If you want to show all unique rows regardless of whether or not they have a counterpart, then change th... | Combine row pairs with swapped columns | [
"",
"sql",
"oracle",
""
] |
I'm trying to do an subquery with SUM() and LIMIT. This works fine with the following code:
```
SELECT id,
(
SELECT SUM(number)
FROM (
SELECT number
FROM t2
WHERE u_id = '1'
ORDER BY time ASC
LIMIT 30
) AS temp
) AS test
... | Unfortunately, MySQL limits the scope of table aliases. Oracle is another database that does this.
You can phrase your query as a complicated join:
```
select t1.id, sum(t2.number)
from t1 p join
t2
on p.id = t2.u_id
where 30 >= (select count(*)
from t2 t22
where t22.u_id = t2.u_id... | why not just change p.id to t1.id? I'm pretty sure it's because you are aliasing t1 in the first select, and it isn't defined in the subquery. Try an inner join instead.
```
SELECT id,
(
SELECT SUM(number)
FROM (
SELECT number
FROM t2
INNER JOIN t1 p
... | MySQL Subquery SUM Limit | [
"",
"mysql",
"sql",
""
] |
I start to learn how to write sql language but I got stuck with the problem below : Now I have a data in a table named 'data'
```
+------+----------------------+
| id | date |
+------+----------------------+
| 1 | 2009-05-10 09:17:25 |
| 2 | 2010-04-09 09:17:25 |
| 3 | 2010-12-12 09:17:25 ... | You can try this query:
```
WITH years([year])
AS
(
SELECT DISTINCT TOP 3 YEAR([date]) AS [date]
FROM Table1
ORDER BY YEAR([date]) DESC
)
SELECT TOP 3 [year]
FROM years
ORDER BY [year] ASC;
```
[SQL FIDDLE DEMO](http://sqlfiddle.com/#!3/3aa13/52) | You could use `top`:
```
SELECT DISTINCT TOP 3 YEAR([date]) AS [date]
FROM my_table
ORDER BY YEAR([date]) DESC
``` | sql statement query last data | [
"",
"sql",
"sql-server",
"date",
""
] |
I have the following table structure and data
```
TransID TransType Product Qty OrderRef Date
------- --------- ------- --- -------- ----
C123 Credit Prod1 1 Order8 2014-07-08
C123 Credit Prod2 5 Order8 2014-07-08
Inv111 Invoice Prod1 1 Order8 2014-07-08
I... | I think a `LEFT JOIN` and some `GROUP`ing is the most obvious way to deal with this requirement:
```
SELECT
cr.TransID,
MAX(inv.TransID) as InvoiceID,
MAX(CASE WHEN inv.TransID is NULL THEN 1 ELSE 0 END) as Unsatsified
FROM
@t cr
left join
@t inv
on
cr.Product = inv.Product... | The resulting TransIDs should be the ones you need to delete
```
DECLARE @Trans TABLE
([TransID] varchar(6), [TransType] varchar(7), [Product] varchar(5), [Qty] int, [OrderRef] varchar(6), [Date] datetime)
;
INSERT INTO @Trans
([TransID], [TransType], [Product], [Qty], [OrderRef], [Date])
VALUES
('C123',... | TSQL - Exact match on subset of records | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. ... | There are a number of ways to go about doing this.
For example, you could convert the generated `datetime` from `GetDate()` to a `smalldatetime` first, à la:
```
CAST(GetDate() AS smalldatetime)
```
To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the cu... | For truncation:
```
SELECT SMALLDATETIMEFROMPARTS(
datepart(year ,dt)
,datepart(month ,dt)
,datepart(day ,dt)
,datepart(hour ,dt)
,datepart(minute,dt)
)
FROM (SELECT GETDATE()) t(dt)
``` | Truncate seconds and milliseconds in SQL | [
"",
"sql",
"sql-server",
"date",
"datetime",
""
] |
I want to optimize a query but I have no idea how I could do that. Here is the table I want to query:
```
Device table:
Id || PushId || created
abc aaa 10/10/13
def aaa 10/12/13
efg abb 9/9/12
```
The query I want is the following: I want to get duplicate PushIds and r... | This will provide the equivalent of row\_number() in MySQL using @ variables. Here it locates all but the 2 most recent rows for each PushId
```
SELECT
PushId
, Id
, created
FROM (
SELECT
@row_num :=IF(@prev_value = d.PushId,@row_num+1,1)AS RN
, d.PushId
, d... | There may need to be some manipulation to get it to fit into your delete statement, but try the following using the MIN function to find the lowest date+id combination, where there is more than one entry. then remove the date from the result, giving the correct id only:
```
delete from Device where id in (
select ... | Optimizing a query, duplicate rows that have oldest date | [
"",
"mysql",
"sql",
"performance",
"query-optimization",
""
] |
My problem is that I have 4 differents SELECT with
```
SELECT COUNT (*) AS regular
WHERE experience = 1 AND bl = 1
SELECT COUNT (*) AS rptmm
WHERE experience = 1 AND bl = 0
SELECT COUNT (*) AS new
WHERE experience = 0 AND bl = 0
SELECT COUNT (*) AS rptss
WHERE experience = 0 AND bl = 1
```
I want that the results ... | ***Firstly, I'd suggest not to use Count(*)\***. There are many answers on this site explaining why so I am not going to repeat it.
Instead, I'd suggest you to use a query like this:
```
SELECT (SELECT COUNT (tab.someColumnName)
FROM TableName tab
WHERE tab.experience = 1 AND tab.bl = 1) AS ... | Just put UNION ALL between your four statements you will get four rows with each count on its own row. However, you will lose the column name. You could also use join to get one row with four columnes. Just put the keyword join between each sql statement.
```
SELECT COUNT (*) AS regular
WHERE experience = 1 AND bl = 1... | Union different tables with differents columns and data | [
"",
"sql",
"sql-server",
"select",
""
] |
Quick question: Does exiting out of TOAD (for Oracle) while it is trying to cancel a pending query harmful?
Should I be letting this dialog box run its course?
I did have the screenshot but am unable to post pics until I have 10 reps.
EDIT: It has been going for around 30 minutes now.
EDIT2: I should mention it is n... | When this happens and I've already waited long enough (and the **`Cancel`** button has no effect), I open *Task Manager* and apply *"End Process Tree"* command on the `Toad.exe` process.
If a database connection is lost, all uncommitted changes made are automatically rolled back by the database. **So it is not harmful... | I just had same problem.
[LIKE THIS FOR DAYS](https://i.stack.imgur.com/3Z08s.png)
One solution to cancel the running process (processing or canceling) in TOAD which take time (keep processing for longer hours and same going for hours) is
JUST disable the internet connection which auto cancels the toad process.
Lat... | Exiting TOAD while cancel pending? | [
"",
"sql",
"oracle",
"toad",
""
] |
i have the data like this:
```
CODE_VD
N_10_19_xxx
N_0_3_xxx
N_121_131_xxx
N_100_120_xxx
N_80_90_xxx
N_20_29_xxx
```
as you can see i need to sort just the first number after N\_,i don't know how can i get this number.
i have tried with susbsting(CODE\_VD,2,3) but not exactly what i expected.
i want to get this:
... | ```
DECLARE @MyTable TABLE
(
CODE_VD VARCHAR(20)
)
INSERT INTO @MyTable
( CODE_VD )
VALUES
('N_10_19_xxx'),
('N_0_3_xxx'),
('N_121_131_xxx'),
('N_100_120_xxx'),
('N_80_90_xxx'),
('N_20_29_xxx');
SELECT * FROM
(
SELECT
*,
CONVERT(INT,
SUBSTRING(mt.CODE_VD,
3,
... | ```
SELECT SUBSTRING(CODE_VD,3, CHARINDEX('_',CODE_VD, 3)-3)
``` | sorting SQL with substring on string | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I'm grabbing the first day of the next quarter as `StartDate`. How can I add 90 days to it. The below is gives me invalid column error for StartDate within `EndDate`.
```
SELECT
DATEADD(qq, DATEDIFF(qq, 0, MAX(Time_Stamp)) + 1, 0) as StartDate,
DATEADD(day, 90, MAX(StartDate)) as EndDate
FROM Survey
WHERE Main... | The sql query doesn't know of column alias in the select. It is a self referencing error. The select statement creates the alias so it can't itself use the alias. The only statement to run after select is order by, where you can use an alias.
I would reuse your logic to prevent needing a subquery. Since ninety days is... | It's invalid because StartDate is alias for your date calculation. You can use alias only when you have results. In other words alias is available when you have dataset returned from server.
You can for example use subquery:
```
SELECT
StartDate,
DATEADD(day, 90, MAX(StartDate)) as EndDate
FROM (
SELECT
DA... | Adding 90 days to created date | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
""
] |
I have the following SQL select. How can I convert it to a delete statement so it keeps 1 of the rows but deletes the duplicate?
```
select s.ForsNr, t.*
from [testDeleteDublicates] s
join (
select ForsNr, period, count(*) as qty
from [testDeleteDublicates]
group by ForsNr, period
having count(*) > ... | Try using following:
**Method 1:**
```
DELETE FROM Mytable WHERE RowID NOT IN (SELECT MIN(RowID) FROM Mytable GROUP BY Col1,Col2,Col3)
```
**Method 2:**
```
;WITH cte
AS (SELECT ROW_NUMBER() OVER (PARTITION BY ForsNr, period
ORDER BY ( SELECT 0)) RN
FROM testD... | This is easy as long as you have a generated primary key column (which is a good idea). You can simply select the min(id) of each duplicate group and delete everything else - Note that I have removed the having clause so that the ids of non-duplicate rows are also excluded from the delete.
```
delete from [testDeleteD... | Delete duplicates but keep 1 with multiple column key | [
"",
"sql",
"sql-server",
"duplicates",
"delete-row",
""
] |
```
WHERE
StartDate BETWEEN
CAST(FLOOR(CAST(DATEADD("month", - 12, ISNULL(RunDate.testdate, GETDATE()) - DAY(ISNULL(RunDate.testdate, GETDATE())) + 1) AS FLOAT)) AS DATETIME)
AND
CAST(FLOOR(CAST(ISNULL(RunDate.testdate, GETDATE()) - DAY(ISNULL(RunDate.testdate, GETDATE())) + 1 AS FLOAT)) AS DA... | If you [abandon the `x BETWEEN a AND b` pattern](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common "What do BETWEEN and the devil have in common? ") in favour of one that could roughly be expressed as
```
x BEGINS WITH a
ENDS BEFORE b
```
(which, of course, is not valid SQL syntax but `x >... | Here is another expression:
```
where startdate > cast(dateadd(year, -1, getdate() - day(getdate()) as date) and
startdate <= cast(getdate() - day(getdate()) as date)
```
When you subtract a number from a `datetime` it is treated as a number of day, which can be easier to read.
EDIT:
Oh, that's 2005, not 2008... | SQL Server 2005 Query DateDate | [
"",
"sql",
"sql-server",
"datetime",
"sql-server-2005",
""
] |
I have some enormous tables of values, and dates, that I want to compress using run length encoding. The most obvious way (to me) to do this is to select all the distinct value combinations, and the minimum and maximum dates. The problem with this is that it would miss any instances where a mapping stops, and then star... | Try this:
```
DECLARE @MyTable TABLE (
Id INT,
Value1 VARCHAR(10),
Value2 VARCHAR(10),
Value3 VARCHAR(10),
DataDate DATE
);
INSERT @MyTable
SELECT 01, '1', ' 2', '3', '2000-01-01' UNION ALL
SELECT 01, '1', ' 2', '3', '2000-01-02' UNION ALL
SELECT 01, '1', ' 2', '3', '2000-01-03' UNION ALL
SELEC... | You'll probably want to use windowing functions. Try something like this:
```
select
id, value1, value2, value3,
from_date=update_date,
to_date=lead(update_date) over (partition by id order by update_date)
from (
select
t.*
,is_changed=
case when
value1 <> lag(value1) over (pa... | Select Contiguous Rows for Run Length Encoding | [
"",
"sql",
"sql-server",
"run-length-encoding",
""
] |
I'm building a tool to query a database from an html form, and I defined a data type to capture the form values. For example:
```
data BookSearchParams = BookSearchParams
{ Title :: Maybe Text
TitleSearchType :: SearchType
, Author :: Maybe Text
, AuthorSearchType :: SearchType
}
```
The columns of the d... | I've asked a similar [question](https://stackoverflow.com/q/23838630/376113) a couple of weeks ago, and the elegant answer was to use a `Writer` monad. (In fact, it's was exactly the same problem : building SQL query but I transformed it to a more general question).
```
import Control.Monad.Writer hiding (forM_)
impor... | I would use Monoid to solve this problem.
```
import Data.Monoid (<>)
titleSQL, authorSQL :: BookSearchParams -> Text
bookSearchSQL p = titleSQL p <> authorSQL p
``` | Convert value to sql select in Haskell | [
"",
"sql",
"haskell",
""
] |
I am converting my mysql script to sql server script.
I want to sort data and then collapse the data by some criteria.
Lets take below example:
in Mysql:
[sql fiidle](http://sqlfiddle.com/#!2/f26cf/2)
lets say we have table "test" and 3 column (colA,colB and colC)
Now I want to sort data by colA and colB and then... | I think this should be the trick. Don't know if it's very efficient but you could give it a try
```
SELECT t1.cola, t1.colb, t1.colc FROM
(SELECT *, ROW_NUMBER() OVER(ORDER BY cola, colb) AS RowNumber
FROM test) t1
JOIN
(SELECT cola, colb, MIN(RowNumber) AS RowNumber
FROM
(SELECT *, ROW_NUMBER(... | Your question as is doesn't really make sense. Either you want the smallest value for **colc** for every group or the first group-value of **colc** else. The solution of Nesuke for example does exactly what your fiddle example does. So why do you want to order by **cola** and **colb** before grouping? | Collapse Data using Order By and Group BY | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I would like to introduce a new column where it holds the calculated sum of next three Periods.
This is the sample data
```
Company Value Period
------- ----- ------
MGT 9 1401
MGT 2 1402
MGT 3 1403
MGT 4 1404
MGT 5 1405
MGT 6 1406
MGT 7 1407
M... | I used the following code in MS SQL Server 2008
```
select t1.Company, t1.value value, t1.period period,
isnull(t2.value,0)
+ isnull(t3.value,0)
+ isnull(t4.value,0) New_Column
from @NOA t1
left join @NOA t2 on (t1.period % 100 < 12 and t1.period = t2.period - 1)
or (t1.period % 100 >= ... | ```
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(company CHAR(3) NOT NULL
,dt DATE NOT NULL
,value INT NOT NULL
,PRIMARY KEY(company,dt)
);
INSERT INTO my_table VALUES
('MGT',20140101,9),
('MGT',20140201,2),
('MGT',20140301,3),
('MGT',20140401,4),
('MGT',20140501,5),
('MGT',20140601,6),
('MGT'... | Introduce calculated values in a new column | [
"",
"mysql",
"sql",
"sql-server-2008",
""
] |
Suppose I have a table like below:
```
row_id record_id tag_id
1 1 2
2 1 3
3 2 2
4 2 4
5 3 2
6 3 3
```
I want to get those record\_id which they have record with tag\_id of value 2 but does not have 3, in this case, I w... | This can be simply written as
```
SELECT record_id FROM table_A WHERE tag_id = 2
EXCEPT
SELECT record_id FROM table_A WHERE tag_id = 3;
``` | You can use **[bool\_or()](http://www.postgresql.org/docs/9.2/static/functions-aggregate.html)** function in your query in postgresql:
```
select record_id from table1 group by record_id
having bool_or(tag_id = 2) and not bool_or(tag_id = 3);
```
## [SQL Fiddle](http://sqlfiddle.com/#!15/1f8c1/5) | SQL - How to select records with value A but not B? (A and B belongs to different rows) | [
"",
"sql",
"postgresql",
"selection",
"multiple-value",
""
] |
Although the question seems to be somehow obvious, I could not find a clear specification for how duplicate elimination of UNION DISTINCT is defined (I hope it's defined in general and not per database system):
When writing
```
select * from table A
union distinct
select * from table B
```
and A and B have dupl... | There is no way to detect the order of elimination, because all columns, not only the key ones, are taken into consideration when performing a `UNION`:
```
create table a(k int primary key,x int);
create table b(k int primary key,y int);
insert into a(k,x) values (1,1),(2,2);
insert into b(k,y) values (1,3),(2,2);
se... | UNION [DISTINCT] removes duplicate result rows. So if you select columns (1,x) and (1,y) from your tables, no matter how often they occur and in which of the tables, you will get both rows, and each row just once.
The result is the same as
```
select distinct *
from (select * from a union all select * from b);
```
j... | SQL UNION: Is the order of duplicate elimination defined? | [
"",
"sql",
""
] |
I have 2 tables in SQL like below and need to run some tests queries on the data. The tables are with some sample data:
```
Table A
ID groupName value
id2000 groupA 1
id2000 groupA 2
id2000 groupA 3
id3000 groupB 1
id3000 groupB 2
Table B
ID groupNameB valueB
... | You want to use [EXCEPT](http://msdn.microsoft.com/en-us/library/ms188055.aspx).
It removes the rows from the first query that are also in the second query. It does not return rows in query2 that were not in query1.
```
select id, groupName, value
from tableA
except
select id, groupNameB, valueB
from tableB
``` | ```
select a.ID, a.groupName, a.Value
from [Table A] a
left join [Table B] b
on a.ID = b.ID
and a.groupName = b.groupNameB
and a.Value = b.ValueB
where b.ID is null
``` | SQL query with UNION or INTERSECT | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Hi im trying to return a resultset from one table. However, I want to add another column on the result set, that is coming from a different table.
```
SELECT ID, NAME,
CASE (SELECT STATUS FROM OTHERTABLE O WHERE O.ID = M.ID)
WHEN '1' THEN 'In progress'
WHEN '2' THEN 'Complete'
END as ... | Use join and organize your case
```
SELECT
M.ID,
M.NAME,
CASE
WHEN O.STATUS = '1'
THEN 'In progress'
WHEN O.STATUS = '2'
THEN 'Complete'
END AS STATUS
FROM
MAINTABLE M
JOIN OTHERTABLE O
ON (O.ID = M.ID)
``` | This is because your MainTable Id has more then one record in OtherTable
try it
```
SELECT ID, NAME,
CASE
WHEN O.STATUS = '1' THEN 'In progress'
WHEN O.STATUS = '2' THEN 'Complete'
END as STATUS
FROM MAINTABLE M JOIN OTHERTABLE O ON O.Id = M.ID
``` | select statement on CASE | [
"",
"mysql",
"sql",
"select",
"case",
""
] |
Wondering if someone could explain why my query is not giving the desired result in SQLite
I have two tables
Table A contains many lines with a column called picklist\_id in which the value is repeated, I am trying to get the distinct value of these and then check to see if this picklist id exists in table two. This ... | This should be IS NULL, not = NULL.
```
SELECT pt.picklist_id
FROM picklisttable pt
LEFT JOIN pickingtable p on pt.picklist_id = p.picklist_id
WHERE p.picklist_id = null;
```
When asking for the existence of data, the EXISTS clause is more readable usually, or the IN clause when dealing with one column only.
```
... | Try this. Same query except instead of `= NULL` it's `IS NULL`
```
SELECT distinct(pt.picklist_id) from picklisttable pt LEFT JOIN pickingtable p on
pt.picklist_id = p.picklist_id where p.picklist_id IS null
``` | LEFT Join Query failure | [
"",
"sql",
"sqlite",
""
] |
I have the following table:
```
+----+-------+---------+
| id | media | status |
+----+-------+---------+
| 1 | FOO | ACTIVE |
| 1 | FOO | PENDING |
| >1 | BAR | ACTIVE |
| 2 | FOO | ACTIVE |
| 2 | FOO | PENDING |
| >3 | BAR | ACTIVE |
+----+-------+---------+
```
What I need to get is a list of ... | You can use a NOT EXISTS clause (a NOT IN would also work).
```
select distinct id
from table t
where status = 'ACTIVE'
and not exists (select null
from table
where t.id = id and t.media = media
and status = 'PENDING')
```
see [sqlFiddle](http://sqlfiddle.com/#!2/... | ```
SELECT DISTINCT id
FROM t
GROUP BY id, media
HAVING MAX(status) = 'ACTIVE';
```
This assumes that an id that has a pending media should still be included if it also has a different media type without pending. If that's incorrect, or not applicable, you can remove `DISTINCT` from the SELECT and `media` from the ... | MySQL query to find unique records | [
"",
"mysql",
"sql",
""
] |
I’m going nuts. It seems everyone has had this same problem by the number of results I get when I google ‘left join not working’. I’ve studied them all and despite best efforts I cannot get my specific problem to work. Please help.
I have two tables; an animals\_Table and an animalMilestones\_Table.
Some of the anima... | It seems to me that you want a list of all [animalID] values from [animals\_Table] along with a column that indicates whether or not that [animalID] has a "milestone" equal to 'Intake'. If so, then I would suggest this:
```
SELECT at.animalID, amt.milestoneType
FROM
animals_Table at
INNER JOIN
... | animalMilestones\_Table.milestoneType will be NULL in cases where there is no record. You need to check for it being NULL or the value you are querying for.
```
animalMilestones_Table.milestoneType="Intake" or animalMilestones_Table.milestoneType is null
```
Not sure on the exact SQL syntax in Accesss | Left join including a where condition not working | [
"",
"sql",
"vb.net",
"ms-access",
"left-join",
""
] |
I have a field namely `Modified_Dt` of type `Datetime` in all of my tables, to keep track of last modified date and time for a record.
Now, let's say I need to know which tables has records that has been modified recently(like today).
How do I write a query for that? How do I query multiple tables?
By the way, I am ... | ```
declare @T table (T_Name nvarchar(255), M datetime)
declare @T_Name nvarchar(255), @SQLT nvarchar(max)
declare c cursor for select name from sys.tables
open c
fetch next from c into @T_Name
while @@fetch_status = 0 begin
set @SQLT = 'select top 1 ''' + @T_Name + ''', Modified_Dt from ' + @T_Name + ' order by M... | ```
USE MASTER
GO
DECLARE @ObjectName NVARCHAR(255)
DECLARE TablesList CURSOR
FOR select object_name(object_id, db_id('DBStackExchange'))
from [DBStackExchange].sys.columns
where name = 'Modified_Dt'
OPEN TablesList
FETCH NEXT FROM TablesList INTO @ObjectName
WHILE @@FETCH... | List tables with recently modified records | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I need to select all the `rows` AFTER the first 50 rows from a `table`. I can't seem to figure out an efficient way to do it.
I could select the first 50 `rows`, put their `IDs` in an array, then make another `query` that selects everything except them, but that seems wasteful.
I can't seem to find anything here that... | You are probably looking for `OFFSET`:
For example:
```
SELECT * FROM users ORDER BY id LIMIT 100 OFFSET 50
``` | You can [define](https://dev.mysql.com/doc/refman/5.0/en/select.html) an offset:
> [LIMIT {[offset,] row\_count | row\_count OFFSET offset}]
Like this:
```
SELECT * FROM table1 LIMIT 5, 10; # Retrieve rows 6-15
``` | Select after first 50 with MYSQL and PHP | [
"",
"mysql",
"sql",
""
] |
I have this query
```
Select Model_Number
From Guitar.Fenders
Where Model_number LIKE ('5%' OR '6%')
```
This doesn't work.
I only want the query to return model numbers that begin with 5 or 6. | There are a couple of ways you can do this, one by making use of `LIKE` and the other by making use of `IN` :
`LIKE`
```
Select Model_Number
From Guitar.Fenders
Where Model_number LIKE '5%' OR Model_Number LIKE '6%'
```
`IN`
```
Select Model_Number
From Guitar.Fenders
Where ... | Select Model\_Number
From Guitar.Fenders
Where (Model\_number LIKE '5%' OR Model\_number LIKE '6%') | How do I pass multiple options for a like statement? | [
"",
"sql",
"db2",
""
] |
We are new to postgres, we have following query by which we can select top N records from each category.
```
create table temp (
gp char,
val int
);
insert into temp values ('A',10);
insert into temp values ('A',8);
insert into temp values ('A',6);
insert into temp values ('A',4);
insert into temp va... | To retrieve the rows based on the percentage of the number of rows in each group you can use two window functions: one to count the rows and one to give them a unique number.
```
select gp,
val
from (
select gp,
val,
count(*) over (partition by gp) as cnt,
row_number() over (partit... | Referencing the response from a\_horse\_with\_no\_name, you can achieve something similar using *[percent\_rank()](https://www.postgresql.org/docs/11/functions-window.html)*
```
SELECT
gp,
val,
pct_rank
FROM (
SELECT
gp,
val,
percent_rank() over (order by val desc) as pct_rank
... | Postgresql : How do I select top n percent(%) entries from each group/category | [
"",
"sql",
"database",
"postgresql",
"postgresql-9.1",
""
] |
SQL:
```
WITH joined AS (
SELECT *
FROM table_a a
JOIN table_b b ON (a.a_id = b.a_id)
)
SELECT a_id
FROM joined
```
returns invalid identifier.
How can you select joined column when using WITH clause? I have tried aliases, prefixing and nothing worked. I know I can use:
```
WITH joined AS (
SELEC... | You can use the effect of the `USING` clause when joining the tables.
When you join tables where the join columns have the same name (as it is the case with your example), the `USING` clause will return the join column only once, so the following works:
```
with joined as (
select *
from table_a a
join table... | I don't think you can do this without aliases. The result of the "joined" query has two fields, both named a\_id. Unless you alias one (or both), as you did in your final query, the outer query has no idea which a\_id you are referring to.
Why is your final query not a "perfect" solution? | Oracle SQL WITH clause select joined column | [
"",
"sql",
"oracle",
"join",
"with-clause",
""
] |
the used table is here:
<http://sqlzoo.net/wiki/SUM_and_COUNT>
There's a thing I can't understand. If I use this:
```
select continent, count(name)
from world
group by continent
having population >= 10000000
```
They say Unknown column 'population' in 'having clause'. But this other query is considered fine:
```
s... | Syntax for HAVING clause is:
```
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
```
There have to be some aggregate function (or already aggregated column) after HAVING. | I am guessing this is MySQL, since other DBMS will throw a different error (e.g SQL Server `Column 'world.population' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause`, or Posgresql: `column "world.population" must appear in the GROUP BY clause or be use... | SQL: why is the HAVING clause rejected in this case? | [
"",
"sql",
"group-by",
"sum",
"having",
""
] |
Can anyone point out why this insert trigger is not inserting the new rows into the IVRTestB table?
```
If Object_ID('MyTrig3', 'TR') IS Not Null
Drop Trigger MyTrig3;
GO
Alter Trigger MyTrig3
On dbo.IVRTest
After Insert, update
AS
Begin
SET NOCOUNT ON;
Insert Into [dbo].[IVRTestB]
(IVRAID, ... | By putting every column of `Inserted` into single quotes, you're effectively inserting **string literals** into your destination table - not the column values!
Use this code instead:
```
INSERT INTO [dbo].[IVRTestB] (IVRAID, IVRName, DayNumber, OpenFlag)
SELECT
i.IVRAID, i.IVRName, i.DayNumber, i.OpenFlag ... | ```
Alter Trigger MyTrig3
On dbo.IVRTest
After Insert
AS
Begin
SET NOCOUNT ON;
IF EXISTS ( SELECT
1
FROM
INSERTED
WHERE
INSERTED.DayNumber IS NULL )
Insert Into
[dbo].[IVRTestB]
... | Insert trigger not inserting new rows in other table | [
"",
"sql",
"sql-server",
""
] |
I need to find same digit phone numbers from a table and delete these. Phone Numbers are like below :
```
+999999999999
11111111
0000000000000
44444444
```
I am following [this answer](https://stackoverflow.com/questions/24251440/regexp-find-numbers-that-have-all-same-digits) to solve this. I am trying :
```
select ... | Try this:
```
select *
from tblPhone
where
substring(replace(PhoneNo,'+',''),1,len(replace(PhoneNo,'+',''))-1)
= substring(replace(PhoneNo,'+',''),2,len(replace(PhoneNo,'+','')))
```
The idea is that if substring from 1st to second-last position matches the one from 2nd to last, the string must be composed of ident... | Here is an idea. There is a problem with the first character, which can be a `+` or number. Let's substitute the second character for an empty string and look at the result:
```
where replace(PhoneNo, substring(PhoneNo, 2, 1), '') in ('+', '') and
(PhoneNo not like '%[^0-9]%' and PhoneNo like '[0-9]%'or
P... | using regex to find same digit phone numbers | [
"",
"sql",
"sql-server",
"regex",
"sql-server-2008",
""
] |
Consider the following table `#temp`:
```
objectid field1 field2 field3
--------------------------------
1 X 001 foo
2 Y 022 bar
2 Z 033 baz
3 A 111 abc
3 B 222 def
3 C 333 ghi
4 Q 900 tom
`... | ```
declare @t table (objectid INT, field1 VARCHAR(50), field2 VARCHAR(50), field3 VARCHAR(50))
INSERT INTO @t (objectid,field1,field2,field3)values (1,'X','001','foo')
INSERT INTO @t (objectid,field1,field2,field3)values (2,'Y','022','bar')
INSERT INTO @t (objectid,field1,field2,field3)values (2,'Z','033','baz')
INSE... | ```
DECLARE @Temp TABLE
(
objectid INT,
field1 VARCHAR(20),
field2 VARCHAR(20),
field3 VARCHAR(20)
)
INSERT INTO @Temp
( objectid, field1, field2, field3 )
VALUES
(1 ,'X' ,'001' ,'foo'),
(2 ,'Y' ,'022' ,'bar'),
(2 ,'Z' ,'033' ,'baz'),
(3 ,'A... | How can I concatenate values from 3 column per id? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this query
```
SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_AS
WHERE (status = 'Paid' OR status = 'Available') AND platform = 'Sales'
GROUP BY Year(date), Month(date)
ORDER BY Year(date), Month(date)
```
sample result:
```
Monthly ... | First you need to run union on data and then do the aggregation:
```
SELECT
Month(data.date) AS Monthly,
Year(data.date) AS Annual,
COUNT(data.idcad) AS NumCad,
SUM(CONVERT(FLOAT, data.valorpag)) AS Valor
FROM
(SELECT date, idcad, valorpag FROM PI_AS
WHERE (status = 'Paid' OR status = 'Ava... | This should fix what you want:
```
SELECT Monthly, Annual, SUM(NumCad), SUM(Valor)
FROM
(
SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_AS
WHERE (status = 'Paid' OR status = 'Available') AND platform = 'Sales'
GROUP BY Year(date), Mon... | SUM some columns of SQL Selects with UNION of two tables | [
"",
"sql",
"sql-server",
""
] |
I'm using phpMyAdmin for submitting queries. When using GROUP BY in subquery the whole application just hangs without errors until I restart the browser.
I have three tables: `files` stores information about uploaded files, `file_category` defines the available categories for files and `file_category_r` stores relatio... | ```
select fc.name, count(*)
from file_category fc
inner join file_category_r fcr on fc.id = fcr.category_id
group by fc.name
```
Not quite sure about that "some files can have multiple entries in the files table, so I need to group them by files.filename", though.
Maybe you need something like
```
select fc.name, co... | Often, the use of `in` can result in inefficient query plans. You can try `exists` instead:
```
SELECT fc.*,
(SELECT COUNT(*)
FROM file_category_r fcr
WHERE fcr.category_id = fc.id AND
exists (select 1 from files f where f.mandant_id = 1 and fcr.file_id = f.id)
) as fi... | How to use GROUP BY in MySQL subquery | [
"",
"mysql",
"sql",
"group-by",
"subquery",
""
] |
I have a mammal attribute table with the following elements;
```
MammalAttributeID AttributeID MammalID
```
Some mammals have an attribute record of "cat" (AttributeID 234) , some have an attribute record of "feline" (AttributeID 456) and some have both "feline" and "cat" attribute records.
We want to replace the at... | I think Olgas response would miss the case where a mammal is a cat but not a feline because the delete happens first.
```
--update cats to felines
Update "mammal attribute table"
set AttributeID = 456
where AttributeID=234
go
--delete cat attribute
delete from attributetable where AttributeID=234
go
--delete dup... | Step 1. Delete rows with 'cat' attribute for mammals that have 'feline' attribute too.
```
DELETE FROM [YOUR_TABLE]
WHERE MammalID in
(SELECT MammalID FROM [YOUR_TABLE] WHERE AttributeID = 234 -- cat
INTERSECT
SELECT MammalID FROM [YOUR_TABLE] WHERE AttributeID = 456) --feline
AND AttributeID = 234
```
Step 2. Repla... | Deleting and replacing entries in a table using SQL Server | [
"",
"sql",
"sql-server",
"insert",
"sql-delete",
""
] |
Say I've got a query like this:
```
select table1.id, table1.name
from table1
inner join table2 on table1.id = table2.id
where table1.name = "parent" and table2.status = 1
```
Is it true that, since there's an inner join, I can refer the table2's status column even from table1? Like this:
```
select table1.id, table... | If I am not mistaken, you are asking that in an inner join, two fields of the same name, data type and length will be one field in the particular query. Technically that is not the case. Regardless of anything, `Table1.Status` will refer to `Table1` and `Table2.Status` will refer to `Table2`'s condition/value.
The two... | No, that's not true. By Inner join what you are doing is say if you have table1 with m rows and table two with n rows then the third `SET` that will be produced by joining the two tables will have m\*n rows based on match condition that you have mentioned in where clause. It's not m+n rows or infact columns of the two ... | sql - what's the faster/better way to refer to columns in a where clause with inner joins? | [
"",
"sql",
"performance",
"syntax",
"inner-join",
"where-clause",
""
] |
I have a table in SQL Server 2012, with columns like:
```
Client_ID, Sale_Date
```
I need 2 additional flag columns:
```
FirstPurchase, ActiveWithin90Days
```
"FirstPurchase" shoud take one of these 2 values: **new**, or **old**.
**New** means the Client\_ID value is identified for the first time given the existi... | You need to have a sub query that finds the first sale date. Something like:
```
select s.ClientID,
s.Sale_Date,
case when s.Sale_Date = m.MinSales_Date then 1 else 0 end AS IsFirstSale,
case when dateadd(day, -90, getdate()) < m.MinSale_Date then 1 else 0 end
AS IsNewAcc... | Try this:
```
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY ClientID ORDER BY Sale_Date)
FROM YourTable
)
SELECT A.ClientID,
A.Sale_Date,
CASE WHEN RN = 1 THEN 'new' ELSE 'old' END Flag1,
CASE WHEN B.ClientID IS NULL THEN 1 ELSE 0 END Flag2
FROM CTE A
OUTER APPLY (SELECT... | SQL: flag if value exists in the past | [
"",
"sql",
"sql-server",
""
] |
I wrote the below query which shows me ApplicationIDs associated with two specific ables. I need the results to return the number of times each Applications.AppID appears in those tables next to the row with the application name. Ive used distinct because in my results I only want the name to appear once but have a num... | First, you do realize that order is **unspecified** unless you order the result set using `order by`? That means there is no guarantee that the first two selects in your `union all` will come first.
So, let's strip those two out as they are really extraneous to the actual problem. Let us consider the core `select`:
s... | DISTINCT is logically equivalent to a GROUP BY:
```
SELECT Applications.AppId, Applications.ApplicationName
,COUNT(*)
FROM SupportingApplications
INNER JOIN applications ON SupportingApplications.Appid = applications.appid
INNER JOIN ImpactedApplications as Apps on SupportingApplications.AppId = Applications.Ap... | How can I count and show the number of times a row appears within multiple joined tables? | [
"",
"sql",
"sql-server-2008",
""
] |
For experimental purposes only.
I would like to build a query but not querying data extracted for any table but querying data provided in the query it self. Like:
```
select numbers.* from (1, 2, 3) as numbers;
```
or
```
select numbers.* from (field1 = 1, field2 = 2, field3 = 3) as numbers;
```
so I can do things... | If you wanted the values to be on separate rows instead of three fields of the same row, the method is the same, just one row per value linked with a `union all`.
```
select *
from(
select 1 as FieldName union all
select 2 union all
select 3 union all
select 4 union all -- we could continue this for a ... | Use the `values` row constructor:
```
select *
from (values (1),(2),(3)) as numbers(nr);
```
or using a CTE.
```
with numbers (nr) as (
values (1),(2),(3)
)
select *
from numbers
where nr > 2;
```
**Edit:** I just noticed that you also taggeg your question with `mysql`: the above will not work with MySQL, only ... | SQL, build a query using data provided in the query itself | [
"",
"mysql",
"sql",
"postgresql",
""
] |
I'm working on creating a report page for an ASP.NET project, the url to that page is
```
'localhost/reports'
```
But for some reason, the SQL Server reporting page is turned on and now there is a url conflict.
So my url now redirects me to the following url:
```
'localhost/Reports/Pages/Folder.aspx'
```
It seems ... | You can turn of the entire reporting service in the `SQL Server Configuration Manager` or you can go to the `Reporting Services Configuration Manager` and change the `Report Manager URL` to point to a different location. The default is /Reports. | If you look under "Internet Information Services (IIS) Management", I usually just search for it from start menu, you will see an app pool for reporting services/SSRS with a Reports entry under it. You will probably also see an entry under Default Website. Unfortunately different versions of IIS manager will look diffe... | How does /reports redirect to the SQL server reporting page | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
Query:
```
select * from v_fi_trans_logs
where case_num like '105'
AND TRANS_DT=CAST('09-JUL-2014' AS DATE);
```
Doesn't return me any records.
But If I do a select as
```
select TRANS_DT,CAST('09-JUL-2014' AS DATE) from v_fi_trans_logs where case_num like '105'
```
It returns me values which is equal.
```
T... | I found the solution by HIT and TRAIL method :
It worked with:
```
select * from v_fi_trans_logs
where case_num like '105'
AND TRANS_DT LIKE CAST('09-JUL-2014' AS DATE);
```
That is,replacing **"="** with **"LIKE"** solves the issue. | I think that the problem is that you are using :
```
like '105' AND TRANS_DT=CAST('09-JUL-2014' AS DATE);
```
You can use like as a comparation of numbers and strings… only once.
But if you are trying to compare ´105´ AND TRANS\_DT=CAST('09-JUL-2014' AS DATE) logically. You cannot do it. The translation will be ( 7 ... | Select Query in Oracle giving issue | [
"",
"sql",
"oracle",
""
] |
Table1:
```
BrID HQID
------------
Br1 HQ1
HQ1
HQ2
Br2 HQ1
Br3 HQ2
```
Table2:
```
ID Name BrID IDt2
------------------------------
11 OthName11 Br1
22 HQName111 HQ1
33 HQName222 HQ2
44 OthName22 Br2
55 OthName33 Br3
```
I need to UPDATE Table... | You just need multiple `JOIN` statements:
```
UPDATE a
SET a.IDT2 = c.ID
FROM Table2 a
JOIN Table1 b
ON a.BRID = b.BRID
JOIN TAble2 c
ON b.HQID = c.BRID
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!6/4784b/5/2) | Try this:
```
UPDATE A
SET A.IDt2 = A1.ID
FROM table2 A
INNER JOIN table1 T1 ON A.BrID = T1.BrId
INNER JOIN table2 A1 ON T1.HQID = A1.BrId;
``` | UPDATE and SELECT to/from the same table | [
"",
"sql",
"sql-server",
"select",
"join",
"sql-update",
""
] |
I find myself needing to retrieve matches for, on average, ~1.5m rows from a remote database. There are two tables (ITEM1 and ITEM2) that have dated item information. There should always be at least one record for an item in ITEM1, and there may be 0 to many records for the same item in ITEM2. I have to find the latest... | So after much testing and experimentation I have come up with the following that outperforms everything else I have tried:
```
SELECT DISTINCT oInv.Item_ID, oInv.Month_Ending, oInv.Original_Cost
FROM (
SELECT Item_ID, Month_Ending, Original_Cost
FROM ho_data.dbo.CO_Ho_Inven
UNION ALL
SELECT Item_ID, Mo... | Rewrite the Correlated Subqueries using MAX with ROW\_NUMBERs:
```
SELECT GETDATE() AS DateElement, A.SourceStore,
COALESCE(FR.original_cost,CO.original_cost) AS Cost
FROM #TEMPA A
INNER JOIN
(
SELECT *
FROM
(
SELECT original_cost,
item_id,
ROW_NUMBER() OVER (PARTITIOM BY i... | Optimizing A Slow Complicated Remote SQL Query | [
"",
"sql",
"sql-server",
"database",
"performance",
"query-optimization",
""
] |
As we know in Oracle no data or action query is committed until we call a commit. I want such implementation with SQL Server that I can run action queries on db but data is not changed permanently, it just let me see data before and after my action queries.
Or is there any way to mirror database on same server in such... | You can use the [`IMPLICIT_TRANSACTIONS`](http://msdn.microsoft.com/en-gb/library/ms187807.aspx) setting to achieve a similar function to what Oracle does:
> Transactions that are automatically opened as the result of this setting being `ON` must be explicitly committed or rolled back by the user at the end of the tra... | You can do it within same query window, in which you have written 'begin tran'
do not commit until not conform.
you can execute number of query within same window, which was give you your query preview before committing transaction.
It's only possible within same query window. you can not able view preview in other q... | How to use sql server database in preview mode? | [
"",
"sql",
"sql-server",
""
] |
I have quite a large DB, but I've simplified it for the purpose of this question:

Basically, every time a user clicks something on my site, it gets logged as a row in my DB: the `UserID` field is a cookie that is used to identify the user, and `Stuff` an... | You could use aggregate function `COUNT()` and then `HAVING` statement like:
```
SELECT userID, COUNT(userID)
FROM tbl
GROUP BY userID
HAVING COUNT(userID) >= 2
```
You can then re-use the above query if you want to filter out who are the repeat visitors like:
```
SELECT * FROM tbl
WHERE EXISTS
(
SELECT userID,... | You can do this with a `group by` and `min(timestamp)` table. Then put that in a view or temporary aliased table and join.
Example - get first visits timestamp:
```
SELECT userID,
min(TIMESTAMP)
FROM info
GROUP BY userID
```
Example - get all information:
```
SELECT *
FROM info t,
(SELECT use... | Separate new and returned users in database | [
"",
"mysql",
"sql",
"database",
""
] |

From this above table I will need the **event\_ids** that **tag\_id** 21 and 5 involved
in a single query. I want those event\_ids that only 21 and 5 both visited | If you need events that must have both of these tags then you can do so
```
select * from
table
where tag_id IN (21,5)
group by event_id
having count(distinct tag_id) = 2
``` | ```
SELECT *
FROM TABLE_NAME
WHERE tag_id=21 OR tag_id=5;
```
OR
```
SELECT *
FROM TABLE_NAME
WHERE tag_id IN (21,5);
``` | Find all possible event_id that were attend by tag_id 5 and 21 | [
"",
"mysql",
"sql",
""
] |
I want to add a string to my sql database using JDBC. But the problem is that whenever the string contains a double quote, then the sql command is interpreted completely differently and a "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax" gets thr... | I tried adding the string by escaping the double quote but that didn't work. The only way I could add the string is by using PreparedStatement instead of a Statement class.
```
String string = "abc\"abc";
String sql = "INSERT INTO tableName VALUES(?)";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
pre... | You need to escape the string value to make a string literal in the query.
When you are using quotation marks to delimiter the string:
* A backslash (`\`) in the string should be replaced by two backslashes.
* A quotation mark (`"`) in the string should be replaced by a backslash and a quotation mark.
If you would u... | How to add a string containg a double quote to a sql database? | [
"",
"mysql",
"sql",
"database",
"jdbc",
""
] |
I have two columns:
* id (nchar)
* name (varchar)
Something simple just can't figure out how.
```
select *
from plant.carrier
where carrier_id like 'NT'
```
This gives an expression error
```
SELECT *
FROM plant.carrier
WHERE RTrim(CAST([carrier_id] As VarChar) = 'NT'
```
id column
... | To compare nchar and varchar you need to convert char to varchar and compare two varchars:
```
RTrim(CAST([nCharColumn] As VarChar)
```
**Updated**
Here is full example:
```
create table test (
f nchar(20))
insert into test values('nt')
insert into test values('st')
declare @s varchar(20) = 'nt'
select * from tes... | If you [**Read The Documentation**](http://msdn.microsoft.com/en-us/library/ms191530.aspx), you'll see that conversion between `[var]char` and `n[var]char` is implicit, so saying something like
```
where x.some_char_column = y.some_nchar_column
```
should work just fine...unless the columns differ in their defined co... | SQL Comparing nchar to string | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table with a column1 nvarchar(50) null. I want to insert this into a more 'tight' table with a nvarchar(30) not null. My idea was to insert a derived column task between source and destination task with this expression: Replace column1 = **(DT\_WSTR,30)Column1**
I get the "truncation may occur error" and I am... | Consider changing the truncation error disposition of the Derived Column component within your Data Flow. By default, a truncation will cause the Derived Column component to fail. You can configure the component to ignore or redirect rows which are causing a truncation error.
To do this, open the Derived Column Transf... | JotaBe recommended using a data conversion transformation. Yes, that is another way to achieve the same thing, but it will also error out if truncation occurs. Your way *should* work (I tried it), provided the input data really is less than 30 characters.
You could modify your derived column expression to
```
(DT_WST... | Insert data via SSIS package and different datatypes | [
"",
"sql",
"sql-server",
"ssis",
"type-conversion",
""
] |
I have a column which is named "`Firstname`" and contains
```
Firstname Lastname
```
and I want to create another column called `Lastname` and cut the `Lastname` from the "`Firstaname`" column and paste it on the "`Lastname`" column, for multiple rows.
before
```
Firstname
---------
Bob Weller
```
after
```
First... | This query splits it into FirstName and LastName at the first space.
```
SELECT FirstNameLastName,
substring(FirstNameLastName, 0, charindex(' ', FirstNameLastName) -1) as FirstName,
substring(FirstNameLastName, charindex(' ', FirstNameLastName) -1,len(FirstNameLastName)) as LastName
from [Table]
```
To modify your ... | If you want then split into 2 *columns* not *rows* then something like this should do:
```
SELECT
SUBSTRING(WholeName, 1, CHARINDEX(' ', WholeName) - 1) AS Firstname,
SUBSTRING(WholeName, CHARINDEX(' ', WholeName) + 1, len(FirstName)) AS LastName
FROM MyTable
```
NOTE: This is assuming that EVERY record has a space... | How to split a row into two strings and copy the second string in a separate column in SQL? | [
"",
"sql",
"string",
"split",
""
] |
I made a little pl/pgsql script to rename some sequences (prefixes adding) and set their schema to 'public'. However I don't understand why but my 'ELSE' instructions are executed only once in the loop, which is not logical because I have many rows whose value of 'nspname' is other than 'docuprocess' :
```
CREATE OR R... | I finally found the source of the problem! In the beginning of my function (masked part "[...]"), I have a loop which rename tables in schemas passed as parameters, and move these tables to schema 'public'. At this time, sequences owned by tables present in 'docufacture' and 'notification' schemas are automatically mov... | There is a space missing in this line after `RENAME TO`:
```
sql := 'ALTER SEQUENCE '||rec.nspname||'.'||rec.relname||' RENAME TO '||newname;
```
As a result, upon the first sequence that is not in schema `docuprocess` the `sql` statement is executed and raises an error which aborts the loop.
Note also that you do n... | Issue with a control structure in pl/pgsql script loop | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
At wits end with this
How do I pass a null value to my stored procedure within SSMS?
I have set two of my parameters to optional eg.
```
--This is inside my storedproc
@name varchar(50)
@surname varchar(50) = null,
@text varchar(255) = null,
```
Now to execute
```
--Now execute without the 'text'
EXEC sp_bla '... | ```
EXEC sp_bla NULL, 'Noob Question Name', 'Noob Surname'
```
Basically, just pass NULL as parameter value in the required position | Try this
If u want to define all the three parameters then
```
EXEC sp_bla @name = 'Noob Question',@surname = 'Noob',@text = 'Newtext'
```
If u want to define any two
```
EXEC sp_bla @name = 'Noob Question',@surname = 'Noob'
```
or
```
EXEC sp_bla @name = 'Noob Question',@text = 'Text'
```
If u do not have any of... | Pass explicit NULL value to stored procedure from T-SQL not from application | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
I'm working on a project for school where I have to work with asp.net and sql databases.
I'm wondering If I could use this
```
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionNameWhateverItIs"].ConnectionString);
SqlCommand command = new SqlCommand("functionName", conne... | You can certainly re-use that same code with different parameters, here's one way of doing that
```
public void RunMyFunction(IDictionary<string, object> parameters)
{
using (SqlConnection con = new SqlConnection(...))
using (SqlCommand cmd = new SqlCommand("functionName", conn))
{
cmd.CommandType ... | Yes, you can re-use your db connection.
Keeping the connection open to re-use vs. re establishing the connection every time will depend on your application.
With lots of simultaneous users, it may be a good idea to re-establish a connection every time a db needs to be accessed, as keeping multiple connections open, w... | Database connection on a class | [
"",
"asp.net",
"sql",
"sql-server",
"database",
""
] |
I would like to align my column 'Gesamt':
```
SELECT k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
CONCAT(IFNULL(ROUND(SUM(Betrag), 2), 0), LPAD('Euro', 4, ' ')) AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
```
**Output:**
```
... | Simplify the concat by concatenating `'<space>Euro'` instead of `LPAD('Euro',4,' ')` and add a LPAD in the whole concat to make it shift right (you can decide based on your data how many characters are needed in order to align):
```
SELECT k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
... | Move `LPAD()`, you need it to work on the whole result, not only on `Euro` :
```
SELECT
k.KUNDENID AS ID,
vorname AS Vorname,
nachname AS Nachname,
LPAD(CONCAT(IFNULL(ROUND(SUM(Betrag), 2), 0), ' Euro'), 15) AS Gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUND... | LPAD/RPAD: Align column | [
"",
"mysql",
"sql",
"concatenation",
""
] |
This may seem silly but I am working on an old system where we don't have separate table for project. We have a table something like this.
```
| PROJECTNAME | EMPID |
|--------------------|-------|
| casio calc new | 1 |
| calc new | 2 |
| tech | 3 |
| financial calc new ... | Here you go. You can create a dynamic query with the help of `REPLACE` function with a little bit *hack*. Then use `EXEC` function to execute that query.
```
DECLARE @str VARCHAR(MAX)
SELECT @str='casio,calc'
SELECT @str='LIKE ''%'+REPLACE(@str,',','%'' OR ProjectName LIKE ''%')+'%'''
EXEC('SELECT * FROM ProjectDeta... | The solution is to use several `LIKE` conditions:
```
SELECT *
FROM ProjectDetails
WHERE ProjectName LIKE '%casio%'
OR ProjectName LIKE '%calc%';
``` | LIKE condition with comma separated values | [
"",
"sql",
"sql-server",
"sql-like",
"sql-in",
""
] |
I'm wanting to return the total number of times an `exerciseID` is listed, but filter it so each `exerciseID` may only be increment once per a date. For this reason I believe I cannot do a `group by date`.
```
id | exerciseid | date
1 | 105 | 2014-01-01 00:00:00
2 | 105 | 2014-02-01 00:00:00
3 | 105 ... | for V2.0 question:
```
select
exerciseid
, count(distinct date) as exercise_count
from user_exercises
group by
exerciseid
;
| EXERCISEID | EXERCISE_COUNT |
|------------|----------------|
| 54 | 1 |
| 85 | 3 |
| 420 | 2 |
```
see [th... | If you want count how many group you have on group by :
```
$db->query("SELECT e.id as id, e.name, count(id) as total, ue.date
FROM `users exercises` as ue
LEFT JOIN `exercises` as e ON exerciseid = e.id
WHERE ue.`userid` = $userid
GROUP BY id ASC
ORDER BY to... | SQL: Increment for every GROUP BY | [
"",
"mysql",
"sql",
"count",
"group-by",
""
] |
Can you please assist me in writing a query to remove duplicates. See below
looking the results I have a column added as my status (manually) added. The category is the one determining where a record is a duplicate or not. In this case our main focus is cancellation. If for a member a cancellation has reinstatement aft... | **Strategy**
In order to remove the duplicates, let's start by writing some code that only selects the duplicates. If you can write the proper select statement, it is easy to convert it into a delete statement. Now, the select statement is a little tricky because we need to compare the dates, but your dates are split ... | ```
;with TempCte as (Select CreateYear,MonthDay,Category,Member, MemberCount =ROW_NUMBER()
over(PARTITION By CreateYear, MonthDay, Category, Member, Status Order By CreateYear)
From TableName)
Delete TempCte
Where MemberCount >1
``` | Remove duplicate records | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.