Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
First I need to point that I read [Database columns type prefix](https://stackoverflow.com/questions/995512/database-columns-type-prefix) but it's not the same issue.
A long time ago someone who I worked with told me that in project I took part, all columns need to have unique prefix.
For example for `users` table I ... | I believe this is stupid. You actually end up prefixing all columns in all queries with their table names (or "identifiers"), even where there is no ambiguity.
If you compare:
```
SELECT t1_col1, t2_col1
FROM t1, t2;
```
... with:
```
SELECT t1.col1, t2.col1
FROM t1, t2;
```
... then the recommendation may appear ... | I think it's unnecessary, BUT in the name of consistency on an existing project you should maintain it or refactor the whole database.
Why it is unnecassary? Well take a look at the following query wich illustrates how you can get whatever you want out of the database
Also i think it's more readable and the alliasing... | Column prefixes in tables | [
"",
"mysql",
"sql",
"database",
"database-schema",
"prefix",
""
] |
I have data similar to the following:
```
Date ID Amount
10-Jun-14 978500302 163005350
17-Jun-14 978500302 159947117
24-Jun-14 978500302 159142342
1-Jul-14 978500302 159623201
8-Jul-14 978500302 143066033
14-Jul-14 978500302 145852027
15-Jul-14 978500302 148595751
```
Is ... | The easiest way is to use analytic functions to get the minimum and maximum values before aggregating:
```
select id, avg(amount)
from (select d.*,
min(amount) over (partition by id) as mina,
max(amount) over (partition by id) as maxa
from data d
) d
where amount > mina and amount ... | ```
select id, avg(amount)
from tbl t
where id not in (select id from tbl group by id having count(distinct amount) > 2)
or (amount <> (select min(x.amount) from tbl x where x.id = t.id)
and amount <> (select max(x.amount) from tbl x where x.id = t.id))
group by id
```
The first line in the WHERE clause is ... | Group by and exclude minimum and maximum from results | [
"",
"sql",
"database",
"oracle",
"select",
""
] |
Looking for some advice on how to tackle the following select query with EF.
\*Note, I just need help with the SELECT via EF the create table/insert stuff is in there just for a sample of my table structure
```
CREATE TABLE SampleTable(Foo INT, Bar VARCHAR(50))
INSERT SampleTable VALUES
(1,'GoodData'),
(2... | Here are a couple of extension methods to help:
```
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T... | There is another namespace in LINQ named **system.linq.dynamic**
It is very usefull if you want to make your query dynamicly via your code runtime.
Have a look on it!! | How to do this dynamic where clause in EF | [
"",
"sql",
"entity-framework",
""
] |
I am using SQL Server 2012 to write a procedure and I am receiving this error when trying to run this select statement.
> Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
I think it has something to do with the `Se... | Since your WHERE clause is grouping by Team.Name and selecting the MIN(Date) you are going to return the minimum date for each team (based on the other criteria too). If you are using a <> operator you can only have one value on the other side of that operator, if you need more than one value use the NOT IN operator in... | If the subquery may return more then one result you should replace the `<>` operator with `not in` | Select Statement in Where Clause Returning More Than 1 Value | [
"",
"sql",
"sql-server",
"select",
"sql-server-2012",
""
] |
I have a problem and I have 2 solutions for that problem. I have to write a procedure which will return rows falling into required categories. The required categories will be passed as boolean (or bit) values. The first solution is:-
```
DECLARE @IsRowType1Req bit;
DECLARE @IsRowType2Req bit;
DECLARE @tbl1 table (ID ... | The answer would likely depend on the size of the table as well as the size of each subset returned.
The IF solution has to insert rows into another table, which doesn't come cheap. The WHERE solution, on the other hand, uses UNION which implies sorting to remove duplicate entries. If you replaced UNION with UNION ALL... | With the information you have given there seems no need to use a `UNION`of `IF`.
```
SELECT *
FROM @tbl1
WHERE
(RowType = 'RowType2' AND @IsRowType2Req = 1)
OR (RowType = 'RowType1' AND @IsRowType1Req = 1);
``` | Checking condition in IF vs WHERE clause | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have a derived table with a list of relative seconds to a foreign key (ID):
```
CREATE TABLE Times (
ID INT
, TimeFrom INT
, TimeTo INT
);
```
The table contains mostly non-overlapping data, but there are occasions where I have a TimeTo < TimeFrom of another record:
```
+----+----------+--------+
| ID | Ti... | Left join each row to its successor overlapping row on the same ID value (where such exist).
Now for each row in the result-set of `LHS left join RHS` the contribution to the elapsed time for the ID is:
`isnull(RHS.TimeFrom,LHS.TimeTo) - LHS.TimeFrom as TimeElapsed`
Summing these by ID should give you the correct an... | OK. I'm still trying to do this with just one `SELECT`. But This totally works:
```
DECLARE @tmp TABLE (ID INT, GroupId INT, TimeFrom INT, TimeTo INT)
INSERT INTO @tmp
SELECT ID, 0, TimeFrom, TimeTo
FROM Times
ORDER BY Id, TimeFrom
DECLARE @timeTo int, @id int, @groupId int
SET @groupId = 0
UPDATE @tm... | How to consolidate blocks of time? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |

I have 2 tables with above fields.
I have created below query
```
SELECT DISTINCT H.HolidayId,H.HolidayDate,H.Description,CH.ClientId,
case when CH.HolidayId is not null then 1 else 0 end as IsHoliday
FROM Holiday H LEFT JOIN Cli... | I have used your queries after 2 days only i found bug in that. then i found a solution for that.
Below is the solution:
```
SELECT h.HolidayId, HolidayDate,Description,CASE WHEN ClientID IS NULL THEN 0 WHEN ClientID != @ClientId THEN 0 ELSE 1 END AS IsHoliday
FROM HOLIDAY h LEFT OUTER JOI... | Try below query, it will work as per the requirement :)
```
SELECT h.HolidayId, HolidayDate,
CASE WHEN ClientID IS NULL THEN 0 ELSE 1 END AS IsHoliday
FROM HOLIDAY h
LEFT OUTER JOIN CLIENTHOLIDAYS ch ON ch.HolidayId = h.HolidayId
WHERE ClientId = 1 OR ClientID is null
``` | select table using complicated query | [
"",
"sql",
"sql-server",
""
] |
Seeing slowness in insert/select after truncating a table that has over 6 million rows.
I daily insert 5 to 6 millions records into a table and I was able to insert/select data without any issue for some 7 or 8 days but when the table size went above 10 GB / 30 million rows, there were a few timeout issues.
So I thou... | After enabling auto stats update , every thing went normal. from now After truncating big tables i will makes sure table stats get updated if DB auto stats update is disabled.. thanks every one for all your valuable suggestions. | Make sure you update your statistics on all your indexes... and it probably wouldn't hurt to shrink your log file. There are articles on how to do both all over the internet. But that's my best guess at what's going on. | SQL Server - insert/select slow after TRUNCATE TABLE has 6 over million rows | [
"",
"sql",
"sql-server",
"performance",
"sql-server-2008",
"truncate",
""
] |
Could someone help me with this table?
```
col1 col2
0 1
0 1
1 0
1 1
2 0
2 1
3 1
3 1
```
(<http://sqlfiddle.com/#!2/67d076>)
I'd like to select distinct values from the first column and filter out the values that have zeroes in the second column. The result should b... | ```
select distinct col1 from test where
col1 not in (select col1 from test where col2 = 0)
``` | It sounds like your looking for a query like this:
```
SELECT DISTINCT `col1`
FROM `test`
WHERE `col1` NOT IN (
SELECT `col1`
FROM `test`
WHERE `col2` = 0)
```
Or using a `JOIN`, like this:
```
SELECT DISTINCT a.`col1`
FROM `test` a
LEFT JOIN `test` b ON a.`col1` = b.`col1` AND b.`col2` = 0
WHERE b.`col1` IS N... | Select distinct rows and apply a filter | [
"",
"mysql",
"sql",
"distinct",
""
] |
so the 672 is the amount of quarters in a week and i need the avg(value) of all quarters of 5 weeks on the same day on the same quarter
```
select value, DATEADD(MINUTE, a.QuarterNumber * 15, '2000-01-01') AS [Timestamp]
from measurements.Archive a
INNER JOIN measurements.Points p ON a.PointId = p.Id
INNER JOIN fifth... | I do not know which is the last number you want. But the principal would be to find how many ones you want. In your example i will assume 5 as the max multiplier.
So knowing the firt quarter which is `510176` ani would find the min quarter which would be in your example `510176 - (672*5)` and i would test the integer ... | Use `in` instead:
```
where a.QuarterNumber in (510176, 510176 - 672, 510176 - (672*2), 510176 - (672*3), 510176 - (672*4)
510176 - (672*5), . . .)
```
If there is some sort of coding scheme, and you essentially want in infinite list, then use modulo arithmetic. In many databases, this will ... | how to rewrite this SQL Query without the or 's | [
"",
"sql",
""
] |
```
DECLARE @TodayDayOfWeek INT
DECLARE @EndOfPrevWeek DateTime
DECLARE @StartOfPrevWeek DateTime
DECLARE @EndOfThisWeek DateTime
DECLARE @StartOfThisWeek DateTime
```
--Delcared the Parameters
```
SET @TodayDayOfWeek = datepart(dw, GetDate())
SET @EndOfPrevWeek = DATEADD(dd, -@TodayDayOfWeek, GetDate())
SET @StartOf... | ```
;WITH MyCTE AS
(
select st.SALESID
, st.SALESNAME
, st.CUSTACCOUNT
, st.CUSTOMERREF
, st.SALESSTATUS
, cast (sl.LINENUM as decimal (18,0)) AS LINENUM
, sl.ITEMID
, cast (sl.SALESQTY as decimal (18,0)) AS SALESQTY
, cast (sl.LINEA... | The nasty way to do this would be to just add the conditions for setting 'T' or 'L' to your WHERE clause:
```
DECLARE @TodayDayOfWeek INT
DECLARE @EndOfPrevWeek DATE
DECLARE @StartOfPrevWeek DATE
DECLARE @EndOfThisWeek DATE
DECLARE @StartOfThisWeek DATE
--Delcared the Parameters
SET @TodayDayOfWeek = datepart(dw, Get... | Using Case results in where clause - i would like to use the results of TorL - SQL Server | [
"",
"sql",
"sql-server",
"case",
""
] |
```
SELECT *
FROM Products
WHERE Name LIKE '%' +
(SELECT TOP 1 Gift.Name FROM Gift WHERE Id = 65)
+ '%'
```
Subquery returns sth like "toy gun". Some of them even consists of three or more words. Obviously main query looks for Names that include "toy gun".
What I want to do is return all results for "toy" or ... | You will need to create function that splits out the text of your column. Here is one possible way to do it:
<http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/>
Once you have that, you can use a JOIN with a LIKE:
```
SELECT
*
FROM... | If you have Full Text indexing enabled then using `FREETEXT` query produce what you want. You can check Full Text if it enabled by running the below query:
```
SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')
```
If the above returns 1, then your good to go. If 0 is returned then search for installation instruct... | Query with LIKE statement for any of the words, not whole | [
"",
"sql",
"sql-server",
"t-sql",
"sql-like",
""
] |
I have two tables:
tables: **products** and **posts**
table **products** has field **model** with values "AH0002", "O-PO-201", "O-PO-304" etc.
table **posts** has field **post\_title** with values like "Product AH0002 is the best", "Red O-PO-201 is really good".
What I need is to display products rows where their nam... | Try:
```
select pr.*
from products pr
left join posts po
on post_title like concat('%', pr.model, '%')
where post_title is null
```
The above assumes mysql syntax, it will vary slightly by database.
[SQL Fiddle](http://sqlfiddle.com/#!2/ec9d6/5) | I think you want something like this:
```
SELECT p.*
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM posts WHERE post_title LIKE '%' + p.model + '%')
```
This syntax assumes Microsoft SQL Server.
For MySQL, just change the LIKE clause to be LIKE CONCAT('%', p.model, '%') | SQL - Get records from one table that aren't "LIKE" in another table | [
"",
"mysql",
"sql",
""
] |
I'm attempting to create a SQL query to delete child records when the parent has been deleted.
The thing is, the children and parents are both stored in the same table.
Here's the (simplified) data model:
***ThingTable***
```
ID | Name | ParentID
1000 | Thing1 | NULL
1001 | Thing2 | 1000
1002 ... | You can use a Common Table Expression to recurse the
```
-- Begin Create Test Data
SET NOCOUNT ON
CREATE TABLE #ThingTable (
ID INT NOT NULL,
[Name] VARCHAR(255) NOT NULL,
[ParentID] INT NULL
)
CREATE TABLE #ChildThingTable (
ID INT NOT NULL,
[Color] VARCHAR(255) NOT NULL,
)
INSERT INTO #ThingTable (ID,[Name],... | Does adding a constraint constitute 'alter the underlying database structure in any way'
Because I would consider using a constraint with a cascading Delete, This would require the Parent Id column to be a Foreign key to the ID table, then adding the constraint when you delete the primary key, the matching foreign key... | Delete Child Records with Missing Parent | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
My table looks like this AFTER UNION
```
St
----
FUT
80CE
79CE
81PE
79PE
```
I need
```
St
----
FUT
79CE
80CE
81PE
79PE
```
Using this:
```
order by
case St
when 'FUT' then 1 else 2 end ,
case
when St like '%PE' then St end,
case
when St like '%CE' then St end
```
... | Well, you could use `ROW_NUMBER()` to order the data in a common table expression, that would allow you to easily use the row number in the ordering `CASE`;
```
WITH unionresult AS (
<original query here>
), cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY st) rn
FROM unionresult
)
SELECT st FROM cte
ORDER BY
... | Try this:
```
order by case St
when 'FUT' then 1 else 2 end ,
case when St like '%CE' then 1 else 2 end ,
case when St like '%PE' then St end DESC,
case when St like '%CE' then St end
``` | SQL Server 2005 using case in order by | [
"",
"sql",
"sql-server",
""
] |
from table I retrieves values, for example,
```
7752652:1,7752653:2,7752654:3,7752655:4
```
or
```
7752941:1,7752942:2
```
i.e. string may contain any quantity of substrings.
What I need: remove all occurrences of characters from char ':' to a comma char.
For example,
```
7752652:1,7752653:2,7752654:3,7752655:4
``... | I solved this problem with CLR function. It is more quickly and function can be used in complex queries
```
public static SqlString fnRemoveSuffics(SqlString source)
{
string pattern = @":(\d+)";
string replacement = "";
string result = Regex.Replace(source.Value, pattern, replacement);
return new Sql... | Replace `:` with start tag `<X>`.
Replace `,` with end tag `</X>` and an extra comma.
Add an extra end tag to the end `</X>`.
That will give you a string that look like `7752941<X>1</X>,7752942<X>2</X>`.
Cast to XML and use `query(text())` to get the root text values.
Cast the result back to string.
[SQL Fiddl... | T-SQL - remove chars from string beginning from specific character | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Hi I have the following script:
```
DECLARE @sql VARCHAR(2000);
DECLARE @tableName SYSNAME;
DECLARE @columnName SYSNAME;
DECLARE @count INT;
DECLARE @NotCursor TABLE(ID INT IDENTITY(1, 1),
TableName SYSNAME,
ColumnName SYSNAME)
DECLARE @StartLoop INT
DECLARE @EndLoop INT
DECLARE... | @user3712641,This answer is related to the question from [SQL Server 2008 - Optimizing Select statement [duplicate]](https://stackoverflow.com/questions/24998798/sql-server-2008-optimizing-select-statement)
By the time I could answer, the original thread was closed as a duplicate. However as I had already put some tim... | Based on the updated comments that the OP wants to get the counts for all tables, not just the 10 largest counts this can be done with no loops.
```
declare @SQL nvarchar(max)
select @SQL =
STUFF((
select top 20 'SELECT ''' + TABLE_NAME + ''' as [TableName], ' +
'''' + COLUMN_NAME + ''' AS [ColumnName]... | SQL Server 2008 - How to find top 10 tables and order them | [
"",
"sql",
"sql-server",
""
] |
I have a logging table collecting values from many probes:
```
CREATE TABLE [Log]
(
[LogID] int IDENTITY (1, 1) NOT NULL,
[Minute] datetime NOT NULL,
[ProbeID] int NOT NULL DEFAULT 0,
[Value] FLOAT(24) NOT NULL DEFAULT 0.0,
CONSTRAINT Log_PK PRIMARY KEY([LogID])
)
GO
CREATE INDEX [Minute_ProbeID_Val... | This is another approach
```
select *
from log l
where minute =
(select max(x.minute) from log x where x.probeid = l.probeid)
```
You can compare the execution plan w/ a fiddle - <http://sqlfiddle.com/#!3/1d3ff/3/0> | Try this:
```
SELECT T1.*
FROM Log T1
INNER JOIN (SELECT Max(Minute) Minute,
ProbeID
FROM Log
GROUP BY ProbeID)T2
ON T1.ProbeID = T2.ProbeID
AND T1.Minute = T2.Minute
```
You can play around with it on ... | How to select most recent values? | [
"",
"sql",
"sql-server",
""
] |
Here is the result I need, simplified:
```
select name, phonenumber
from contacttmp
left outer join phonetmp on (contacttmp.id = phonetmp.contact_id);
name | phonenumber
-------+--------------
bob | 111-222-3333
bob | 111-222-4444
bob | 111-222-5555
frank | 111-222-6666
joe | 111-222-7777
```
The quer... | Consider the slightly modified test case in the fiddle below.
### Simple case
For the simple case dealing with a **single column** from each column, comparing to the *previous* row with the window function `lag()` does the job:
```
SELECT CASE WHEN lag(c.contact) OVER (ORDER BY c.contact, p.phone_nr)
... | You can do this type of logic in SQL, but it is not recommended. The result set from SQL queries is in a table format. Tables represented unordered sets and generally have all columns meaning the same thing.
So, having a result set that depends on the values from the "preceding" row is not a proper way to use SQL. Alt... | SQL JOIN to omit other columns after first result | [
"",
"sql",
"postgresql",
"window-functions",
""
] |
I have a MySQL table where I have a certain id as a foreign key coming from another table. This id is not unique to this table so I can have many records holding the same id.
I need to find out which ids are seen the least amount of times in this table and pull up a list containing them.
For example, if I have 5 recor... | You need a double `select` in the `having` clause:
```
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = (SELECT MIN(cnt) FROM (SELECT COUNT(*) as cnt FROM table GROUP BY id) t);
``` | I would try with:
```
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM table GROUP BY id ORDER BY COUNT(*) LIMIT 1);
```
This gets the minimum selecting the first row from the set of counts in ascendent order. | Obtain a list with the items found the minimum amount of times in a table | [
"",
"mysql",
"sql",
""
] |
I need a query that could remove unnecessary characters (a not-so-needed trailing comma as an example) from the string stored in my database table.
So that
```
EMAIL_ADD
abc@gmail.com,
abc@yahoo.com,def@example.org,
abs-def@ac.uk,
```
would update it into something like this:
```
EMAIL_ADD
abc@gmail.com
abc@yahoo.c... | Using `TRIM()` function with `TRAILING` option removes a specific unwanted character from end of string , in your case being a comma present at end.
```
UPDATE tableName
SET EMAIL_ADD = TRIM(TRAILING ',' FROM EMAIL_ADD)
```
[**See documentation here TRIM()**](http://www.techonthenet.com/oracle/functions/trim.php) | If you have a specific list of characters to filter out at the start and end use `trim` functions:
```
select ltrim(ltrim(rtrim(rtrim(email_add, ','), ' '), ','), ' ')
from tableX
```
Here I nested `ltrim` and `rtrim` to remove leading and trailing `,` and .
Or using `trim`:
```
select trim(trim(both ',' from ema... | How could I remove unnecessary characters in SQL | [
"",
"sql",
"database",
"oracle",
""
] |
Apologies if I'm not phrasing this well. I've searched for some time but I somehow have been missing how to do this. It would be great if someone could point me in the right direction.
Basically, I have a table with 2 columns: `Serv_No` / `Prd_Name`
Each `Serv_No` (1,2,3,4,5 etc.) may have unlimited varying `Prd_Name... | This is usually done using GROUP BY/HAVING over CASEs:
```
select serv_no
from tab
group by serv_no
having -- include AA
sum(case when prd_name = 'AA' then 1 else 0 end) = 1
-- AA plus at least 1 other row <> BB
and sum(case when prd_name <> 'BB' then 1 else 0 end) >= 2
-- e... | try this:
```
SELECT * FROM [TABLE] WHERE [serv_no] IN(
SELECT [serv_no] FROM [TABLE] GROUP BY [serv_no] having COUNT([serv_no])=1
) AND prd_name = 'AA'
```
this will select all serv\_no where they have only 1 prd\_name and then filter table by them
you can change your condition by adding more conditions at e... | Excluding all ID values based on criteria, with a one to many relationship - SQL | [
"",
"sql",
"teradata",
""
] |
I have two tables called Recovery and Installments.
```
Recovery ([pk] RID, emp_id, amount, duration, type]
Installments ([pk] ID, [fk] recovery_id, recovered_amount, date)
```
When an employee is granted a loan, that information is stored in `Recovery` table. This loan is then recovered installment basis, from mont... | You need `is not null`:
```
WHERE ((CASE WHEN installment IS NOT NULL THEN (amount-installment)
ELSE(amount) END)> 0 )
```
Almost any comparison to `NULL`, including `= NULL` and `<> NULL` returns `NULL`. And, `NULL` is treated as false. Use `IS NULL` and `IS NOT NULL`. | The criteria `installment != NULL` needs to be replaced with `installment is not null`.
[All comparisons to NULL return FALSE.](http://technet.microsoft.com/en-us/library/ms191270(v=sql.105).aspx)
For the specific comparison you are making, this WHERE clause might be easier on the eyes:
```
WHERE (amount - COALESCE(... | SQL Where clause does not filter out "Zero" values | [
"",
"sql",
"sql-server",
"filtering",
"where-clause",
"common-table-expression",
""
] |
I had to make a new table to get the Include statement working in Entity Framework since EF was looking for a table called `be_PostTagbe_Posts`. I was using EF Code First from DB. But now the question is about SQL. I added one row of data and now the include works. But what I am looking for is a SQL command that can co... | ```
SELECT PostTagID AS be_PostTag_PostTagID, PostRowID AS be_Posts_PostRowID
INTO be_PostTagbe_Posts
FROM be_PostTag
Inner JOIN be_Posts
ON be_PostTag.PostID=be_Posts.PostID
```
That command created the new table with the 2 columns populated. | If i understand you ,you want to Copy `Table Z's Column A` to `Table X` And `Table Z's Column B` to `Table Y`.
If it is so, According to your question it is not clear about Table Structure of `TableX` and `TableY`
Assuming `TableX` And `TableY` to single ColumnTable [Apart from IdentityColumn] our query will be
```
... | SQL Command to copy data from 1 column in table and 1 column in another table into a new table? | [
"",
"sql",
"sql-server",
""
] |
I am using oracle 11g and trying to insert a string containing special UTF8 characters eg '(ε- c'. The NLS character sets for the databse are...
```
NLS_NCHAR_CHARACTERSET AL16UTF16
NLS_CHARACTERSET WE8ISO8859P1
```
when I copy and paste the above string into a `NVARCHAR` field it works fine.
if I execute the be... | Our DBA found the solution to this issue. The answer lay in a setting on the dbc connection on the bus to tell it to convert utf8 to NChar.
On The connection pool page add the following lines to the Properties box.
oracle.jdbc.convertNcharLiterals=true
oracle.jdbc.defaultNchar=true
this will allow you to be able to ... | First verify the data is being stored correctly, then use the correct NLS\_LANG settings. See my answer to this question:
[when insert persian character in oracle db i see the question mark](https://stackoverflow.com/questions/24584283/when-insert-persian-character-in-oracle-db-i-see-the-question-mark/24597374#2459737... | Losing special characters on insert | [
"",
"sql",
"oracle",
"xpath",
"utf-8",
"osb",
""
] |
Suppose I have a list of inventory I have acquired/discarded:
```
Date Quantity Item
1/1/2000 10 Apple
2/2/2000 5 Orange
21/10/2000 1 Banana
4/1/2001 2 Apple
8/8/2000 -3 Orange
```
I would now like to generate a query that can produce the number of oranges, ... | Try this:
```
select curr.[Date],
curr.[Quantity] as change_in_qty,
sum(prev.[Quantity])+curr.[Quantity] as total_qty,
curr.[Item]
from tblname curr
inner join tblname prev
on curr.[Item] = prev.[Item]
where prev.[Date] < curr.[Date]
group by curr.[Date],
curr.[Quantity],
... | If you are looking to see quantity
of item by date you may want to try this statement using a `Group BY`.
```
Select [Date],Count(*) As Quantity,
Item from Inventory group by Date,Item
``` | How do I use an Access SQL query to track inventory composition? | [
"",
"sql",
"ms-access",
""
] |
Is there a way to achieve the following union query using only one query using IN clause with multiple columns?
Instead of using
```
select *
from table_a
where field_a in (select field_1 from table_b)
union
select *
from table_a
where field_a in (select field_2 from table_b);
```
I want to create something tha... | The most you can get is to put the union inside the sub query:
```
select *
from table_a
where field_a in (select field_1 from table_b union select field_2 from table_b)
```
Or:
```
select *
from table_a
where field_a in (select field_1 from table_b)
or field_a in ( select field_2 from table_b)
``` | The equivalent is this:
```
select *
from table_a
where field_a in (select field_1 from table_b)
or field_a in (select field_2 from table_b)
```
NOT THIS:
```
select *
from table_a
where field_a in (select field_1, field_2 from table_b)
```
Because in the latter case, field1 and field2 would have to be ap... | IN clause with multiple columns | [
"",
"mysql",
"sql",
""
] |
The idea is to check for the last time the systems were synced up by selecting the start time of the last sync. The problem is that the table that holds the sync info is new and as it moves to production the table will be empty so this query breaks the system because it does not return anything:
```
select ST_DT_TM
fr... | I would change your system code to check the count of records retunred and solve your issue that way. If that isn't possible try:
```
select ST_DT_TM
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE... | Try this:
```
select top 1 ST_DT_TM
from (
select ST_DT_TM,
0 as IsAlternate
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN')
union all
select 0 as S... | SQL case with exists not working | [
"",
"sql",
"sql-server",
""
] |
Let's say I have a simple schema of two tables, `users` and `posts`. The `posts` table has a foreign key to `users` indicating who authored the post.
Also, let's say I want to list the users and their 3 most-recent posts. I can do this in O(n) queries (1 to list users, 1 for each user getting their posts), but how wou... | A self join that should work on most db's. This assumes that `post_time` is unique per user. If that's not the case, then you can replace `on p2.post_time >= p.post_time` with `on p2.id >= p.id`.
```
select u.username, p.id, p.title
from user u join
(
select p.id, p.title, p.user_id
from posts p join posts p2... | You didn't state your DBMS, so this is ANSI SQL (supported by a wide range of DBMS):
```
select *
from (
select u.username,
p.title,
row_number() over (partition by u.id order by p.post_time desc) as rn
from users u
join posts p on u.id = p.user_id
) t
where rn <= 3
order by u.username;... | SQL query: how to get users and their three latest posts? | [
"",
"sql",
"greatest-n-per-group",
""
] |
I have a table where each address has different types, for each type a row. How to find the addresses where for the exact types i need?
Eg.
```
ID TypID Street
1 1 Street 1
1 2 Street 1
2 2 Street 2
3 1 Street 3
3 2 Street 3
```
In the above i need to find addresses which h... | Group by the `id` and then count the different `typeid`s in the `having` clause
```
select id from your_table
where typeid in (1,2)
group by id
having count(distinct typeid) = 2
``` | You can use INTERSECT for this
```
select id
from tbl
where typid = 1
intersect
select id
from tbl
where typid = 2
```
although it won't work in mysql if that happens to be the database you're using. | TSQL - Query for multiple types in multiple rows | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
first table:
```
create table login(
id int auto_increment,
user varchar(20),
pass varchar(20),
primary key(id)
);
```
first table is created with primary key..
second table:
```
create table check(
cid int,
rid int,
usname varchar(20),
word varchar(20),
FOREIGN KEY(rid) REFERENCES login(id... | The problem isn't the foreign key. `check` is a reserved word in MySQL. So you need to choose another name or escape it:
```
create table `check`(
cid int,
rid int,
usname varchar(20),
word varchar(20),
FOREIGN KEY(rid) REFERENCES login(id)
);
```
Ironically, although it is a reserved word, it is ... | `check` is a key word in `MySQL`; either surround it with backticks, `, or choose a different name. | foreign key not creating in table | [
"",
"mysql",
"sql",
""
] |
I'm attempting to do something similar to [this question](https://stackoverflow.com/questions/1250156/how-do-i-return-rows-with-a-specific-value-first). I have this table:

`tab_id` is the... | Try changing the query like this:
```
select *
from cam_to_tab_mapping
where unit_id='90013550'
order by CASE WHEN tab_id='2' THEN 1 ELSE 0 END DESC, tab_id asc, order_in_tab asc
``` | I think you have a copy & paste error in your query.
```
select *
from cam_to_tab_mapping
where unit_id='90013550'
order by (tab_id='2') asc, tab_id asc, order_in_tab asc
```
You have a logical expression as the first `order by` criteria.
Maybe you meant
```
select *
from cam_to_tab_mapping
where unit_id='9001... | Incorrect syntax at '=' | [
"",
"sql",
"sql-server",
""
] |
```
SELECT s1.id,
s3.food_name,
Count(*) AS TotalRefill
FROM (SELECT ( s1.food_value - s2.food_value ) AS difference
FROM `serving_info` s1,
`serving_info` s2
WHERE s1.id - s2.id = '1'
AND s1.food_name = 'Shrimp'
AND s2.food_name = ... | What all others here said is right, but just to give you a more preceise solution, look at the query below it should not be s1.id but it should be diff.id
```
SELECT diff.id,
s3.food_name,
Count(*) AS TotalRefill
FROM (SELECT ( s1.food_value - s2.food_value ) AS difference, s1.id
FROM `se... | S1is defined inside the parentheses and thus not visible outside them, where you reference it. | SQL SELECT query not working | [
"",
"sql",
""
] |
I am using sql to write up a query in which I am trying to choose records that have their date\_from column (of type date/time) that satisfy these conditions:
* it can be any year
* months are june, july, august and september
* AND IF IT IS JUNE, IT SHOULD CONSIDER FROM THE 15th JUNE ONWARDS
Here's what i've tried ..... | ```
WHERE MONTH(emp.date_from) IN (7,8,9)
OR (MONTH(emp.date_from) = 6 AND DAY(emp.date_from) >= 15);
```
**UPDATE**
Or as dates are treated as strings in `MySQL`
```
WHERE RIGHT(emp.date_from, 5) BETWEEN '06-15' AND '09-30';
```
I don't know which would perform better however. | Sqlserver 2012
```
SELECT
*
FROM
employees
WHERE
DateFromParts(2000,month(date_from),day(date_from))
between '2000-06-15' and '2000-09-30'
```
Year 2000 is chosen because it is leap year and will handle leap year issues around 2000-02-29. | SQL Date Wildcards | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a database with two different tables.
```
**call_code** activity
call_id activity_id
maintCall_plan activity_desc
maintCall_unplanned contact_person
creditCalls day
newBussCalls activi... | I get it now guys.. I'm just missing a bracket in some of my fields. Here's the code snippet..
```
sqlStr = "INSERT INTO activity(activity_desc, contact_person, revenue, [day], activity_date, [time]) VALUES ("
sqlStr = sqlStr & "'" & txtAct8am.Text & "',"
sqlStr = sqlStr & "'" & txtComp8am.Text & "',"
sqlStr = sqlStr ... | Your first `INSERT` statement has declared in this wrong way:
You have two field `activity_desc, contact_person` but you try to insert more than two fields (six for precision). So you must add the other 4 missing fields
```
sqlStr = "INSERT INTO activity(activity_desc, contact_person) VALUES ("
sqlStr = sqlStr & "'" ... | Syntax error in my SQL statement "INSERT INTO" | [
"",
"sql",
"ms-access",
"vb6",
""
] |
I'm working through a problem, working with SQL Oracle. I'm getting the right results beside a row that should be showing up that has a count of 0. The question is
**Question:**
For each section of the Project Management course, list the section ID, location and number of students enrolled. Sort by section ID.
**My ... | How about joining to the tables instead of using the WHERE clause:
```
SELECT s.Section_Id,
s.Location,
COUNT(e.Section_Id) AS Enrolled
FROM course c
LEFT JOIN section s
ON c.Course_No = s.Course_No
LEFT JOIN enrollment e
ON s.Section_Id = e.Section_Id
... | You need to outer join to course and enrollment otherwise you won't see sections that don't have any courses/enrollments. You can either use the ANSI syntax ...LEFT JOIN... etc or the old Oracle syntax using (+) against the columns of the deficient table:-
```
SELECT s.Section_Id, s.Location, COUNT(*) AS Enrolled
FROM... | Row that should have a 0 count not showing | [
"",
"sql",
"oracle",
"join",
""
] |
**Is there a way to store the WHERE clause statements as a callable variable?**
I need to run the query below about 20 times using different 'Date' and 'ID' values, but the 'Code' values will stay the same. However, after the 20 queries, I will need to change the 'Code' values to another set of values and using the sa... | In this scenario, I will use a variable table to store the code values like below
The @t table here is a variable table, I.e an in memory table, but it can also be a permenant table
The table contains a value called key, the key column will contain an integer for each set of code ranges you want to store.
For the be... | If this is an ad hoc query that you're just going to run manually a handful of times, this is ugly but correct.
If this is something you'll be doing somewhat regularly, you can store your values in another table. You could have a table called "coderange" that had two columns, "minCode" and "maxCode". Then you'd rewrit... | How to store a list of values as a variable to perform multiple SQL queries? | [
"",
"sql",
"sql-server",
"sql-server-2012",
"table-variable",
""
] |
I have the following query in a stored procedure in SQL server:
```
SELECT TLI.LESNumber
,COUNT(TLT.PL)
INTO #PWCM
FROM #tmpLESImport TLI
INNER JOIN tbl_LES L
on TLI.LESNumber=L.NUMB
WHERE ISNULL(L.DELT_FLAG,0)=0
AND L.SCHL_PK=@SCHL_PK
AND TLI.PL IS NOT NULL
AND LEN(TLI.PL)>0
GROUP BY LESNumber
... | When you `SELECT INTO` a table, it creates the table (in this case, a temp table). In order to create a table, each column needs a name, which your `count` column does not. You just need to give it a name:
```
SELECT TLI.LESNumber,COUNT(TLT.PL) [NumRecords]
INTO #PWCM
FROM #tmpLESImport TLI
...
``` | I had this error for this query
```
SELECT
CASE WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'A'
WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'B'
...
END AS aaa INTO ##TEMPTABLE
FROM [dbo].[my-table]
```
Turns out I had to change the `""` inside the COALSCE into `''`.
Solved ... | SQL Server query erroring with 'An object or column name is missing or empty' | [
"",
"sql",
"sql-server",
""
] |
I have a table that looks something like this:
```
__________________________________________________________________________________
|id |code |code_status |code_due_date|code2 |code_status2 |code_due_date2|...|
|1 |ABCD |A |MMDDYYYY |Null |Null |Null |...|
|2 |Null |Null ... | You can do it like this one:
```
declare
id MY_DATA.PRSN_UNIV_ID%type;
cd varchar2(6);
stat varchar2(1);
due date;
cur sys_refcursor;
begin
for i in 1..30 loop
open cur for
'select PRSN_UNIV_ID, CHKL_ITM_CD_'||i||', CHKL_ITM_STAT_CD_'||i||', CHKL_ITM_DUE_DT_'||i||' from MY_DATA';
l... | You could use a `SYS_REFCURSOR` and the `DBMS_SQL` package to dynamically address this requirement. The below procedure is a generic example of how to dynamically interact with a query, in this case it simply prints the results to the console. You could modify it to test the column descriptions at each iteration and pe... | Looping through rows and then columns in Oracle | [
"",
"sql",
"oracle",
"plsql",
""
] |
I am trying to update a column of the table using the below query.. But I get an error
> An aggregate may not appear in the set list of an UPDATE statement
Code:
```
UPDATE Test.dbo.Table1
SET InDate = MIN(b.Date)
FROM
Test.dbo.Table1 a
LEFT OUTER JOIN
Test.dbo.Table2 b
ON
a.ID1 =... | You need to put the aggregate in a temp table or subquery and you need an explicit `GROUP BY` statement.
```
UPDATE Test.dbo.Table1
SET InDate = min_date
FROM Test.dbo.Table1 c inner join
(SELECT a.id1, MIN(b.Date) min_date
FROM Test.dbo.Table1 a
LEFT OUTER JOIN Test.dbo.Table2 b
ON a.ID1 = b.I... | Assuming your data model is something like the following, joining to a derived table should do the trick:
```
--Data Setup:
DECLARE @Table1 TABLE (ID1 INT, InDate DATETIME)
DECLARE @Table2 TABLE (ID2 INT, ID1 INT, Date DATETIME, Code VARCHAR(12))
INSERT INTO @Table1 (ID1)
VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(1... | Updating Using Aggregate Function | [
"",
"sql",
"sql-server",
""
] |
**I currently have** a table `Bugs` that looks like this:
```
|ID |Priority |Created |Updated |Status |Category
|X123 |Major |01/01 |01/03 |Open |A
|X145 |Normal |01/01 |01/02 |Closed |B
|X678 |Minor |01/03 |01/03 |Open |C
|X763 ... | This is what I tested at last:
```
SELECT d.Dates as Date,
SUM(CASE Priority WHEN 'Major' THEN 1 ELSE 0 END) as Major,
SUM(CASE Priority WHEN 'Normal' THEN 1 ELSE 0 END) as Normal,
SUM(CASE Priority WHEN 'Minor' THEN 1 ELSE 0 END) as Minor,
b.Category
FROM Bugs b
INNER JOIN DatesTable d ON d.Dat... | Something like this might what you are looking for.
```
select b.Date
, SUM(case when b.Priority = 'Major' then 1 end) as Major
, SUM(case when b.Priority = 'Normal' then 1 end) as Normal
, SUM(case when b.Priority = 'Minor' then 1 end) as Minor
, b.Category
from Bugs b
group by b.Date, b.Category
orde... | Grouping types of bugs by date and priority | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
This code compiles, but in TOAD it won't show the "hi wo" output
```
CREATE OR REPLACE PROCEDURE AdelTest IS
tmpVar NUMBER;
BEGIN
DBMS_OUTPUT.ENABLE(100: in INTEGER);
DBMS_OUTPUT.PUT_LINE('hi wo');
tmpVar := 0;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
WHEN OTHERS THEN
--consider logg... | You need to enable DBMS Output. If working in the Editor right-click and choose DBMS Output off of the Desktop flyout menu. There's a button that is red if it's disabled. Click it and it will turn green. Then execute your code. Output will display there. If you are working outside of the Editor (in Schema Browser for i... | You can also view server output if for some reason DBMS output window is not getting enable. use `QSR` editor embedded within toad for oracle edition..
How to use
1. select the code in place
2. Editor > Execute `SQL` via `QSR`
have the set `serveroutput` on as first statement in QSR window and run..
now it will show... | How to get my PUT_LINE statement to display in TOAD? | [
"",
"sql",
"toad",
""
] |
I need to SUM Col3 but the non-empty value for Col2 needs to be retained. Is there a way to accomplish this with a GROUP BY?
Table
```
Col1 Col2 Col3
-----------------------------------
123 abc 2
123 3
```
`SELECT` query:
```
SELECT Col1, Col2, S... | Group by only Col1
```
SELECT Col1, Max(Col2) SUM(Col3)
FROM Table
GROUP BY Col1
``` | Add a filter on col2 with a having clause. With this it will remove line 2 that has the null value.
We cannot consider the row that has the null value and use it only for sum(col3). hence result would be 123, abc, 2 and not 123, abc, 5
```
select col1, col2, sum(col3) as c from table2
group by col1, col2
having col2 ... | How to overwrite empty column values in a GROUP BY with SQL Server? | [
"",
"sql",
"sql-server",
"group-by",
""
] |
In my query's `where` clause I have the condition:
```
User.DateOfBirth BETWEEN @startDate AND @endDate
```
Where `@startDate` and `@endDate` are nullable. If `@startDate` is null, I want all values less than or equal to `@endDate`; if `@endDate` is null, I want all values greater than or equal to `@startDate`; if bo... | Try this:
```
[User].DateOfBirth BETWEEN ISNULL(@startDate,[User].DateOfBirth) AND ISNULL(@endDate,[User].DateOfBirth)
``` | Two approaches spring to mind:
### Tread the four cases separately and then OR them together:
1. start and end are null: any date matches,
2. start is null, so need DoB <= end
3. send is null, so need DoB >= start
4. neither is null, so need between
This will lead to a long expression.
### Use [`IsNull`](https://st... | How can I include null values in BETWEEN clause? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I've moved to PostgreSQL from MySQL, but got strange problem. My query worked perfect in MySQL.
```
SELECT MIN("events"."schedule") AS schedule
FROM "events"
WHERE ("events"."state" IN (1)) AND ("events"."schedule" >= '2014-07-01')
GROUP BY EXTRACT(YEAR FROM "events"."schedule"),
EXTRACT(MONTH FROM "events"."sche... | If you want to order by the resulting column (the min(schedule)) then you can use the following:
```
SELECT MIN("events"."schedule") AS schedule
FROM "events"
WHERE "events"."state" IN (1)
AND "events"."schedule" >= '2014-07-01'
GROUP BY EXTRACT(YEAR FROM "events"."schedule"),
EXTRACT(MONTH FROM "even... | You can also simplify quite a bit:
```
SELECT MIN(schedule) AS schedule
FROM events
WHERE state = 1
AND schedule >= '2014-07-01'
GROUP BY date_trunc('month', schedule)
ORDER BY 1 DESC;
```
In particular, replace the two `EXTRACT` calls with a single [`date_trunc()`](http://www.postgresql.org/docs/current/i... | PostgreSQL grouping error in a query after moving from MySQL | [
"",
"mysql",
"sql",
"postgresql",
""
] |
I'm working through a problem, working with SQL Oracle. For some reason I am getting the result of 13 for instructors teaching that course when I should only be getting 1. There is only 1 Instructor that teaches only 3 or more students in that room.
**Question:**
Create a query to determine the number of instructors ... | try this:
```
SELECT COUNT(*) NumberOfInstructors
From (Select Instructor_Id
FROM Section s
join Enrollment e
on e.Section_Id = s.Section_Id
WHERE s.Location = 'L211'
Group By Instructor_Id
HAVING COUNT(Student_Id) >= 3) Z
``` | I **did not** test the code, but it seems to me you are missing a condition. Your question requires you to find "Instructor that teaches only 3 or more students in that room", but you did not have any condition to check for student number > 3. Try this:
```
SELECT COUNT(Instructor_Id) AS NumberOfInstructors
FROM Secti... | A Query of certain students in a certain room | [
"",
"sql",
"oracle",
""
] |
I would want to leave a sorted table, ie when I did a query `select * from NewTable` I obtained the sorted table.
I've tried, but not sort the table how I specify
```
select column1,column2,column3,column4
into NewTable
from Table1,Table2
order by column1,column2
``` | The clustered index of a table decides how the data is ordered, this example will demonstrate it:
```
CREATE TABLE test (id int, value varchar)
INSERT INTO test VALUES(1, 'z')
INSERT INTO test VALUES(2, 'y')
INSERT INTO test VALUES(3, 'x')
SELECT * FROM test
CREATE CLUSTERED INDEX IX_test ON test (value ASC)
SELEC... | You only get result sets in a particular order when you use `order by`. Tables represent unordered sets, so they have no order except when being output as result sets.
However, you can use a trick in SQL Server to make that `order by` fast. The trick is to using the `order by` in insert and have an identity primary ke... | How to sort a table by columns without query | [
"",
"sql",
"sql-server",
"jquery-ui-sortable",
""
] |
Is there a function in ***PostgreSQL*** that is the same as `NUMTODSINTERVAL(n, interval unit)` in *Oracle*? | If you want a functionality similar to [this](http://docs.oracle.com/cd/B12037_01/server.101/b10759/functions093.htm) function (i.e. the unit is variable -- not constant): a simple concatenation & a cast is enough in PostgreSQL:
```
select cast(num || unit as interval)
```
[SQLFiddle](http://sqlfiddle.com/#!15/d41d8/... | Just multiply your variable with the desired interval:
```
interval '1' day * n
```
Since Postgres 9.4 you can also use the function [make\_interval()](https://www.postgresql.org/docs/9.4/functions-datetime.html)
```
make_interval(days => n)
``` | NUMTODSINTERVAL in PostgreSQL | [
"",
"sql",
"oracle",
"postgresql",
""
] |
I have the following tables
```
AdmittedPatients(pid, workerid, admitted, discharged)
Patients(pid, firstname, lastname, admitted, discharged)
DiagnosticHistory(diagnosisID, workerid, pid, timeofdiagnosis)
Diagnosis(diagnosisID, description)
```
Here is an SQL Fiddle: <http://sqlfiddle.com/#!15/e7403>
Things to note... | Not sure why out need group by or having here... no aggregate...
```
SELECT A.pid, firstname, lastname, A.workerid, P.admitted, A.discharged
FROM patients P
INNER JOIN admittedpatients A
on P.pID = A.pID
WHERE date_add(a.discharged, interval 30 day)>=p.admitted
and p.admitted >=a.discharged
```
updated fiddle: <... | I didn't see any diagnostic info in the fiddle, so I didn't return any.
```
select pid
,p.lastname,p.firstname
,ad.lastname,ad.firstname
from AdmittedPatients as a
join AdmittedPatients as d using (pid)
join Patients as p using (pid)
join AdminDoctors as ad on ad.workerid=a.workerid
where d.discharged between a.admi... | Postgresql - retrieve rows within criteria within 30 day span | [
"",
"sql",
"postgresql",
""
] |
I'm having trouble finding the right sql query. I want to select all the rows with a unique x value and if there are rows with the same x value, then I want to select the row with the greatest y value. As an example I've put a part of my database below.
```
ID x y
1 2 3
2 1 5
3 4 6
4... | Here is a typical way to formulate the query in ANSI SQL:
```
select b.*
from base b
where not exists (select 1
from base b2
where b2.x = b.x and
b2.y > b.y
);
```
In Postgres, you would use `distinct on` for performance:
```
select distinc... | You could try this query:
```
select x, max(y) from base group by x;
```
And, if you'd also like the `id` column in the result:
```
select base.*
from base join (select x, max(y) from base group by x) as maxima
on (base.x = maxima.x and base.y = maxima.max);
``` | SQL query: same rows | [
"",
"sql",
"r",
"postgresql",
"sqldf",
""
] |
I am looking for a way to change the output of an access query to return either 1, 2 or 3 in replace of Low, Medium or High. I would like to convert the format of the field from Text to Numeric, since I wish to perform calculations using these numbers. Any ideas would be appreciated. | Another possibility is [switch](http://www.techonthenet.com/access/functions/advanced/switch.php), for example:
```
SELECT Field1,
Switch([field1]="Low",1,[Field1]="Medium",2,[Field1]="High",3) AS SwitchValue
FROM aTable
```
But it may be more convenient to simply create a small table with the substitute valu... | You can use `iif()` in MS Access:
```
select iif(col = 'High', 3, iif(col = 'Low', 1, 2)) as ColNumeric
``` | Microsoft Access Query - Convert Text to Numeric Depending on Field Contents - Low, Medium, High to 1,2 ,3 | [
"",
"sql",
"ms-access",
"text",
"format",
"numeric",
""
] |
I'm using SQL Server 2012.
When I run this query...
```
select
count(*)
from
MembershipStatusHistory msh
join
gym.Account a on msh.AccountID = a.AccountID
join
gym.MembershipType mt on a.MembershipTypeID = mt.MembershipTypeID
join
MemberTypeGroups mtg on mt.MemberTypeGroupID = mtg.MemberTypeG... | Very strange but try something like this....
```
declare @CancellationsToday int;
select @CancellationsToday = count(*)
from MembershipStatusHistory msh
join gym.Account a
on msh.AccountID = a.AccountID
join gym.MembershipType mt
on a.MembershipTypeID = mt.MembershipTypeID
join MemberTypeGroups mtg
on mt.MemberTypeGr... | Mmmm strange, try this:
```
SELECT @CancellationsToday = COUNT(*) FROM ......
```
Another thing worth to mention is don't use functions in the `WHERE` clause.
I think you have only the date in `msh.ChangeDate`, make a variable with today's date like this:
```
DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
```
and use ... | Horrible sql server performance when capturing result in variable | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Hi i have 2 tables.
```
A B
|-----|--------------| |------|-------|--------|
| ID | aText | | ID | aId | bText |
|-----|--------------| |------|-------|--------|
| 1 | test | | 10 | 1 | zzzzz |
|-----|--------------| |------|-------|-------... | exactly no. You should use one table with parent
```
|------|-------|--------|
| ID |Parent | Text |
|------|-------|--------|
| 1 | | zzzzz |
|------|-------|--------|
| 10 | 1 | yyyyy |
-------------------------
```
Parent column foreign key to ID column its mean self refferencing. | Yes if `aText` is `UNIQUE` in table `A`; create a `UNIQUE INDEX` on `(aId,btext)` for table `B`
Otherwise I don't think it is possible with your current data structure. | Unique key on 2 columns over joined tables | [
"",
"mysql",
"sql",
"database",
""
] |
I'm faced with a big query that is generated in a string and executed with "OPEN pCursor FOR vQuery" and I'm trying to get the query out of the string variable and as a proper "compilable" query.
I'm having this problem where a different table is query depending on a variable
```
vQuery := 'SELECT ...';
IF pVar = 1 ... | You could use a [UNION](http://www.w3schools.com/sql/sql_union.asp) and use your variable pVar to only include the results from one query in the result set.
```
SELECT t1.col1, t1.col2, ..., t1.col10
FROM table1 t1
WHERE pVar = 1 and ...
UNION
SELECT t2.col1, t2.col2, ..., t2.col10
FROM table1 t2
WHERE pVar <> 1 and .... | Perhaps using UNION / UNION ALL to unite both queries? The requirement for using UNION/UNION ALL is that all SELECTs being united must return columns with the same names.
So if you have
```
SELECT t.f1,
t.f2,
t.f3
FROM t
WHERE ...
and your other query is
SELECT q.f1,
q.f2,
q.f3
FROM ... | Same query but different tables | [
"",
"sql",
"oracle",
""
] |
I have this table:
```
Date |StockCode|DaysMovement|OnHand
29-Jul|SC123 |30 |500
28-Jul|SC123 |15 |NULL
27-Jul|SC123 |0 |NULL
26-Jul|SC123 |4 |NULL
25-Jul|SC123 |-2 |NULL
24-Jul|SC123 |0 |NULL
```
The reason only the top row has an OnHand val... | Try this (**[Fiddle demo](http://sqlfiddle.com/#!3/a9164/33)**)
```
DECLARE @Movement INT , @OnHandRunning INT
;WITH CTE AS
(
SELECT TOP 100 percent DaysMovement, OnHand
FROM Table1
ORDER BY [StockCode], [Date] DESC
)
UPDATE CTE SET @OnHandRunning = OnHand = COALESCE(@OnHandRunning - @Movement, OnHand)... | This works, no idea how it performs compared to a cursor though?
```
--Data
DECLARE @Table TABLE (
[Date] DATE,
StockCode VARCHAR(50),
DaysMovement INT,
OnHand INT);
INSERT INTO @Table VALUES ('20140729', 'SC123', 30, 500);
INSERT INTO @Table VALUES ('20140728', 'SC123', 15, NULL);
INSERT INTO @Table V... | SQL Update table with cumulative value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Say I have these tables:
```
create table letter (id_letter bigint, id_group_table bigint, letter char(1));
create table group_table (id_group_table bigint, id_whatever bigint, champion char(1));
create table whatever (id_whatever bigint);
```
I want to update the `group_table` so I can set in the `champion` column... | ```
update group_table
join
(
select tab1.letter, tab1.id_group_table from
(
select letter,
id_group_table,
count(letter) as occurrences
from letter
group by id_group_table, letter
order by occurrences desc
) tab1
group b... | You can do a `JOIN` with `group_table` separately in inner query like below
```
update group_table
join
(
select letter,
id_group_table,
count(distinct id_group_table) as occurences
from letter
group by letter
having max(occurences)
... | How to reference outer table in a SET sub query? | [
"",
"mysql",
"sql",
""
] |
As I am not good with MySQL query's so I wish someone help me for creating this kind of sql query.
I having two MySQL tables which is describe bellow:
```
Table Name: rating
-------------------
property_id user_id area_rate_count safety_rate_count friendly_rate_count walkability_rate_count
4 28 ... | I think you want the `avg()` aggregation function along with a `join`:
```
select l.property_id, l.title,
coalesce(avg(area_rate_count + safety_rate_count + friendly_rate_count + walkability_rate_count
), 0) as rate
from listing l left outer join
property_id p
on l.property_id = p.property_i... | If I understood it right I think you need this:
```
select l.property_id, l.title, coalesce(r.ssum/if(r.ct=0,1,r.ct), 0) as rate
from listing l LEFT JOIN
(select property_id,
sum(area_rate_count+safety_rate_count
+friendly_rate_count+walkability_rate_count) ssum,
... | SQL - How to calculate column value and join with another table | [
"",
"mysql",
"sql",
"sum",
""
] |
I have a varchar value display as same as SQL date time.i need to convert this to SQL date time format.can any one help me.........
```
2014-07-28 18:05:14(varchar) --> 2014-07-28 18:05:14(DateTime)
``` | ```
select cast('2014-07-28 18:05:14' as datetime)
``` | YOU CAN TRY THIS
```
cast('2014-07-28 18:05:14' AS DATETIME)
``` | SQL Convert varchar value to datetime | [
"",
"sql",
""
] |
Fairly new to SQL programming.
I'm trying to create a stored procedure which will take the users name, compare it to the users table to retrieve their 'role' and then select all pieces of Feedback from the Feedback table which are related to them.
There are currently 3 possible values:
- User
- Governance Board
- Adm... | You can write this query as a single `select`.
```
select f.*
from Feedback f cross join
(SELECT [Role] FROM [CSLL].[Users] WHERE [Alias] = @Alias) r
where (r.[role] in ('Admin', 'Governance Board') ) or
(r.[role] = 'User' and ([Publish] = True OR [Author] = @Alias or [IdentifiedBy] = @Alias))
```
I think ... | You can't use CASE this way to control flow. You have to use IF.
```
IF @Role='Admin'
SELECT * FROM [CSLL].[Feedback]
ELSE IF @Role='Governance Board'
SELECT * FROM [CSLL].[Feedback]
ELSE IF ... etc
``` | SQL CASE Selection Statement Error | [
"",
"sql",
"sql-server",
"stored-procedures",
"case",
""
] |
I have a list of items and, by deposit, stocks, purchase orders, sales orders, forecasts of consumption or production, etc.. I want to set up a query for each item back to me all this information, deposit by deposit. Obviously, it is not said that this information is available for each item.
For example, considering t... | An example with all the 4 tables and Coalesce as stated by Gordon Linoff
```
;with[T1]([REF])as(
select * from (values(1),(2))[A]([REF])
),
[T2]([REF],[DEPOT])as(
select*from(values
(1,'A'),
(1,'B'),
(1,'E')
)[a]([REF],[DEPOT])
),
[T3]([REF],[DEPOT])as(
... | You can fix your particular query by using `coalesce()`:
```
SELECT coalesce(T1.ref, t2.ref, t3.ref) AS T1ref
```
However, instead of using `full outer join`, I find it easier to start with the lists and combinations that I care about. In this case, you seem to care about `t1.ref` and `depots` from all the tables. Pe... | FULL JOIN on severals tables | [
"",
"sql",
"sql-server",
"join",
"outer-join",
""
] |
This has been stumping me for a little bit and I can't seem to get the right query
Table 1:
```
╔════════════════════╗
║ Record Level ║
╠════════════════════╣
║ 1 0 ║
║ 1 1 ║
║ 1 2 ║
║ 2 3 ║
║ 2 4 ║
║ 2 5 ║
║ 3 ... | You can use a sub-query to first determine the max levels and then do a count of the max levels, as below:
```
SELECT
max_level,
count(*)
FROM
(
SELECT
max(level) AS max_level
FROM table1
GROUP BY Record
) max_levels
GROUP BY max_level
ORDER BY max_level;
``` | You need two steps, (1) find the max level for each record and (2) count the records that have that max level for each level. You can use a subquery to create the Record/MaxLevel table:
```
SELECT MaxLevel, COUNT(*) AS RecordCount
FROM (
SELECT Record, MAX(Level) AS MaxLevel
FROM Table1
GROUP B... | SELECT Count of MAX value over 2 columns | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I am having a problem with the last select statement, the OR. what we want is to include
records who have TIER = T1 but only if the have a COST > 500 and skilllevel = 'S'. but this code of last line only has to be an OR. AND will leave out most of the records.
```
Insert Into @tblMain
Select * from (
... | SQL Server will respect parentheses for order of evaluation, which I think you need:
```
...
AND
(
(TIER <> 'T1')
OR
(TIER = 'T1' AND COST>500 AND SKILLLEVEL = 'S')
)
``` | By default in sql server `NOT` takes precedence over `AND` , `AND` takes precedence over `OR`
```
NOT --> AND --> OR
```
to enforce an order other than default you can make use of Parenthesis.
```
...........
and f.FACILITY_ID = @FacilityId
and a.STAT not in (3,4,5)
and (
(TIER <> 'T1')
OR
... | Or on Query not working | [
"",
"sql",
""
] |
Is there any difference when I create a table index for more columns if I use the columns in different order?
Exactly is difference between `ID, isValid, Created` and `ID, Created, isValid` indices?
And is there any difference in querying order?
```
where ID = 123
and isValid = 1
and Created < getdate()
```
v... | > Exactly is difference between `ID, isValid, Created` and `ID, Created, isValid` indices?
If you always use **all three** columns in your `WHERE` clause - there's no difference.
(*as Martin Smith points out in his comment - since of the criteria is not an equality check, the sequence of the columns in the index **d... | `AND` is commutative, so the order of ANDed expressions in `WHERE` doesn't matter.
Order of columns in an index *does* matter, it should match your queries.
If `ID` is your table's clustered primary key and your queries ask for specific `ID`, don't bother creating an index. That would be like giving an index to a book... | SQL Server table index columns order | [
"",
"sql",
"sql-server",
"indexing",
"query-performance",
""
] |
I have a problem once I want to run the next query:
```
declare @j int = 1;
declare @column varchar(255);
set @column = 'last_name';
declare @tmp varchar(255);
declare @query nvarchar(255) = N'select ' + @column + N' from TEST where id = @j'
declare @tbl table(tmp varchar(255))
insert into @tbl
exec sp_executes... | in the place of ==== `where id = @j'`
change like this may it works
Convert(nvarchar(2), @j); | You need to cast the `@j` variable to string. AS its type is [INT](http://msdn.microsoft.com/en-us/library/ms187745.aspx) you should cast it as
```
CAST(@j AS VARCHAR(12))
```
Also, you can pass parameters to dynamic SQL statement when it is executed using `sp_executesql`. In your case it will be something like this:... | Variable in a dynamic query | [
"",
"sql",
"sql-server",
"variables",
"dynamic",
""
] |
Hello I am currently developing a small website for a real estate and I want to design a database for it. I have implemented user sign-up but I want the user to select one or more roles. To be more specific a **user** can be someone who can **sell** or **buy** houses or **both**. So for each user-type I want to have a ... | It has been already said that you could use foreign key to link your buyer and seller tables to the user they represent. As a minor improvement I can propose you to use `user_id` as primary key for both your `seller` and `buyer` tables while it is the foreign key at the same time.
```
User:
int userid; (Primary Key)
v... | You don't say what database you are using, but I'll guess maybe it's MySql? Anyway, the following principles will apply to almost any relational database package (MS Access, SQL Server, PostGres etc)
For any table that has a relationship with the user table, you need to have a "foreign key", which is a field that rela... | How to connect base table with its specific role variation tables? | [
"",
"sql",
"database-design",
""
] |
I am having issues forming this SQL string in VB6
```
Select A.ID, A.AstTp, A.Offset, A.Age, B.LNo, B.ACnt, B.CommCnt
Into [LnReg]
From [ALPA] In [c:\Temp\ALPA.mdb] As A
LEFT OUTER JOIN
[ALX] IN [c:\Temp\ALX.mdb] As B On A.ID = B.ID Where (A.AstTp="Sealed")
```
My ADO connection is to the mdb with LnReg.
Error t... | I prefer linking table from other mdb files to main mdb file. I use this functions to linking tables. With linked table you can do anything like with local table.
```
Function AccessLinkToTable(sLinkFromDB As String, sLinkToDB As String, sLinkToTable As String, Optional sNewLinkTableName As String, Optional sPassword ... | ```
Select A.ID, A.AstTp, A.Offset, A.Age, B.LNo, B.ACnt, B.CommCnt
Into [LnReg]
From [c:\Temp\ALPA.mdb].ALPA As A
LEFT OUTER JOIN [c:\Temp\ALX.mdb].ALX As B On A.ID = B.ID Where (A.AstTp="Sealed")
``` | Using two mdbs to Select Into a third | [
"",
"sql",
"vb6",
"adodb",
""
] |
My goal is to create a query that will return a count of unique customers who have purchased in a 365 day window. I created the query below in postgres and and the resulting queries are very slow. My table is 812,024 rows of just order dates and customer id's. When I remove the distinct statement, I can get the query t... | Assuming actual `date` types.
```
SELECT d.day, count(distinct o.id) AS users_past_year
FROM (
SELECT generate_series(min(order_date), max(order_date), '1 day')::date AS day
FROM orders -- single query
) d
LEFT JOIN ( -- fold duplicates on same day right away
SELECT id, order_date
... | No need for the self-join, use `generate_series`
```
select
g.order_date as "Ordered",
count(distinct o.id) as "Users"
from
generate_series(
(select min(order_date) from orders),
(select max(order_date) from orders),
'1 day'
) g (order_date)
left join
orders o on o.order... | Slow query in postgres using count distinct | [
"",
"sql",
"postgresql",
""
] |
I have the following table:
```
my_table
------------------------
| common_id | uniq_val |
------------------------
| 1 | foo |
------------------------
| 1 | bar |
------------------------
```
And I want to aggregate values from it such that the resulting query looks lik... | How about simple aggregation?
```
select common_id, min(uniq_val) as uniq_val_1, max(uniq_val) as uniq_val_2
from my_table
group by common_id;
``` | you can try `distinct on`
`SELECT distinct on (t1.common_id) t1.common_id, t1.uniq_val, t2.uniq_val
FROM my_table t1 JOIN my_table AS t2
ON t1.common_id=t2.common_id
WHERE t1.uniq_val!=t2.uniq_val;`
I think it will produce what you need! | Aggregating a unique pair of column values from the same table based on a common column value | [
"",
"sql",
"postgresql",
"join",
"group-by",
""
] |
I have many many rows in the table. The table has a Date column (which includes date and time)
I want to be able to loop through the table and find any gap between the two rows where the difference between the row is 5 min.
For example:
```
ID Date
1 2014-07-29 13:00:00
2 2014-07-29 13:01:00
3 2014-07-29 13:07:00
``... | One way to do it
```
WITH ordered AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY date) rn
FROM table1
)
SELECT o1.id id1, o1.date date1, o2.id id2, o2.date date2, DATEDIFF(s, o1.date, o2.date) diff
FROM ordered o1 JOIN ordered o2
ON o1.rn + 1 = o2.rn
WHERE DATEDIFF(s, o1.date, o2.date) > 60
```
Output:
``... | Since you are on SQL Server 2012, you can make use of the `LEAD` and `LAG` functions, like so:
```
;with cte as
(select id,
[date],
datediff(minute,[date],lead([date],1,0) over (order by [date])) difference,
row_number() over (order by [date]) rn
from tbl)
select * from cte
where rn <> 1 --Skip first row ordered... | Find a gap between time stamp | [
"",
"sql",
"sql-server",
""
] |
I have a table structure like this:
```
-------------------------------------
| Country | Count 1 | Count 2 |
-------------------------------------
| USA | 10 | 10 |
-------------------------------------
| USA | 10 | 10 |
-------------------------------------
| France |... | Try using [`SUM()`](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum)
```
SELECT Country,
SUM(`Count 1` + `Count 2`) AS count
FROM table_name
GROUP BY country
``` | This is pretty straight-forward, you can use the aggregate function [`SUM()`](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum) with a `GROUP BY`:
```
SELECT country,
sum(count1 + count2) as Total
FROM yourtable
GROUP BY country;
```
See [Demo](http://sqlfiddle.com/#!2/1ef0e/1) | SQL: Selecting sum of two columns across multiple rows | [
"",
"mysql",
"sql",
""
] |
I am receiving the 0x84BB0001 Error after attempting to install a new instance of SQL Server 2012. This is happening after an uninstall of a previous version of SQL Server 2012. I have pasted the log file below. Any help is greatly appreciated.
```
Overall summary:
Final result: Failed: see deta... | I was able to get past the error by changing the instance name. The old instance name from the uninstalled version was SQLEXPRESS, I changed this to SQLEXPRESS2012 and the installation proceeded. | Have you tried deleting the contents in the folder?
C:/Users/[UserName]/AppData/Local/Microsoft\_Corporation.
installation again as a repair, hope this will work. | Error 0x84BB0001 while installing Sql Server 2012 | [
"",
"sql",
"sql-server",
"database",
""
] |
I'm running the below SQL query:
```
SELECT
share_name AS "Server",
Capacity, Available,
((available * 1.00) / capacity) * 100 as "% Free"
FROM
storage_info
WHERE
share_name LIKE '%192.168.1.1%'
OR share_name LIKE '%192.168.1.2%'
OR share_name LIKE '%192.168.1.3%'
OR share_name LIKE ... | ```
SELECT CASE WHEN share_name LIKE '%192.168.1.1%' THEN 'SERVER 1'
WHEN share_name LIKE '%192.168.1.2%' THEN 'SERVER 2'
WHEN share_name LIKE '%192.168.1.3%' THEN 'SERVER 3'
WHEN share_name LIKE '%192.168.1.4%' THEN 'SERVER 4'
ELSE share_name END AS "Server",
Capa... | You can do it as follows:
```
SELECT
CASE
WHEN
share_name = '192.168.1.1'
THEN
'Server 1'
ELSE
share_name
END AS "Server",
Capacity, Available,
((available * 1.00) / capacity) * 100 as "% Free"
FROM
storage_info
WHERE
share_n... | How can I change the results of a single column of a sql query, within the query itself? | [
"",
"sql",
"sql-server",
"database",
""
] |
I am having problems with the following script. I am trying to return a table where recipient counts for both mailings are returned simultaneously. I know that what I have is wrong, but it may give you an idea of what I am looking for.
```
SELECT count( mailing_recipient_id ) AS CountA
FROM mailing... | You can use a `JOIN` and `GROUP BY` to achieve the result you're looking for, as:
```
SELECT
m.mailing_name ,
count(mr.mailing_recipient_id)
FROM mailing_recipient mr
INNER JOIN mailing m
ON mr.mailing_id = m.mailing_id
GROUP BY m.mailing_name
ORDER BY m.mailing_name;
``` | Just throw them in a subquery:
```
SELECT SUM(tot.CountA) FROM (
SELECT count( mailing_recipient_id ) AS CountA
FROM mailing_recipient
WHERE `mailing_id` =(
SELECT mailing_id
FROM mailing
... | MYSQL: Return Counts from Multiple Tables | [
"",
"mysql",
"sql",
"join",
"return",
""
] |
I have a table with columns A,B,C and I'd like to get all combinations of records having {B,C} unique.
That is both B value and C value will appear only once in one set.
Do you have any ideas how to achieve that? I assume the output has to contain one combination on a single row, which is not a problem.
To make it cl... | I think you want a strange verson of a self join:
```
select t1.*, t2.*
from table t1 join
table t2
on t1.b <> t2.b and t1.c <> t2.c;
```
This will return all pairs from the table where the `b` columns have distinct values and the `c` columns have distinct values. | This is what group by is for. It combines all records with the same values in the group by list into a single row.
```
select B, C
from my_table
group by B, C
``` | SQL restricted set of combinations | [
"",
"mysql",
"sql",
"combinations",
"restrict",
""
] |
I have a Database,Which is in Single user mode ,If i want to access a tables in the database i will be changing in the properties from single to multiuser.How can i make the Database multi user permenantly?. | `ALTER DATABASE [MyDB] SET MULTI_USER`
If it throws an error like `user is already connected to it`, select 'master' db in the dropdown and try it that way.
If that doesn't do it, use `sp_who` to find what spid is accessing the DB and kill it. | If you want to do it in SSMS object explorer.
Right click on your database.
Go to properties > options.
Scroll to the bottom and find "Restrict Access" and change it to multi\_user.
Click ok.
Just an alternative to query window. Both do the same the same. | How to change database from Single user mode to multi user | [
"",
"sql",
"sql-server",
"database",
"database-administration",
"administrator",
""
] |
I have an application that will provide me with a string from which some unknown portion of that string may be the entire string found in the column of another record, i.e.,
I am provided with "A12345B" and there may be a record in the table whose [SerialNumber] column is equal to "12345" or perhaps to "123".
Is ther... | Here's a couple of ways to achieve that:
Assuming we have a search variable:
```
DECLARE @Input NVARCHAR(50) = 'ABC12345'
```
**Using [LIKE](http://msdn.microsoft.com/en-gb/library/ms179859.aspx) Operator**
```
SELECT *
FROM MyTable
WHERE @Input LIKE '%' + SerialNumber + '%'
```
If you need to exclude blank `Seria... | If I understand your question correctly you're looking for `CHARINDEX`. It accepts two strings and looks for one in the other.
```
CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] )
``` | SQL query to find record from superset of characters | [
"",
"sql",
"sql-server",
"sql-server-ce",
""
] |
I am struggling writing a (to me!) complex query which will calculate the total number of units sold of items, pulling data from two separate tables. I am using MySQL.
The first table is a simple 'order\_contents' table (`sale_ord_contents` in my example) with item\_id's and the quantity sold. Some items may be an Ass... | Updated my answer, please try again the following:
```
SELECT
IF (soac.item_id IS NULL, soc.item_id, soac.item_id) as item_id,
IF (soac.name IS NULL, soc.name, soac.name) as name,
SUM(soc.quantity * COALESCE(soac.quantity, 1)) AS total_sold
FROM
sale_ord_contents soc
LEFT OUTER JOIN sale_ord_as... | The key to solving your problem is a left join. Essentially what this does is it matches up values between the table on the left and the table on the right side of the `left join`. If the table on the right doesn't have any values that match up correctly, `null` is inserted instead. Doing a left join between sale\_ord\... | Multiple Table Query with SUM and COUNT | [
"",
"mysql",
"sql",
"count",
"sum",
"multiple-tables",
""
] |
suppose I've these two tables with the sample data:


I want to find which employees don't have the role say 5330. The answer should be employee 2 & 3.
If I simply try doing a employee left outer join w... | You can do this with a `Where Not Exists`:
```
Select e.*
From employee e
Where Not Exists
(
Select 1
From employee_roles r
Where r.employee_id = e.employee_id
And r.role_id = 5330
)
``` | Here is the syntax for the `left outer join` version:
```
select e.*
from employee e left outer join
employee_roles er
on er.employee_id = e.employee_id and er.role_id = 5330
where er.employee_id is null;
```
The logic is that you use the `left outer join` to look for matches and returns the rows where ther... | sql with set difference capability | [
"",
"sql",
"db2",
""
] |
How can I get the Count of the subgroup. I have Table1 and Table2 (below). How can I get the table Result. I tired group by but only manage to get the total rows. I am trying it in Microsoft SQL.
```
Table1
ID PriID Function
1 500 A
2 500 B
3 500 C
4 501 A
5 501 B
6 502 C
7 503... | Try this
```
SELECT t1.Function,
SUM(CASE WHEN Color = 'Green' THEN 1 ELSE 0 END) AS Green,
SUM(CASE WHEN Color = 'Red' THEN 1 ELSE 0 END) AS Red,
Count(t1.PriID) as Total FROM Table1 t1
LEFT JOIN Table2 t2 on t1.PriID = t2.PriID
GROUP BY t1.function
``` | This is the best approach for doing this stuff
```
;with cte as
(
select [Function],t1.priID,color
from tbl1 t1
join tbl2 t2 on t1.priID = t2.priid
),def as
(
select [Function],[Green],[Red]
from
(
select [Function],color,priID from cte) dk
Pivot (count(priID) for color in(... | How to get the Count of the subgroup in SQL | [
"",
"sql",
"t-sql",
""
] |
I am using a CASE statement to return Morning, Evening or Not Yet closed on basis of comparison. It works best but not for 'Not Yet Closed'. It returns null which I don't want. I want if no closing date has been inserted then it should return 'Not Yet Closed' instead of NULL.
```
ALTER PROCEDURE [dbo].[USP_Report_Sele... | You must use **`Else`** in your case statement.
```
Select ComplaintID, ComplaintSubject, Complainants.ComplainantName as Complainant,
Case
When (datepart(hour, Complaints.ClosingDateTime) < 17) then 'Morning'
When (datepart(hour, Complaints.ClosingDateTime) >= 17) then 'Evening'
... | You check with **`IS NULL`** and **`ELSE`** part:
Try like this
```
Select ComplaintID, ComplaintSubject, Complainants.ComplainantName as Complainant,
Case
When (datepart(hour, Complaints.ClosingDateTime) < 17) Then 'Morning'
When (datepart(hour, Complaints.ClosingDateTime) >= 17) ... | Returning message instead of null in case statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've started to use access recently. I am trying to insert a few rows into the database; however, I am stuck as it is throwing an error:
> Too few parameters.
I have a table test with only one column in it named start\_date I want to insert all the dates between two dates for example if I consider 1/7/2014 to 3/7/201... | since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.
Now, please use the code below to insert the date values into your table. I have teste... | You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date y... | Error "Too few parameters." when attempting to insert values into a database table using VBA in MS access | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2010",
""
] |
I want to add a clause that does the following:
```
DECLARE @RequiresApproval BIT
SET @RequiresApproval = 0
SELECT * FROM [user] u
WHERE school_id = 1
```
Here's my logic I want
* when @RequiresApproval = 1, then add the clause: AND approved = 1
* when @RequiresApproval = 0, then leave out the clause: AND approved =... | Ok. This should implement your logic:
```
SELECT *
FROM [user] u
WHERE school_id = 1 AND
(@RequiresApproval = 0 or approved = 1);
``` | You can use this query - you just need to use `OR` between your two conditions.
```
SELECT * FROM [user] u
WHERE school_id = 1
AND (approved = 1 OR @RequiresApproval = 0)
``` | SQL Conditional AND Clause | [
"",
"sql",
"sql-server",
""
] |
I have a table with arrays as one column, and I want to sum the array elements together:
```
> create table regres(a int[] not null);
> insert into regres values ('{1,2,3}'), ('{9, 12, 13}');
> select * from regres;
a
-----------
{1,2,3}
{9,12,13}
```
I want the result to be:
```
{10, 14, 16}
```
that is: `{... | **General solutions** for any number of arrays with any number of elements. Individual elements or the the whole array can be NULL, too:
### Simpler in 9.4+ using [`WITH ORDINALITY`](http://www.postgresql.org/docs/current/functions-srf.html)
```
SELECT ARRAY (
SELECT sum(elem)
FROM tbl t
, unnest(t.arr)... | If you need better performances and can install Postgres extensions, the [agg\_for\_vecs](https://github.com/pjungwir/aggs_for_vecs) C extension provides a `vec_to_sum` function that should meet your need. It also offers various aggregate functions like `min`, `max`, `avg`, and `var_samp` that operate on arrays instead... | Pairwise array sum aggregate function? | [
"",
"sql",
"arrays",
"postgresql",
"aggregate-functions",
""
] |
Need some help with the logic for SQL join
Table1
* CustomerID (ex.1234123)
* Customer\_name (ex.string)
Table 2
- CustomerID (ex.1234 but has it multiple times in the column)
- products (dog food, cat food, etc on different rows within the same column)
- revenue for product
How do join two tables together when one... | Try:
```
select c.customerid,
C.Customer_name,
sum(case when product = 'dog food' then revenue else 0 end) as dog_food_rev,
sum(case when product = 'cat food' then revenue else 0 end) as cat_food_rev
from table1 c
join table2 p
on c.customerid = p.customerid
group by c.custom... | Pivoting the table
```
Select CustomerID, Customer_name, IsNull([Dog Food],0) [Dog Food], IsNull([Cat Food],0) [Cat Food]
from (
select A.*, B.product, B.Revenue
from Table1 A
inner join Table2 B
on A.CustomerID = B.CustomerID
) A
pivot (sum(revenue) for product in ([Dog Food],[Cat Food])) B
```
[SQL Fidd... | logic on join two tables and using sum formula | [
"",
"sql",
""
] |
I am looking for some help in regards to the format that I want my data outputted.
Below is a snippet of the code I am using. It is currently converting the value from the database in seconds and outputting it like
> 1d 12:05:52
I want it to output the information so it calculates the day in the hours, so basically ... | This should work:
```
SELECT
CASE WHEN [Running]/3600 <= 9 THEN '0' ELSE '' END +
CONVERT(VARCHAR(10),[Running]/3600)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),([Running]%3600)/60),2)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),[Running]%60),2) AS [Running]
```
I tested it using this:
```
DECLARE @Running int
SET ... | As @Hadi said in his comment, you can use the TimeSpan object in VB.Net (you've tagged the question with this so it seems reasonable to suggest), but you could also use this bit of SQL instead, which I think is slightly simpler than the other suggestion :
```
CAST(CAST(FLOOR([Running] / 3600) AS INT) AS VARCHAR) +
RI... | SQL statement DateTime format | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
I'm working in an IO bound system (and this isn't going to change). So I'm rewriting some sql to only update when it needs to and it's going really well. I'm seeing about a 70% increase in performance. The only problem is the sql is more bloated which isn't the end of the world, just more code to maintain.
So my quest... | Given the nature of how SQL works, this is exactly what you need to do. If you tell it:
```
update table_name
set field_one = 'one';
```
that means something entirely different in SQL than
```
update table_name
set field_one = 'one'
where field_one != 'one';
```
The database can only process what you tol... | I guess there isn't an easier way.... | Avoid redundant updates | [
"",
"sql",
"oracle",
"plsql",
""
] |
```
CUSTOMER(ID,NAME,ENTRY_DT)
1,Dave,8312012
2,Tom,11262013
3,Iva,3312012
.
.
.
```
So the ENTRY\_DT column has numeric string value in MDDYYYY or MMDDYYYY format.
I want to write a simple select query so that ENTRY\_DT shows
```
8/31/2012
11/26/2013
3/31/2012
.... | ```
DECLARE @TABLE TABLE (Int_Date INT)
INSERT INTO @TABLE VALUES
(8312012),
(11262013),
(3312012)
SELECT LEFT(RIGHT('00000000'+ CAST(Int_Date AS VARCHAR(10)), 8), 2) +'/'
+REVERSE(SUBSTRING(REVERSE(Int_Date), 5, 2)) + '/' + RIGHT(Int_Date, 4)
FROM @TABLE
```
## Result
```
08/31/2012
11/26/2013
03/31/20... | ```
Select covert(date,right(('00000000' + entry_dt),8),101)
```
--- if it is SQL server 2008 or above
Replace date with date time if it is 2005 or below. | How to select numeric string as a valid DATE | [
"",
"sql",
"sql-server",
"date",
"select",
"case",
""
] |
I'm trying to read a column from a database using a SQL query. The column consists of empty string or numbers as strings, such as
```
"7500" "4460" "" "2900" "2640" "1850" "" "2570" "9050" "8000" "9600"
```
I'm trying to find the right sql query to extract all the numbers (as integers) and removing the empty ones, bu... | If all columns are valid integers, you could use:
```
select * , cast(code as int) IntCode
from base
where code <> ''
```
To prevent cases when field `code` is not a valid number, use:
```
select *, cast(codeN as int) IntCode
from base
cross apply (select case when code <> '' and not code like '%[^0-9]%' then code ... | Using sqldf with the default sqlite database and this test data:
```
DF <- data.frame(a = c("7500", "4460", "", "2900", "2640", "1850", "", "2570",
"9050", "8000", "9600"), stringsAsFactors = FALSE)
```
try this:
```
library(sqldf)
sqldf("select cast(a as aint) as aint from DF where length(... | SQL query: convert | [
"",
"sql",
"sql-server",
"r",
"postgresql",
"sqldf",
""
] |
I have been working on SQL Server for a long time and recently I was moved to a project which uses Oracle.
While I have heard of the term `Cursor`, I have not encountered one in the SQL Server. So my questions are:
1. Why do you even bother declaring `Cursor` in SQL Server? (or under what circumstances do you actuall... | **Why do you even bother declaring Cursor in SQL Server? (or under what circumstances do you actually need a cursor?)** Anytime you can't do set based processing record by record processing may be needed; then you would need to use a cursor. Set based logic is all or nothing when in the transaction. Perhaps I'm process... | `Cursor` returns the consistent data on the time of the cursor opening.
To show this I will open a cursor then I will change a row and I will compare the results of the database and the cursor:
```
SQL> conn hr/hr
Connected.
SQL> select employee_id, email from employees;
EMPLOYEE_ID EMAIL ... | Why do you use Cursor in SQL Server? | [
"",
"sql",
"sql-server",
"oracle",
""
] |
I have a database with a list of old ItemID's that need updating to a new format.
The old format is of the form 8046Y and the new format moves the 4th digit to the end and prepends a hyphen and adds a 0 if it's a single digit. The old format also uses alpha characters when the number goes over 9 for example 464HB wher... | Try this:
```
select
'1'
+ left(@str,3)
+ right(@str,1)
+ '-'
+ case
when substring(@str,4,1) like '%[0-9]%' 1 then right('00' + substring(@str,4,1),2)
else cast(10 + ascii(substring(@str,4,1))-ascii('A') as varchar(2))
end
```
Explanation: If the 4th character is a digit, then do not change the ... | ```
select '1' + LEFT(ItemID, 3) + RIGHT(ItemID,1) + '-'
+CASE RIGHT(LEFT(ItemID,1),2)
WHEN 'a' then 10
WHEN 'b' THEN 11
etc...
END [NewItemID]
from items
```
Just add the appropriate cases in that format. | SQL String Manipulation and character replacement | [
"",
"sql",
"sql-server",
""
] |
Is there a query which drops / deletes databases with no tables in them (deletes empty databases)?
Server is Microsoft SQL Server 2005 | This should do it.
Tested on a lab machine and it dropped all databases with 0 user tables.
Note, however, that tables aren't the only things in a database, necessarily. There could be stored procedures, functions, etc that someone might still need.
NOTE THAT THIS IS A VERY DANGEROUS OPERATION, AS IT DROPS DATABASES. ... | I think it is not possible (at least not with a TSQL command, might be a stored procedure somewhere). You would have to query `sysobjects` and abort if any found. (And you have to decide if you want to ignore some of the system objects like the design tables). | Drop databases with no tables | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I need some help to complete a query in SQL-Oracle. I trying to have it select the row(s) or security/ies with the highest or max gain from price1 to price2. here is what i have already. When I try to use sub queries in the select or where clauses, fails....and also i cannot use queries that are hard-quoted because the... | There are several ways of doing this. Here is one way:
```
select m.*
from (select security, price1, price2, ((price2 - price1)/price1)*100 as Percentage,
dense_rank() over (order by ((price2 - price1)/price1)*100 desc) as ranking
from market
) m
where ranking = 1;
``` | Here is another alternative.
```
select * from
(select security, price1, price2, ((price2 - price1)/price1)*100 as Percentage
from market
order by ((price2 - price1)/price1)*100 desc
)
where rownum = 1
;
``` | SQL - Oracle - how to select securities from table with top change % | [
"",
"sql",
"oracle",
"stocks",
""
] |
I am using SQL Server 2012 & MATLAB. I have a table of 5 columns (1 char, 1 datetime and 3 floats). I have a simple query shown below that returns the data from this table which contains over a million records - this however causes an out of memory error in MATLAB.
**simple query**
```
select id_co, date_r, FAM_Scor... | Simply use a sub query or [Common Table Expression](http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx) (CTE).
```
;WITH CTE AS
(
--Your query
)
SELECT * FROM CTE
WHERE num_co BETWEEN 250000 AND 500000
``` | You could try using the OFFSET x ROWS FETCH NEXT y ROWS ONLY commands like this:
```
CREATE TABLE TempTable (
TempID INT IDENTITY(1,1) NOT NULL,
SomeDescription VARCHAR(255) NOT NULL,
PRIMARY KEY(TempID))
INSERT INTO TempTable (SomeDescription)
VALUES ('Description 1'),
('Description 2'),
('Descr... | using row_number to return specific rows of query | [
"",
"sql",
"sql-server",
""
] |
I am very new in sql, then i am so confused how to get join or get value from two.
First table:
```
ID P_ID Name AGE U_ID
1 5 B 8 5w
2 8 D 17 6j
3 7 R 67 0qw
```
Second Table:
```
ID P_ID Address Edu
1 6 Bddd +2
2 7 Dssss Bachelor
3 2 ... | Join on the column that both tables have in common.
```
select t1.age, t2.address, t2.edu
from table1 t1
join table2 t2 on t1.p_id = t2.p_id
where t1.u_id = '0qw'
```
Then use the table names or alias names (like `t1` for `table1`) to pick columns from the tables you join. | I think you are looking forward to this:
```
SELECT t2.Address, t2.Edu, t1.Age
FROM firstTable t1
JOIN secondTable t2
ON t1.P_ID = t2.P_ID
WHERE t1.U_ID = '0qw'
``` | How to get value from two table if id is same in sql | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have two tables in two different databases.
My first table is an older version and has fewer columns than the second table.
I want to copy the contents of my old table to my new table.
In each database table there are several distribution in this case.
How can I do to quickly copy data from old tables to the new ... | The following code should do the work.
Basically what it does is:
*1. Collects column names from both tables.
2. Intersects the column names in order to filter out columns that exists only in 1 table.
3. Get a string which is the column names delimited by a comma.
4. Using the string from stage #3 creating the i... | You can "avoid writing the column names manually" in SSMS by dragging and dropping the "Columns" folder under the table in the Object Explorer over to a query window (just hold the dragged item over whitespace or the character position where you want the names to appear). All the column names will be displayed separate... | SQL Server : query to insert data into table from another table with different struct | [
"",
"sql",
"sql-server",
""
] |
there are so many questions here on this subject (see [here](https://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column) or [here](https://stackoverflow.com/questions/24842959/mysql-performance-query) for examples), but I cannot figure out how to correctly run my particular case.
Here ... | Here's a `JOIN` that's equivalent to your first query. You need to take `is_group_production = 0` out of the subquery, and only do it in the main query. This filters out rows where the max version is a group production.
```
SELECT d.id_document id_doc, d.version, d.id_plant_mov,
d.id_production_type id_prod_type,... | A derived table is the way to go here. Your problem in the second example was that you were getting max(version) for every row returned, including differences in is\_group\_production - this is where the extra rows crept in. So the where clause needs to stay in the outer query for that reason. Theoretically you could m... | MySQL select max value without subquery | [
"",
"mysql",
"sql",
"performance",
"greatest-n-per-group",
""
] |
I would just like to copy a specific `LOAD_NO` from a table called `LOADS` and insert it back into the same `LOADS` table but without using the old `LOAD_NO` (aka `ID`)....
The tables name is `LOADS`.
1. I would like to copy a specific row and insert it into the table but without needing to specify all of the fields ... | Since `LOAD_NO` is an **identity** column, you should not be specifying a value for it when inserting. So you need to modify our `INSERT` statement to **not** include the `LOAD_NO` column - something like this:
```
INSERT INTO LOADS(col1, col2, ..., colN) -- all columns *EXCEPT* LOAD_NO
SELECT col1, col2, ...., co... | Try this:
```
set identity_insert LOADS ON
Update LOADS set Load_No = (select max(load_no) + 1 from loads) where load_no = 200
set identity_insert LOADS OFF
```
You probably also want to wrap that in a transaction. | SQL Server : copy row and Insert into to the same table but with a different ID | [
"",
"sql",
"sql-server",
""
] |
I have a list of data that looks like this:
```
Name Date Weight
Person 1 01/01/2014 89KG
Person 2 01/01/2014 62KG
Person 1 07/01/2014 88KG
Person 2 07/01/2014 62KG
Person 1 21/01/2014 85KG
Person 2 21/01/2014 63KG
```
What I would like to do is... | Please see if this works for you.
**Sample Data:**
```
IF OBJECT_ID(N'tempdb..#TEMP') > 0
BEGIN
DROP TABLE #TEMP
END
CREATE TABLE #TEMP(Name VARCHAR(20),
WDate VARCHAR(20),
Weight VARCHAR(20))
INSERT INTO #TEMP
VALUES
('Person 1', '01/01/2014', '89KG'),
('Person 2', '01... | Please try using `DENSE_RANK`:
```
select
*
From (
select
*,
DENSE_RANK() over(PARTITION BY YEAR([Date]),
MONTH([Date])
ORDER BY [Date] desc) Rnk
From tbl
)x where Rnk=1
``` | Select 1 Distinct Record per month by latest date | [
"",
"sql",
"sql-server",
""
] |
I'd like to check the status of the agent after I start it using this statement
```
EXEC sp_startpublication_snapshot @publication
```
As I want to do a next step that needs the job to be already started. | After some research I got a work around way
```
SELECT snapshot_ready FROM sysmergepublications
```
This query returns 0 if not ready and 1 if started
Thanks all for your contribution :) | I do not believe there is a built-in replication stored procedure to check the snapshot agent status, I could be wrong. However, you could query MSsnapshot\_history. Something like this should do the trick:
```
SELECT
agent_id,
runstatus,
start_time,
time,
duration,
comments,
deliver... | How to check replication snapshot agent status? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"database-replication",
"merge-replication",
""
] |
I have 3 different tables as shown below:
```
| DataEntry: | | OOW: | | ContractExpired: |
| +----+-----------------------| | +----+-------------| | +----+-------------|
| Country | valid | invalid | | Country | Warranty | | Country | Expired |
| AU | 1 | 2 ... | If you really want to do this without JOINs, you can, and it is quite simple. You have to use SUBSELECTs, and filter them with a WHERE clause:
```
SELECT de.Country
SUM(CASE WHEN de.CallType = 'valid' THEN 1 ELSE Null END) AS [valid],
SUM(CASE WHEN de.CallType = 'Invalid' THEN 1 ELSE Null END) AS [Invalid],
(S... | shouldn't your query be something like below. This may not be the exact query but will give you an idea as what to be done to get it working.
```
SELECT de.Country,
SUM(CASE WHEN de.CallType = 'valid' THEN 1 ELSE Null END) AS [valid],
SUM(CASE WHEN de.CallType = 'Invalid' THEN 1 ELSE Null END) AS [Invalid],
FROM DataE... | Combine 3 tables without using join but need group by | [
"",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.