Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I don't know if the title makes any sense, but here is the situation: See 2 tables below
**People:** (BTW, if it helps to know, this table will never have >1000 rows)
```
+----+---------+-------------------+---------+
| id | name | address | city_id |
+----+---------+-------------------+---------+
| 1 |... | You can try below query-
```
SELECT p2.*
FROM people p
JOIN cities c ON p.city_id=c.id
JOIN cities c2 ON c.state=c2.state
JOIN people p2 ON p2.city_id=c2.id
WHERE p.id=<my input>;
```
Note: For performance id and city\_id in people table and id and state in cities table should be indexed.
Also for more optimiza... | You might try this.
```
select * from people
where city_id in(
select city from cities c
inner join(
select c.state from people p
left join cities c on c.city = p.city_id
where p.id = '1'
) s on s.state = c.state
)
``` | SQL select addresses from a state in single query from 2 tables | [
"",
"mysql",
"sql",
"performance",
"join",
""
] |
I have a database with several tables.
```
Film (filmID, title, filmCatagory)
FilmCast (filmID, filmStarID, filmStarName)
FilmStar (filmStarID, filmStarName, birthplace).
```
The Film entity states all information about the films, FilmCast links the two tables together as a way to show which film star stars in what p... | You could use a SELECT query with EXISTS:
```
SELECT
filmStarID,
filmStarName,
birthplace
FROM
FilmStar
WHERE
EXISTS (
SELECT *
FROM
Film INNER JOIN FilmCast
ON Film.FilmID = FilmCast.FilmID
WHERE
Film.filmCatagory='Comedy'
AND FilmCast.filmStarID = FilmStar.filmStarID
)... | Find all of the film stars who have appeared in comedies and then GROUP BY.
```
SELECT s.filmStarID, s.filmStarName, COUNT(*)
FROM FilmStar s
INNER JOIN FilmCast c ON c.filmStarID = s.filmStarID
INNER JOIN Film f ON f.filmID = c.filmID
WHERE f.filmCategory = 'Comedy'
GROUP BY s.filmStarID, s.filmStarName
``` | Unique numbers & names of stars that have appeared in at least one comedy | [
"",
"sql",
"database",
"oracle",
"performance",
"relational-database",
""
] |
```
SELECT
Lname + ' ' + Ename as Name,
DateOfBirth,
DATEDIFF(hour,dateOfBirth,GETDATE())/8766 AS Age
FROM EmpTBL
WHERE
DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DateOfBirth), DateOfBirth)
BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30);
```
The above... | change your query to
```
select CONVERT(VARCHAR(10),dateOfBirth,101) FROM EmpTBL WHERE <>
``` | When we fetch date from database to asp.net it's in Date-Time format not in Date so you can convert it to custom date as you want:
```
<%# Convert.ToDateTime(Eval("DateOfBirth")).ToString("yyyy/MM/dd")%>
```
You can use any [Format specifier](http://www.mikesdotnetting.com/article/23/date-formatting-in-c)/[Custom Dat... | SQL Select Query returning DATE without TIME inside SQL but i when i run my ASP project it keeps adding "12:00:00 AM" | [
"",
"sql",
"asp.net",
""
] |
I'm having some issues to complete a SQL statement in SQL Server 2008.
My 'query1' is the following:
```
SELECT [Vc_MONTH],
[Vc_STATE],
[Vc_PRODUCT],
SUM ([TOTAL]) as Total_Units,
SUM ([OPEN]) as Open_Units
FROM [test].[dbo].[Tbl_Summary]
GROUP BY [Vc_MONTH],
[Vc_REGION],
... | so you already have query 1:
```
SELECT [Vc_MONTH],
[Vc_STATE],
[Vc_PRODUCT],
SUM ([TOTAL]) as Total_Units,
SUM ([OPEN]) as Open_Units
FROM [test].[dbo].[Tbl_Summary]
GROUP BY [Vc_MONTH],
[Vc_STATE],
[Vc_PRODUCT]
```
next you need to GROUP BY Month and Product correct? However, you need to speci... | I think you should just use `grouping sets`. Much simpler query and no `union`:
```
SELECT (CASE WHEN GROUPING([Vc_MONTH]) = 1 THEN 'ALL' ELSE [Vc_MONTH] END) as [Vc_MONTH],
[Vc_STATE], [Vc_PRODUCT],
SUM ([TOTAL]) as Total_Units,
SUM ([OPEN]) as Open_Units
FROM [test].[dbo].[Tbl_Summary]
GROUP BY ... | Select and group by - calculated field | [
"",
"sql",
"sql-server",
""
] |
**Table**: `l_test1`
```
CREATE TABLE l_test1
(
Cola VARCHAR(10)
);
```
**Table**: `l_test2`
```
CREATE TABLE l_test2
(
Cola VARCHAR(20)
);
```
**Insertion**:
```
INSERT INTO l_test1 VALUES('1');
INSERT INTO l_test1 VALUES('12');
INSERT INTO l_test1 VALUES('123');
INSERT INTO l_test1 VALUES('1234');
INSER... | Use the `STUFF`:
**[LiveDemo](https://data.stackexchange.com/stackoverflow/query/372926)**
```
WITH cte1 AS
(
SELECT t2.Cola, MAX(t1.Cola) AS r
FROM #l_test2 t2
JOIN #l_test1 t1
ON t2.Cola LIKE t1.Cola + '%'
GROUP BY t2.Cola
),
cte2 AS
(
SELECT t2.Cola, MAX(t1.Cola) AS r
FROM #l_test2 t2... | You can use the following query that employs [**`PATINDEX`**](https://msdn.microsoft.com/en-us/library/ms188395.aspx):
```
SELECT DISTINCT
Cola,
SUBSTRING(Cola, left_index + 1, right_index - left_index - 1) AS sanitized_Cola
FROM (
SELECT MAX(CASE WHEN t3.left_match = 1 THEN LEN(t1.Cola) ELSE 0 END)... | SQL Server 2008 R2: Update table values which matched with another table | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I am fetching records from two different databases and keeping them in two separate files suppose `File1.txt` and `File2.txt` .
I want to compare these two files as we do in case of sql minus operator.
Suppose if File1.txt contains data like
```
COL1|COL2|COL3
A1|A2|A3
B1|B2|B3
```
and File2.txt contains data like
... | Try to use `grep` like this:
```
grep -F -x -v -f file2 file1
```
Note that:
```
-F FILE takes patterns from FILE
-x match whole line
-v show non-matching
``` | This is what `comm` is for
```
comm -23 file1 file2 # b...
comm -13 file1 file2 # c...
```
Check your `comm` man page
The input needs to be sorted. The final answer might be a little more complicated. | Is there any utility in unix like minus operator in sql | [
"",
"sql",
"shell",
"unix",
""
] |
In oracle...How can I know my table 'A' is belongs to which user ! | This query it's work with me
```
select table_name,owner from all_tables where table_name like '%CONTINENT%'
``` | ```
SELECT *
FROM All_Objects
WHERE object_name = 'Your_table'
AND object_type = 'TABLE';
```
you could also query all\_tables
```
SELECT *
FROM all_tables
WHERE Table_name = 'Your_table'
```
[All tables](http://docs.oracle.com/cd/B28359_01/server.111/b28320/statviews_2105.htm) shows the tables accessible to your ... | Table belongs to which user | [
"",
"sql",
"database",
"oracle",
""
] |
This feels like a stupid question since it should have a simple answer, but I just can't find it. I have a table looking like this:
```
|-----|---|
| a | b |
|-----|---|
| ALA | 2 |
| ASP | 1 |
| SER | 1 |
| VAL | 2 |
|-----|---|
```
What I need is to get the two rows with the maximum value (I don't know the values... | ```
SELECT a,b FROM table
WHERE b = (SELECT MAX(b) FROM table)
``` | If you use SQL Server, you can use `TOP WITH TIES`, which should be more efficient than subquery or `RANK`.
```
SELECT TOP(1) WITH TIES
a, b
FROM YourTable
ORDER BY b DESC;
```
Other databases may also have similar option. | SQL max() only returns 1 row if column has several max values | [
"",
"mysql",
"sql",
"max",
""
] |
I have an Access Form that contains a ListBox that gets data from the following query:
```
SELECT tblFUNDS.MorningsStar_Fund_Name, tblFUNDS.ISIN, tblFUNDS.RDR AS [Retro Frei],
tblMorningstar_Data.[DEU Tax Transparence], tblMorningstar_Data.[Distribution Status],
tblISIN_Country_Table.Country
FROM
(tblFUNDS INNER J... | Like in comment, try:
```
SELECT tblFUNDS.MorningsStar_Fund_Name, tblFUNDS.ISIN, tblFUNDS.RDR AS [Retro Frei], tblMorningstar_Data.[DEU Tax Transparence], tblMorningstar_Data.[Distribution Status], tblISIN_Country_Table.Country
FROM (tblFUNDS INNER JOIN tblISIN_Country_Table ON tblFUNDS.ISIN = tblISIN_Country_Table.I... | Glad to hear you've solved your problem. To elaborate my comment I will place the code to change the controlsource of the listbox here anyway. Maybe someone else will find it useful one day. Any comments are also welcomed.
```
Public Function Rapport_query()
Dim sqlTax As String
Dim sqlRDR As String
Dim sql As String
... | SQL Query ignores controls that it refrences | [
"",
"sql",
"ms-access",
"ms-access-2010",
""
] |
Can someone tell me how to use the output of a `CASE` statement as input in the next `CASE` statement in t-SQL?
**exampleTable**
```
id | itemNo | samplesLeft
-------------------------
1 | 001 | 104
2 | 003 | 53
3 | 002 | 193
4 | 001 | 32
```
I would like a query which retur... | You can do this with a sub query like,
```
select
x.*,
case
when samplesUsed < 10 then 'Error'
else 'right'
end as status
from (
select
t.*,
CASE
WHEN itemNo = 001 THEN 200 - samplesLeft
WHEN itemNo = 002 THEN 300 - samplesLeft
W... | you can use this:
```
SELECT id ,
itemNo ,
samplesLeft ,
CASE WHEN ( CASE WHEN itemNo = '001' THEN 200 - samplesLeft
WHEN itemNo = '002' THEN 300 - samplesLeft
WHEN itemNo = '003' THEN 400 - samplesLeft
ELSE 100 - sampl... | Using output from CASE in a new CASE (SQL) | [
"",
"sql",
"t-sql",
"case",
""
] |
I'm working with a MySQL database, trying to grab statistics on the number of users *in a department* who have completed a certain task within a timeline.
My problem is this: certain users are doing tasks multiple times. I was able to construct a query which returns the number of done tasks and total users per group, ... | I think this can be achieved by replacing the "count(\*)" in the 3rd line with "count(distinct a.id)"
This way, if the same agent id exists more than once, it will be counted only once.
So the query would look like this:
```
SELECT total.department, total_count, IFNULL(done, 0) as done_count, ROUND((IFNULL(done, 0) ... | To calculate the number of agents per department in the same query as the number who have completed a task, you could use a sub-query in the select list, but this will not perform as well. Instead I recommend the following, which is more complex but will perform optimally:
```
SELECT d.department, count(*) as dept_co... | MySQL return first row related to a given id | [
"",
"mysql",
"sql",
""
] |
Here is a sample of what I have in my table (SQL Server):
```
Start End
2014-08-31 2014-09-01
2014-09-09 2014-09-11
2014-09-11 2014-09-26
2014-09-15 2014-09-23
2014-09-16 2014-09-22
2014-09-17 2014-09-19
2014-09-17 2014-09-26
2014-09-17 2014-10-03
2014-09-17 2014-09-26
2014-09-17 2014-09-18
2... | I just want to share my resolution.
```
tb_LeaveRequest
id StartDate EndDate
1 09/17/2014 09/18/2014
2 09/18/2014 10/04/2014
3 09/17/2014 10/03/2014
4 09/17/2014 09/26/2014
5 09/18/2014 09/19/2014
6 09/25/2014 09/25/2014
7 09/26/2014 09/26/2014
8 09/19/2014 09/20/2014
9 09/25/2014 09/25/2... | Using `LEFT JOIN`:
[**SQL Fiddle**](http://sqlfiddle.com/#!6/3c800/1/0)
```
SELECT
l.dt, COUNT(t.Start) AS cnt
FROM Leave l
LEFT JOIN tbl t
ON dt BETWEEN Start AND [End]
GROUP BY l.dt
```
Using `OUTER APPLY`:
[**SQL Fiddle**](http://sqlfiddle.com/#!6/3c800/2/0)
```
SELECT
l.dt, a.cnt
FROM Leave l
OUTER... | Sql server Count Days within Date Range | [
"",
"sql",
"sql-server",
""
] |
I am sorry if this duplicate question. Please let me know where I can find right question. I have a stored procedure where I can just make few minor modifications and I cannot change/update data in my Student table. We have this problem and I need to fix it.
In below statement, sometimes student.FullName will have [NE... | You don't need to see if it contains the string. If it does not, `REPLACE` will just return the original string:
```
CASE
WHEN student.ID IS NULL THEN
CASE
WHEN student.Status = 0 THEN
'<BOLDSTART>rejected<BOLDEND>.'+'[LINEBREAK]'+ REPLACE(student.FullName,'[NEXTLINE]','') ... | Is this what you want?
replace
```
+ student.FullName
```
for
```
+ CASE
WHEN student.FullName LIKE '%[NEXTLINE]%' THEN REPLACE (student.FullName,'[NEXTLINE]','')
ELSE student.FullName
END
``` | SQL : IF ELSE with THEN of SELECT CASE | [
"",
"sql",
"sql-server-2008",
""
] |
I have a static dataset that correlates a range of numbers to some metadata, e.g.
```
+--------+--------+-------+--------+----------------+
| Min | Max |Country|CardType| Issuing Bank |
+--------+--------+-------+--------+----------------+
| 400011 | 400051 | USA |VISA | Bank of America|
+--------+-------... | If you *usually* search on both `min` and `max` then a compound key on `(min,max)` is appropriate. The engine will find all rows where `min` is less than X, then search within those result to find the rows where `max` is greater then `Y`.
The index would also be useful if you do searches on `min` only, but would not b... | You can index the first number and then do the lookup like this:
```
select t.*,
(select top 1 s.country
from static s
where t.num >= s.firstnum
order by s.firstnum
) country
from sometable t;
```
Or use `outer apply`:
```
select t.*, s.country
from sometable t outer apply
... | SQL Server Primary Key for a range lookup | [
"",
"sql",
"sql-server",
""
] |
I have 2 tables as follow:
```
1)passenger - with passenger_id,passenger_name and passenger_city
2)flight - with flight_id,flight_name and passenger_id.
```
The question is:
List the passenger details with flight id, who has travelled in more than one flight.
(This function will display the passenger details with th... | Join the flight table to get the passenger's flights
```
select * from passenger_1038299 p
join flight_1038299 f on f.passenger_id = p.passenger_id
where p.passengerid in(
select passengerid from flight_1038299 group by passengerid having count(passengerid)>1
);
```
I like to use `exists` to check for multiples. ... | Another way with using analytic functions:
```
SELECT * FROM (
SELECT p.*, f.flight_id,
count(*) OVER (PARTITION BY f.passenger_id ) As number_of_flights
FROM passenger p
JOIN flight f
ON p.passenger_id = f.passenger_id
)
WHERE number_of_flights > 1
```
Demo: <http://sqlfiddle.com/#!4/dab21... | sql query- group by and then join | [
"",
"sql",
"oracle",
"join",
"group-by",
""
] |
My table looks like this:
```
CREATE TABLE MyTable(
Info varchar(50) null,
Col1 int null,
Col2 int null,
Col3 int null,
Col4 int null,
Col5 int null
);
```
Is there a way? | Without using \* you can use `ABS`:
```
SELECT Info, ABS(Col1) as Col1...
FROM MyTable
``` | You can't manipulate individual fields when you're querying `*`, you'd have to handle each field individually and apply [`abs`](https://msdn.microsoft.com/en-us/library/ms189800.aspx) to it:
```
SELECT info, ABS(col1), ABS(col2), ABS(col3), ABS(col4), ABS(col5)
FROM mytable
``` | Select asterisk from table but if the value is negative turn into positive | [
"",
"sql",
"sql-server",
"select",
""
] |
Case: A table has a field with some XML code.
```
-- Some XML
'<DTS:ConnectionManager DTS:refId="Package.ConnectionManagers[MTS]" DTS:CreationName="FLATFILE" DTS:DTSID="{296732CC-7D91-4E49-ACD4-384E03BC032E}" DTS:ObjectName="MTS">
<DTS:PropertyExpression DTS:Name="ConnectionString">@Something</DTS:PropertyExpressi... | You are not declaring your namespace in your root element so I substituted that. This should be self extracting and run in anything I am guessing 2008 and higher, though I wrote it in 2014. Just pop it into SQL Server Management Studio:
UPDATED 1:45 PM PST:
Thanks to Shnugo for the simplification of the 'With XMLName... | This is an enhancment to the answer of djangojazz. Don't accept this, it's just a copy (but you may vote up, if you like it ;-) ...
By using WITH XMLNAMESPACES you can avoid the multiple declaration of the namespace:
```
WITH XMLNAMESPACES (N'http://DTS' as DTS )
SELECT
x.vals.query('.') AS NodesAsExtracted
, ... | T-SQL - XML to SQL Server Table | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
"sql-server-2012",
""
] |
I am not sure, which method is better?
```
con.createStatement().execute("...");
```
OR
```
Statement st = con.createStatement();
st.execute("...");
st.close();
```
When using the first method, will be the statement create closed or it will remain open? I am sure that in the second method the statement will be clos... | Both `con.createStatement().execute("...");` and `Statement st = con.createStatement();` make same sense. However closing the statement is not performed with the first method. Closing the `ResultSet` or `Statement` is a good practice. You may get additional problems with not closed `Statements`. You can close the `Conn... | Neither is good, although the second alternative is better than the first. You should always close a statement when you are done with (not sooner, but definitely not never). Your second alternative attempts to close the statement, but will actually fail to do that if `execute` throws an exception.
To have a guaranteed... | Java closing Statement | [
"",
"sql",
"jdbc",
"execute",
""
] |
I have following table:
```
TableA
x y
----------------------
3 1
2 5
5 2
```
Now i want to update the value in column x, where the value in column y is lowest, something like that:
```
UPDATE TableA SET x = 1 WHERE y = min(y);
```
Then the firs... | If `y` is unique, then you can use `order by` and `limit`:
```
UPDATE TableA
SET x = 1
ORDER BY Y ASC
LIMIT 1;
```
If you have multiple rows with the minimum value, you can use `join`:
```
UPDATE TableA a JOIN
(SELECT MIN(Y) as miny FROM TableA) m
ON a.y = m.miny
SET x = 1;
``` | you can write your query as follow:
```
UPDATE TableA SET x = 1 WHERE y IN (select min(y) from TableA T2);
``` | MySQL - Update X where Y is lowest | [
"",
"mysql",
"sql",
"database",
""
] |
I want to show a list of chat messages.
For this I have a `SELECT` statement:
```
SELECT id, `from`, sent, message, recd FROM chat
WHERE id IN(
SELECT MAX(id) FROM chat
WHERE `to` = ? GROUP BY `from`
)
ORDER BY id DESC
```
The problem is, I want to select messages that `to` = maria and `from` = maria conditiona... | I think all the proposed queries are fine - meaning they will return the expected results (one row for every different user that has sent or received a message from `'maria'`) - but efficiency may not be great. MySQL does not optimize well queries with `WHERE column IN (complex subquery)`. The optimizer has some improv... | I would got for a UNION.
```
(SELECT id, 'from' as direction, m_from AS fromto, sent, message, recd
FROM chat WHERE id IN (SELECT MAX(id) FROM chat WHERE to = 'Maria' GROUP BY m_from))
UNION
(SELECT id, 'to' as direction, m_to AS fromto, sent, message, recd FROM chat
WHERE id IN (SELECT MAX(id) FROM chat WHERE m_from ... | GROUP BY different column conditionally | [
"",
"mysql",
"sql",
""
] |
I have two tables:
```
Cust Sales Week
123 4 1/8/2015
123 3 1/22/2015
234 4 1/1/2015
```
.
```
Week
1/1/2015
1/8/2015
1/15/2015
1/22/2015
```
I want to combine them so that every Cust has every date and where there are no Sales it is filled with 0.
```
Cust Sales Week
123 ... | First, generate the rows you want using a `cross join`. Then bring in the data you want using a `left join`:
```
select c.cust, w.week, coalesce(t.sales, 0) as sales
from weeks w cross join
(select distinct cust from t) c left join
t
on t.cust = c.cust and t.week = w.week;
``` | You can `left join` on the dates table and use `isnull` on the sales column. Use an equivalent of `isnull` in Netezza.
```
select t1.cust, isnull(t1.sales,0), t2.week
from daystable2 t2 left join salestable1 t1 on t1.week = t2.week
``` | Zero Fill Data for Missing Dates | [
"",
"sql",
"netezza",
""
] |
Here's my table:
```
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| CLID | int(11) | NO | MUL | NULL | |
| calldate | datetime | YES | MUL | NULL | |
| s... | 1.45 seconds to update a single record is very bad performance, and highly unexpected. Your query is intending to update a single row using a primary key. You shouldn't notice the amount of time.
However, the engine cannot use the primary key index for this query, because of the way the condition is expressed. Let's l... | Edit: Before doing what I suggest I would definitely give Gordon Linoff's solution a try as it makes a lot of sense (missing quotes around the value passed on the where clause).
Is your MySQL database is distant from your PHP server? That could explain poor performances.
If you are having better performances when doi... | Speeding up a simple UPDATE query on a huge table | [
"",
"mysql",
"sql",
"optimization",
"query-optimization",
""
] |
Let's say I have 2 tables like this :
**Job Offers:**
```
+----+------------+------------+
| ID | Name | Categories |
+----+------------+------------+
| 1 | Programmer | 1,2 |
| 2 | Analyst | 3 |
+----+------------+------------+
```
**Categories:**
```
+----+-----------------+
| ID | ... | You can greatly simplify this to something like this.
```
SELECT
O.[ID] AS OfferID,
O.[Name] AS OfferName,
c.[CategoryName] AS CategoryName,
c.[CategoryID] AS CategoryID
FROM
JobOffers AS O
outer apply [dbo].[Split](O.[Categories], ',') s
left join Catego... | From SQL SERVER 2016 we can use sql inbuilt function STRING\_SPLIT
as below :
```
SELECT * FROM JobOffers as j
outer apply STRING_SPLIT(j.[Categories], ',') s
left join dbo.Categories as c on c.CategoryID =s.value
``` | String split column and join to another table | [
"",
"sql",
"sql-server",
""
] |
I have two table in sql. First one the patient list, second one is their report. all patient's reports are in the report, just with id we can join them. Each patient has some reports (Maybe all the fields of a record is not filled). Now I want to make a report that get the last report of each patient but if some field ... | this is a sample,
in your case you have to get the value of each column in a subquery (either in the join statement, or in the main select statement
example:
```
inner join (
select distinct bartar_patientname
,(select top 1 bartar_pastePerMonth from [Bartar_MSCRM].[dbo].[Filteredbartar_callcen... | Your script is fine as it looks, so I'll just place that on a temporary table for now, and do a per sequence query and filter it by "OR" afterwards.
Please try the script below.
```
SELECT patient.bartar_id,patient.bartar_enteringthesystem,patient.bartar_proviencename,
patient.bartar_cityname,patient.b... | Sql query with join and group by and | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have written a query that gives me a list of data and I need to select the top 5 pieces of data. For example
```
Num Name
5 a
4 b
4 c
2 d
1 e
1 f
1 g
0 h
```
However if I simply use LIMIT 5, this leaves out data points with name f and g. How would I be able to select from a-h. This is just ... | I think you need a query like this:
```
SELECT *
FROM (
SELECT t1.Num, t1.Name, COUNT(DISTINCT t2.Num) AS seq
FROM yourTable t1
LEFT JOIN
yourTable t2
ON t1.Num <= t2.Num
GROUP BY t1.Num, t1.Name) dt
WHERE (seq <= 5);
```
[[SQL Fiddle Demo]](http://www.sqlfiddle.com/#!9/eba96/1) | You can calculate via adding a new field with an incremental row number within your SQL logic as following:
```
Feeds Num Name
1 5 a
2 4 b
2 4 c
3 2 d
4 1 e
4 1 f
4 1 g
5 0 h
```
and then limit the result by the required rank (in your case 5). ... | Selecting the top 5 in a column with duplicates | [
"",
"mysql",
"sql",
""
] |
In a table I have column A and B. I want to update A using the value of B and then update B to a new value. This has to be done atomically.
I am trying something like this
```
-- Intially A = 1, B = 2
UPDATE T SET A = B, B = 10 WHERE ID = 1;
-- Now A = 2, B = 10
```
Though this is working, I am unable to find docume... | You can find this in SQL standard, which defines general rules.
Oracle certainly conforms to this standard.
See here - SQL 92:
<http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt>
Page 393, chapter "13.9 <update statement: positioned>", point 6)
> 6) **The <value expression>s are effectively evalu... | In a RDBMS (unlike a programming language) there's no order of evaluation, it's all done at once. It's like you set variables to the previous value first and then use those variables:
```
SET a=b, b=a
```
simply switches `a` and `b`.
Warning: Only MySQL does it totally wrong, resulting in both set to the same `b` va... | Order of evaluation of expression in the update-set-clause in oracle database | [
"",
"sql",
"oracle",
""
] |
I have a stored procedure that creates quite a few temp tables in memory. I have the following query which takes an extremely long time to run (7 minutes).
```
select
a.DEPT,
a.DIV,
a.PART,
convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'+ convert(varchar(4),datepart("yyyy",a.Release_Dat... | This is your query, with the unnecessary `select distinct` removed from the subquery:
```
select a.DEPT, a.DIV, a.PART,
convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'+ convert(varchar(4),datepart("yyyy",a.Release_Date)),101) as rptng_mnth
from @tmpReportData3 a
where not exists (select... | A good start would be to change the "not in" to a left join.
You might also consider using "#" (rather than "@") temp tables, because you can index #-tables.
Can you include the complete stored procedure?
```
select
a.DEPT
,a.DIV
,a.PART
,convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'... | Need Help Speeding Up a SQL Server Query | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I am using `SQL Server 2014`. I have a Table having Column `BookNo` as `datatype int`. This column contains below data
```
|BookNo|
1
2
3
4
5
10
12
13
25
26
27
28
```
I want to the Consecutive Numbers Range in Sql query. From above data my output should be like
```
1 to 5
10 to 13
25 to 28
```
Any Help... | I think you can use a query like this:
```
SELECT BookNo, ISNULL(LEAD(prev) OVER (ORDER BY BookNo) , (SELECT MAX(BookNo) FROM yourTable)) As toCon
FROM
(
SELECT *, LAG(BookNo) OVER (ORDER BY BookNo) prev, BookNo - LAG(BookNo) OVER (ORDER BY BookNo) diff
FROM yourTable) dt
WHERE
(ISNULL(diff, 0) <> 1);... | Another solution based on *Windowed Aggregate Functions* which also runs on versions below SS2014 (and should perform better than the `LAG`/`LEAD`):
```
SELECT MIN(BookNo) AS BookNoFrom, MAX(BookNo) AS BookNoTo
FROM
(
SELECT BookNo,
BookNo - ROW_NUMBER() OVER (ORDER BY BookNo) AS dummy
FROM yourTabl... | Get consecutive numbers Range from SQL Server Table | [
"",
"sql",
"sql-server",
""
] |
I have
* A list of Primary keys(around 10).
* A table has 100 rows.
Lets say among 10 keys which I have, if there are 8 keys found in the table.
I need the output of the remaining 2 keys which is not present in the table.
Eg: i have 10 empl id's which i need to query in Empl table.
Empl table has 100 or even more r... | To make the query a little shorter I give you an example for 3 keys you have to check in a table
```
select k.*
from
(
select 1 as pk
union all
select 3
union all
select 7
) k
left join your_table t on t.id = k.pk
where t.id is null
``` | ```
select * from table where my_key not in (select distinct my_key from the_other_table)
``` | Query which should return the non existing values in table | [
"",
"mysql",
"sql",
"database",
"oracle",
""
] |
Hi I have a dataset look like this
```
Brand Category
----------------------
A 1
A 1
A 1
B 1
B 1
C 1
A 2
C 2
C 2
C 2
```
and I want to get the market share for each brand in each category. Say, market share for A in category 1 is 3/6=50%.
I used the sql c... | You need to merge the category total counts back onto the brand\*category combinations. PROC SQL will do that for you automatically if you want.
```
data have ;
input Brand $ Category $ @@;
cards;
A 1 A 1 A 1 B 1 B 1 C 1 A 2 C 2 C 2 C 2
;
proc sql;
select brand
, category
, nobs
, sum(nobs) a... | ```
select count(category) from dataset group by category
```
This subquery returns more than 1 row. It returns the count for each category. But you want the count of a specific category, so replace it with
```
select count(category) from dataset where category = d.category
```
and make sure you give `dataset` an al... | Group by in Subquery SAS | [
"",
"sql",
"group-by",
"sas",
"subquery",
""
] |
I am trying to convert EPOCH to a HUMAN DATETIME.
* When I test this on their website, it returns the right value.
* When I do it within SQL Developer, it's wrong.
This lead me to check other basic SQL to see how they get returned,
```
select sysdate from dual = 12-OCT-2015
```
It's missing the time?
```
SELECT TO... | Your *epoch* includes milliseconds, you need to divide it by 1000:
```
SELECT TO_DATE('01/01/1970 00:00:00','DD/MM/YYYY HH24:MI:SS')
+(1325289600000/1000/60/60/24) AS EPOCH
FROM dual;
``` | Mask should be in TO\_CHAR function as well to output time.
```
SELECT TO_CHAR(TO_DATE('2015/05/15 8:30:25', 'YYYY/MM/DD HH:MI:SS'), 'YYYY/MM/DD HH:MI:SS')
FROM dual;
```
But it will be character string. If you want to do something with this date (add something and so on), you should put TO\_CHAR last (first do every... | Why wont TO_DATE return the TIME section of my query? | [
"",
"sql",
"oracle",
"epoch",
"to-date",
"to-char",
""
] |
I want to get previous Tuesday (or any given day of week) for specified date. Here is the sample input and expected output for Tuesday:
```
CREATE TABLE #temp(testdate DATETIME);
INSERT INTO #temp(testdate) VALUES
('2015-10-06 01:15'), -- Tue -> Tue 2015-10-06 00:00
('2015-10-07 04:30'), -- Wed -> Tue 2015-10... | i hope this will help you
```
SELECT DATEADD(day,- (DATEPART(dw, testdate) + @@DATEFIRST - 3) % 7,testdate) AS Saturday
from #temp
```
OR
```
SELECT DATENAME(weekday,DATEADD(day,- (DATEPART(dw, testdate) + @@DATEFIRST - 3) % 7,testdate)) +' '+
CONVERT(nvarchar,DATEADD(day,- (DATEPART(dw, testdate) + @@DA... | You can use get number of week by using `DATEPART` and then use `CASE` statement in following:
```
SELECT
testdate,
CASE DATEPART(dw,testdate) WHEN 1 THEN DATEADD(dd,-5,testdate)
WHEN 2 THEN DATEADD(dd,-6,testdate)
WHEN 3 THEN DATEADD(dd, 0,tes... | Get previous Tuesday (or any given day of week) for specified date | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"datetime",
""
] |
We have an hour table in our application which stores the working hours for each associate. It has hour values as follow
```
0.30 ,
0.30 ,
1.10
```
`0.30` indicates 30 minutes and 1.10 indicates 1 hour 10 minutes. So when I calculate the sum of hours I got 1.7, but I need to get 1.3 (I need to convert `1.10` to `0.7... | you can use some math calculation to achieve what you want ..
```
SELECT workHours - FLOOR(workHours) + FLOOR(workHours)*0.60
```
---
sample value:
```
SELECT 1.10 - FLOOR(1.10) + FLOOR(1.10)* 0.60
```
> result: 0.70 | A simple solution would be to store the time in minutes making arithmetic simple. Then in the presentation layer convert it to the desired format. | Add the time values in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to split a column from a result set into 2 columns based on the values from the column.
So a user can subscribe to multiple items and the user can have 2 email addresses which can receive this subscription.
The result set gives a list of subscriptions and their corresponding entries for subscribed email ids.... | ```
SELECT
S.subscription_id,
S.subscription_name,
CASE
WHEN US1.mail_ID IS NULL THEN 'N'
ELSE 'Y'
END mail_1,
CASE
WHEN US2.mail_ID IS NULL THEN 'N'
ELSE 'Y'
END mail_2
FROM subscriptions S
LEFT JOIN user_subscriptions US1
ON S.subscription_id = U... | You need a conditional aggregate:
```
select us.subscription_name,
-- there's at least one email
CASE WHEN MIN(us.email_id) IS NOT NULL THEN 'Y' ELSE 'N' END as email_1,
-- there's more than one email
CASE WHEN MIN(us.email_id) <> MAX(us.email_id) THEN 'Y' ELSE 'N' END as email_2
from subscriptions as ... | SQL - Splitting a column based on the values | [
"",
"sql",
"sybase",
""
] |
I have a table
```
User | Phone | Value
Peter | 0 | 1
Peter | 456 | 2
Peter | 456 | 3
Paul | 456 | 7
Paul | 789 | 10
```
I want to select `MAX` value for every user, than it also lower than a tresshold
For tresshold 8, I want result to be
```
Peter | 456 | 3
Paul | 456 | 7
```
I have tried the GROUP BY with HAVIN... | After I have results from "juergen d" solution, I came up with this which gives me the same results faster
```
SELECT DISTINCT ON(user) user, phone, value
FROM table
WHERE value < 8
ORDER BY user, value DESC;
``` | ```
select t1.*
from your_table t1
join
(
select user, max(value) as max_value
from your_table
where value < 8
group by user
) t2 on t1.user = t2.user and t1.value = t2.max_value
``` | PostgreSQL - MAX value for every user | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
I have a table called `MEDECIN` with 2 columns as follows :
```
SQL> DESC MEDECIN;
Name Null? Type
----------------------------------------- -------- ----------------------------
NUM_MED NOT NULL NUMBER(4)
SPECIALITE ... | Should work, unless the filter is failing to match any rows.
**Setup**
```
SQL> CREATE TABLE MEDECIN
2 (
3 NUM_MED NUMBER(4) NOT NULL,
4 SPECIALITE NVARCHAR2(13) NOT NULL
5 );
Table created.
SQL> INSERT INTO MEDECIN VALUES
2 (4, 'Orthopédiste'
3 );
1 row created.
SQL> COMMIT;
Co... | Since it is an nvarchar2 try to put a capital N in front of the string like so = N'Cardiologue'. | Why the WHERE clause in Oracle XE database doesn't work when comparing with a string? | [
"",
"sql",
"oracle",
"oracle11g",
"oracle-xe",
""
] |
I have written sql that creates 4 columns: `Tier0`, `Tier1`, `Tier2` and `Weight`.
Weight is associated with the tiers such that
> when Tier0 = 'X' then weight = 0,
> when Tier1 = 'X' then weight = 0.7, and
> when Tier2 = 'X' then weight = 1.
Right now my code for this portion of my SELECT statement is
```
CAS... | You could use a derived table:
```
SELECT Tier0,
Tier1,
Tier2,
CASE
WHEN Tier0 = 'X' THEN 0
WHEN Tier1 = 'X' THEN 0.7
WHEN Tier2 = 'X' THEN 1
END [Weight]
FROM (Your current query here) AS T;
```
Or a CTE:
```
;WITH CTE AS
(
Your current query... | What about this way?
```
CASE
WHEN (SUM(vst.len_of_stay) / COUNT(vst.len_of_stay)) > (SUM(drg.drg_std_days_stay) / COUNT(drg.drg_std_days_stay))
THEN 0
WHEN (SUM(vst.len_of_stay) / COUNT(vst.len_of_stay)) = (SUM(drg.drg_std_days_stay) / COUNT(drg.drg_std_days_stay))
THEN 0.7
WHEN (SUM(vst.len_of_stay) / CO... | Update Multiple Columns using single case statement | [
"",
"sql",
"sql-server",
"case",
""
] |
How can I make a valid request like:
```
UPDATE b2c SET tranche = '18 - 25'
WHERE (dateofbirth::date BETWEEN NOW()::date - 18 'year' AND NOW()::date - 25 'year')
```
Thanks for help | ```
dateofbirth::date BETWEEN
(NOW() - interval '25 year')::date AND
(NOW() - interval '18 year')::date
``` | You can use Postgres cast syntax:
```
UPDATE b2c SET tranche = '18 - 25'
WHERE dateofbirth::date BETWEEN
NOW()::date - '25y'::interval AND
NOW()::date - '18y'::interval
``` | Postgresql date subtract | [
"",
"sql",
"postgresql",
"datetime",
""
] |
I need help. I have table Employees and table Departments. And I need to get the department, which has the biggest sum of salaries.
I try this:
```
SELECT department_name,MAX(sum_salary) as sum_salary
FROM (SELECT department_name,SUM(salary) AS sum_salary
FROM EMPLOYEES,DEPARTMENTS
WHERE DEPARTMENTS.DEPARTMENT_ID =... | If, in the case of ties, you only want one, then `order by` and some form of getting one row works. The ANSI standard method is:
```
SELECT d.DEPARTMENT_NAME, SUM(e.salary) AS sum_salary
FROM EMPLOYEES e JOIN
DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY d.DEPARTMENT_NAME
ORDER BY SUM(e.salar... | ```
select
min(max(department_name)) keep (dense_rank last order by sum(salary))
as department_name,
min(sum(salary)) keep (dense_rank last order by sum(salary))
as sum_salary
from EMPLOYEES join DEPARTMENTS using(department_id)
group by department_id
```
[fiddle](http://sqlfiddle.com/#!4/d1d42/1) | SQL - How to get MAX of SUM? | [
"",
"sql",
"oracle",
"sum",
"max",
""
] |
The database is running on Oracle Database 11g using SQL \*Plus 11.2. Are aggregate methods not allowed in a WITH clause or is WITH doing something magical? This code tells me "most\_expensive" is an invalid identifier. Yet, a sub-query works with no issue.
```
WITH most_expensive AS (SELECT MAX (enrollment_cost) FROM... | Query factoring (with clauses) allows you to define temporary table aliases.
In your example most\_expensive is going to reference a table object containing a single row with a single column. You can use it anywhere in the query where you can use a table.
Now, if you create a table called t1 (with create table statment... | I don't see any benefit of using **sub-query factoring**(WITH clause) here. The query could simply be written as:
```
SELECT member_id
FROM Enrollments e
WHERE e.enrollment_cost =
(SELECT MAX (enrollment_cost) FROM Enrollments
);
```
Compare the explain plans:
**Without sub-query factoring:**
```
SQL> set autot... | Oracle SQL Plus WITH Clause "invalid identifier" | [
"",
"sql",
"oracle",
""
] |
I am having trouble getting the correct result with `CHARINDEX` . I have a column with the following dummy samples:
```
File Path
C/Desktop/Folder1/FileName1
C/Folder3/Filename2
C/Folder4/Folder5/Folder6/Filename3
```
And I would like it to return the following:
```
Filename1
Filename2
Filename3
```
Is it possible... | Let assume your full paths are stored in table fileinfo in column FullFilePath
```
SELECT
LTRIM(
RTRIM(
REVERSE(
SUBSTRING(
REVERSE(FullFilePath),
0,
CHARINDEX('\', REVERSE(FullFilePath),0)
)
)
)
)
FROM Fileinfo
``` | Try `PATINDEX` (Transact-SQL)
```
SELECT RIGHT(FilePath, PATINDEX('%/%', REVERSE(FilePath))-1) FROM FileTable
```
Ref: <https://msdn.microsoft.com/en-us/library/ms188395.aspx> | How to cut off string with various lengths based on character? | [
"",
"sql",
"sql-server",
"string",
""
] |
I have a sales table with 3 columns
```
OrderId, CustomersId, OrderDateTime
```
How to write a T-SQL select query to find number of `orderId`, January2015orders and April2015orders in the results? Thanks!
Should I use union or a case statement or ??? | What you are looking for is the [datepart function](https://msdn.microsoft.com/de-de/library/ms174420(v=sql.120).aspx)
If you want orders from the January, April of the year 2015 you could write your query as follows:
```
SELECT
count(t.OrderId) as Orders,
DatePart(month, t.OrderDateTime) as Month
FROM
... | If I understand you correctly:
```
select month(OrderDateTime),count(OrderId) from your data group by month(OrderDateTime)
```
It would be good to know If you mean:
> number of orderId as a count ? | Comparing orders by months in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Let's assume I have the following two tables:
```
CREATE TABLE users (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;
CREATE TABLE logins (
user_id NOT NULL,
day DATE NOT NULL,
PRIMARY KEY (`user_id, `day`)
) ENGINE=MyISAM;
```
What I'm tryi... | in order to use aggregate functions (min, max, ...) you need grouping. Try something like this:
```
SELECT u.id AS id, u.name AS name, MIN(l.day) AS first_login, MAX(l.day) AS last_login
FROM users u
LEFT JOIN logins l ON u.id = l.user_id
GROUP BY u.id
``` | Any sensible database except MySQL would have given you an error on mixing row-terms and aggregate terms, making the error clearer. MySQL, unfortunately allows this behavior, making it harder to notice that you forgot the `group by` clause needed to generate a row per user:
```
SELECT u.id AS id,
u.name ... | Using an SQL LEFT JOIN with the MAX() and MIN() functions | [
"",
"mysql",
"sql",
"select",
""
] |
I have two models : User and Rsvp. User has many Rsvps.
I want to get all Users that has no Rsvp created at a specified date.
So i wrote this :
```
scope :free, -> (date) { joins(:rsvps).where.not(rsvps: {created_at: date.beginning_of_day..date.end_of_day}) }
```
But it only works if User has at least one Rsvp but ... | This should work:
`scope :free, -> (date) { includes(:rsvps).where("rsvps.id IS NULL OR rsvps.created_at NOT BETWEEN ? AND ?", date.beginning_of_day, date.end_of_day).references(:rsvps) }`
Hope it helps! | It's normally that `joins` returns Users having at least one Rsvp. That's why I suggest using `includes`. Try this one (probably you have to modify the condition because I'm not sure it's what you want exactly):
```
scope :free, -> (date) { includes(:rsvps).where('rsvps.created_at != ?', date ).references(:rsvps) }
``... | Left outer join and where clause with rails activerecord | [
"",
"sql",
"ruby-on-rails-4",
"activerecord",
"left-join",
""
] |
Sorry for bad topic but I wasn't sure what to call it..
I have a table looking like this:
```
+-----++-----+
| Id ||Count|
+-----++-----+
| 1 || 1 |
+-----++-----+
| 2 || 5 |
+-----++-----+
| 3 || 8 |
+-----++-----+
| 4 || 3 |
+-----++-----+
| 5 || 6 |
+-----++-----+
| 6 || 8 |
+-----++-----+... | You could use [Recursive Queries](https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx)
Please note the following query assuming the id value are all in sequence, otherwise, please use `ROW_NUMBER()` to create a new id
```
WITH cte AS (
SELECT id, [Count], [Count] AS total_count
FROM Table1
WHE... | You can't do this using window/analytic functions, because the breakpoints are not known in advance. Sometimes, it is possible to calculate the breakpoints. However, in this case, the breakpoints depend on a non-linear function of the previous values (I can't think of a better word than "non-linear" right now). That is... | Running SUM in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have two databases heading into this: a table acting\_gigs with columns actor\_name and movie\_title and table movies with columns movie\_title and release\_year. I would like to make a SQL query that lists the names of all the actors that have participated in every single movie in a given release\_year, and display ... | Here's one way:
```
SELECT y.actor_name, y.release_year
FROM (SELECT release_year, COUNT(*) AS cnt
FROM movies
GROUP BY release_year) AS x
INNER JOIN (SELECT actor_name, release_year, COUNT(*) AS cnt
FROM acting_gigs AS t1
INNER JOIN movies AS t2 ON t1.movie_title = t2.movie_title
... | This should do the trick:
```
select m.release_year
, a.actor_name
, count(1) total_movies
from movies m
join actors a on a.movie_title = m.movie_title
group by m.release_year, a.actor_name
order by m.release_year, a.actor_name -- or however you want to order it
``` | How to list movie actors who acted in every single film released in any given year | [
"",
"sql",
"postgresql",
""
] |
I have a legacy column in my table which stores name and surname values together.
For Example: `Mike Huge Muyra` or `John Kutgira`.
I need to split column by whitespace.
Result must be like that (**Last word is surname, others are name**)
```
Name : Mike Huge, Surname : Muyra
Name : John, Surname : Kutgira
``... | You can use regular expressions for this. However, because the rule involves the *last* space perhaps regular string operations are fine:
```
select trim(substr(legacy, 1 - instr(reverse(legacy), ' '))) as surname,
trim(substr(legacy, 1, length(legacy) - instr(reverse(legacy), ' '))) as restname
```
You might ... | Try finding out the last index of space (' ') character and then using substring (twice I guess for first and last part) to get what you want.
Here is an [answer](https://stackoverflow.com/questions/856817/finding-last-index-of-a-string-in-oracle) for the last index of part. | Split column which have two or three word by space in oracle sql | [
"",
"sql",
"regex",
"oracle",
"split",
""
] |
OP is completely new to databases and SQL, so this question may be answered somewhere else but I don't quite have the vocabulary to find what I'm looking for; a push in the right direction would be great.
I'm trying to make a view of two tables inner joined. This is currently how they look:
[![enter image description ... | It is a little big statement to do it in comment so I will post it as an answer. If my understanding of the problem is correct then it will be like:
```
select *
from sizeconditionstable t1
join specalloytable t2
on (t1.c4 is not null and t2.c4 is not null and t1.c4 = t2.c4) or
(t1.c5 is not null and t2.c5 is not... | I think a UNION ALL query is your best bet here.
```
SELECT field1, field2, field3
FROM table1 t1
JOIN table2 t2 ON t2.field1 = t1.field1 AND t2.field2 = t2.field2
UNION ALL
SELECT field1, field2, field3
FROM table1 t1
JOIN table2 t2 ON t2.field1 = t1.field1 AND t2.field3 = t2.field3
```
In this case, if field 2 is... | SQL Inner join on one field when second is null and on second when first is null | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
"inner-join",
""
] |
The problem is that I want to list the orders that haven´t been payed at the end of the selected month (for example october 31.10.2015)
That means:
list all orders from the beginning of time to 31.10
AND date\_payed BETWEEN (1.11 - today)
AND date payed = NULL or before 1970
$sel\_date = 10-2015 (the selected day... | This was the solution for me
```
octt_order
WHERE order_status_id >= 1
AND (date_added BETWEEN STR_TO_DATE('01-2001','%m-%Y') AND STR_TO_DATE('$s3','%m-%Y'))
AND (date_payed BETWEEN STR_TO_DATE('$s3','%m-%Y') AND STR_TO_DATE('11-2300','%m-%Y') OR date_payed is NULL)
ORDER BY date_format(date_added,'%... | The first `BETWEEN` doesn't compare dates but strings. So '02-2000' will come before '03-2000', but after '02-2020', which is probably not what you want. Compare dates (like in the second `BETWEEN`) to fix that.
The second `BETWEEN` looks like it could do with some more brackets, though you might get away with your ve... | SQL multiple AND statements | [
"",
"mysql",
"sql",
"statements",
""
] |
I need big help from you I am using sql server 2008 and I want to get the output using sql query.
I have a following data in the table.
```
Id Code
-----------------
1 01012
2 01012
3 01012
4 01012
5 01013
6 01013
7 01014
```
I need Following output
```
Id Code
--... | **SQL Server 2012+ Solution**
*Can be adpated to 2008 be replacing `CONCAT` with `+` and `CHOOSE` with `CASE`.*
Data:
```
CREATE TABLE #tab(ID INT, Code VARCHAR(100));
INSERT INTO #tab
SELECT 1, '01012'
UNION ALL SELECT 2, '01012'
UNION ALL SELECT 3, '01012'
UNION ALL SELECT 4, '01012'
UNION ALL SELECT 5, '01013'
U... | You can use `ROW_NUMBER`. When Rn = 1, retain the original `Code` else, add `A`, `B`, and so on.
To determine which letter to add, the formula is `CHAR(65 - RN - 2)`.
```
WITH CTE AS(
SELECT *,
Rn = ROW_NUMBER() OVER(PARTITION BY Code ORDER BY Id)
FROM tbl
)
SELECT
Id,
Code = CASE
... | Add A,B,C letters to Duplicate values | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
I am using a statement as below and get this error:
> SELECT Failed. 3771: Illegal expression in WHEN clause of CASE
> expression.
I had better hopes from Teradata. SQL Server can do it but Teradata can't.
How can I work around this? Any solution?
```
sel ( CASE
WHEN EXISTS ( sel '1' from VolatileTable Dtb1 w... | Teradata doesn't like EXISTS in Correlated Scalar Subqueries within a CASE, but you can rewrite it like this:
```
select
( CASE
WHEN C1 = ( select MIN(C1) from VolatileTable Dtb1
where Dtb1.c1=ft.C1)
THEN ft."CustomColumName"
ELSE 'ALL OTHER'
END ) (NAMED "CustomColumNa... | Replace
```
WHEN EXISTS (...)
```
By
```
WHEN 1 = (SELECT 1 WHERE EXISTS (...))
``` | teradata SQL tuning pundits - SELECT Failed. 3771: Illegal expression in WHEN clause of CASE expression | [
"",
"sql",
"case",
"teradata",
"exists",
"sql-tuning",
""
] |
I want to write a query which retrieves rows in each tables present under a particular owner. I am not very good at writing queries and so I could not figure out the solution on internet. The query I am writing is:
```
SELECT TABLE_NAME, COUNT(*) FROM DBA_TABLES WHERE TABLE_NAME IN
(SELECT TABLE_NAME FROM DBA_TABLES ... | > Extracting number of records in each table
Then you are completely in a wrong direction while querying **DBA\_TABLES**. It will give you the count of tables owned by a user, but not the count of rows in each table.
There are three ways:
* In pure SQL, the table name must be static. i.e. you will have to list down ... | When you using group function (count) you must place all columns which appear in SELECT and not in group function in GROUP BY section
```
SELECT TABLE_NAME, COUNT(*)
FROM DBA_TABLES
WHERE OWNER='ABC'
GROUP BY TABLE_NAME;
```
BUT this query will return nothing interesting to you. It is not number of rows. It is num... | Extracting number of records in each table | [
"",
"sql",
"oracle",
"ora-00937",
""
] |
I want to display the number of reminders in queue as a statistic on my website. That statistic is the number of rows in my table. What I have been doing in the past is having a separate table that caches the number. The cached table has just one row and one column contained the number of rows in the reminder table. Ev... | As with the most optimization related question the answer is: well, it depends.
If your table uses myisam table type, then the number of rows is already cached in the table itself and count(\*) without where will read that number.
If you use innodb table engine and you have lots of inserts and less selects, then main... | If you are thinking of caching row counts, you probably shouldn't and you probably don't need it. There is a built in mechanism
[**SHOW TABLE STATUS**](http://dev.mysql.com/doc/refman/5.5/en/show-table-status.html)
Part of the output of that query includes:
> The number of rows. Some storage engines, such as MyISAM,... | Recount or cache count of mysql table | [
"",
"mysql",
"sql",
"caching",
""
] |
For simplicity say I have a column 'Hour' which is either the value 10, or 12. I wish to update a new column, Hour\_type which will be 'A' if the Hour value is 10 or B if 12 and so on. I can output a column, 'Hour\_type' by using CASE, as follows
```
SELECT CASE WHEN Hour = 10 then 'A'
WHEN hour = 12 then ... | The `case [...] end` block is an expression. `update` is used to `set` columns from expressions. So, just take the entire `case [...] end` block and make that the right-hand-side of an `update` to your desired column. This would work for any other `select`able expression, too (barring conflicting types, etc.) | Use this, but i am not sure what are you doing.
This return 'a', 'b' or 'X' if the HOUR not 10 or 12
```
update table set Hour_type = IF(HOUR = 10 , 'a', IF(HOUR = 12, 'b', 'X'));
``` | Using CASE to update column value depending on other column values | [
"",
"mysql",
"sql",
""
] |
I have one table like
```
product_id tag_id value
1 1 10
1 2 51
1 3 47
2 1 15
2 2 59
2 3 44
3 1 10
3 2 51
3 ... | Either do a `GROUP BY`, use `HAVING` to make sure all 3 different tag\_id/value combos are included.
```
SELECT product_id
FROM tablename
WHERE (tag_id = 1 AND value = 10)
OR (tag_id = 2 AND value = 51)
OR (tag_id = 3 AND value = 47)
group by product_id
having count(distinct tag_id) >= 3
```
Or, do a double sel... | This is usually done using `HAVING`:
```
SELECT product_id
FROM tablename
WHERE (tag_id = 1 AND value = 10)
OR (tag_id = 2 AND value = 51)
OR (tag_id = 3 AND value = 47)
GROUP BY product_id
HAVING COUNT(*) = 3 -- number of searched combinations
```
This assumes that the combination`tag_id`/`value` is unique,... | Sql return distinct rows with specific values | [
"",
"sql",
"distinct-values",
""
] |
please help me solve this problem:
You are given a table, containing two columns:
column is one of the followings:
```
Doctor
Professor
Singer
Actor
```
Write a query to output the names underneath the corresponding occ. in the following format:
```
+--------+-----------+--------+------+
| Doctor | Professor | Sing... | You just need to give each name a row number based on their occupation and order alphabetically.. then include that row number in your pivot query.
```
CREATE TABLE Occupations (
NAME VARCHAR(MAX),
Occupation VARCHAR(MAX)
)
INSERT INTO Occupations
VALUES
('Samantha','Doctor'),
('Julia','... | I tried this in **Oracle**, seemed easier to comprehend:
```
SELECT min(Doctor), min(Professor), min(Singer), min(Actor)
FROM
( Select
ROW_NUMBER() OVER (PARTITION BY Occupation order by Name) rn,
CASE
WHEN Occupation = 'Doctor' then Name
end as Doctor,
CASE
WHEN Occupation = 'Professor' then Name
end as Professor,... | How to use pivot in sql server (without aggregates )? | [
"",
"sql",
"sql-server",
"database",
""
] |
I have this string `1111-2222-3-4-55-12345678901234567 1` in MYSQL Table Field.
What I need to do is to separate first 5 parameters separated with a `-`. Like I need to Separate:
```
1111
2222
3
4
55
``` | Even though I did not test it, this should solve your problem.
```
SELECT `mystring`,
SUBSTRING_INDEX(mystring,'-',1) AS part1,
SUBSTRING_INDEX(SUBSTRING_INDEX(mystring,'-',2),'-',-1) AS part2,
SUBSTRING_INDEX(SUBSTRING_INDEX(mystring,'-',3),'-',-1) AS part3,
SUBSTRING_INDEX(SUBSTRING_INDEX(mystrin... | ```
$stringElements = explode('-', $string);
echo $stringElements[0];// 1111
echo $stringElements[1];// 2222
echo $stringElements[2];// 3
echo $stringElements[3];// 4
echo $stringElements[4];// 55
$stringElements[5];// 12345678901234567 1
``` | Need to Separate the String with a separator of - in MYSQL | [
"",
"mysql",
"sql",
""
] |
There is a column `name` from which I want to use to make a new column.
example:
```
name
asd_abceur1mz_a
asd_fxasdrasdusd3mz_a
asd_abceur10yz_a
asd_fxasdrasdusd15yz_a
```
The length of the column is not fixed so I assumed i have to use charindex to have a reference point from which I could trim.
**What i want:** at... | This works for one or two digits:
```
stuff(case
when name like '%[0-9][0-9]_z[_]a'
then left(right(name, 9), 6)
when name like '%[0-9]_z[_]a'
then left(right(name, 8), 5)
end, 4, 0, '_')
``` | You can use a combination of `substring` , `reverse` and `charindex`.
[SQL Fiddle](http://www.sqlfiddle.com/#!6/6f3dc/1)
```
select substring(namenew,1,3) + '_' + substring(namenew, 4, len(namenew))
from (
select
case when name like '%[0-9][0-9]_z[_]a' then
reverse(substring(reverse(name), charindex('a_z',reverse(n... | using charindex in a substring to trim a string | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I have a report written out of SQL that I am pulling into an Excel workbook (hence the multiple tags) with Patient Information that I want to filter into other values. For instance my workbook looks something like this:
```
Name Acct # Date
Shmo,Joe 12345 1/1/15
Shmo,Joe 49738 ... | Answer for Excel. This adds a new column in D. Change to a different column if necessary.
```
Sub Zach()
Dim lastRow As Long
lastRow = WorkSheets("Sheet6").Cells(WorkSheets("Sheet6").Rows.Count, "A").End(xlUp).Row 'change sheet
n = 1
S = 2
For i = 2 To lastRow
If Cells(i + 1, 1) <> Cells(i, 1) Then
Ran... | If you are using Sql Server then the following will give the alias you want:
```
concat('Patient ',DENSE_RANK() over(order by name))
``` | Substitute codes for names | [
"",
"sql",
"excel",
"vba",
""
] |
I have a table `company` with column `customerID` and I want every customer id from 80000 to 80999.
But the column `customerID` is varchar an some of them contain letters.
So, I must put `customerID` into ' ' and when I try this query:
```
select *
from company
where customerID between '80000' and '80999'
```
it re... | ```
where customerID between '80000' and '80999'
and character_length(customerID) = 5 -- only five digit IDs
``` | You could use regular expressions to format. Something like this should get you started [Query to get only numbers from a string](https://stackoverflow.com/questions/16667251/query-to-get-only-numbers-from-a-string) | SQL - WHERE between on varchar column | [
"",
"sql",
"where-clause",
"between",
""
] |
I have a table with a column of comma separated values,
i want to take them as different values and place inside The In clause of another select statement. i've tried with cross apply but didn't get it working properly
the table (T1) looks like :
```
Empcode Eid Unitcodes
007645 164 UNT111$UNT112$UNT113$
000645 162... | You can do It in following:
**QUERY**
```
SELECT *
FROM #test2
WHERE ID IN (
SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Unitcodes
FROM
(
SELECT CAST('<XMLRoot><RowData>' + REPLACE(Unitcodes,'$','</RowData><RowData>') + '</RowData></XMLRoot>' AS X... | Create a function : This function will split your values
```
Create FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHI... | Comma separated values In An IN statement (SQL) | [
"",
"sql",
"sql-server",
"cross-apply",
""
] |
I need to inactivate a bunch of users. I have a list like this (sample):
N0120454
N0219746
N0074342
N0203867
N0155928
N0025471
N0017467
N0239158
N0191759
N0007671
```
UPDATE dbo.Users
set IsActive = 0, IsLocked = 1
where UserName = 'N0007671'
```
Is there a way to perform this without doing it UserId by UserId? | If you have a hard-coded list the easiest way is to do:
```
UPDATE dbo.Users
set IsActive = 0, IsLocked = 1
where UserName IN ('N0120454', 'N0219746', 'N0074342',
'N0203867', 'N0155928', 'N0025471',
'N0017467', 'N0239158', 'N0191759', 'N0007671')
```
If you expect to pass in a... | May be using [in operator](http://www.w3schools.com/sql/sql_in.asp)
```
UPDATE dbo.Users
set IsActive = 0, IsLocked = 1
where UserName in( 'N0007671', 'N0219746', 'N0074342' ...)
```
If your vales are in the database table, you have 2 ways to do it
1 - Using [IN](http://www.w3schools.com/sql/sql_in.asp)
```
UPDATE... | Updating Based on List | [
"",
"sql",
"sql-update",
""
] |
Okay, so I have 3 tables:
users
```
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL,
`user_username` varchar(25) NOT NULL,
`user_email` varchar(100) NOT NULL,
`user_password` varchar(255) NOT NULL,
`user_enabled` int(1) NOT NULL DEFAULT '1',
`user_staff` varchar(15) NOT NULL DEFAULT '',
... | Your best bet would be to use the `UNION` operator to mix them all in 1 table, and then query based on type. For instance, you could do something like this :
```
SELECT f.*,
t.training_company_name as name,
null as staff,
t.training_company_enabled as enabled,
t.training_company_has_banner as banner... | I think you will need another variable to tell you the type in addition to the user id. Then you can wrap both up in a CASE statement, like so:
```
WHERE
CASE WHEN type = 'USER' THEN timeline_status.timeline_status_user = id
WHEN type = 'FRIENDS' THEN friends.friends_user = id
WHEN type = 'FOLLOWING' THEN following.u... | Trying to left join 3 tables where the id could be the same, I am defining it via the type | [
"",
"mysql",
"sql",
""
] |
I'm trying to split a column, in SQL, into multiple columns.
My data looks like this:
```
Column1 | Column2 | Column3
ABC | 123 | User7;User9
nbm | qre | User1;User2;User3
POI | kjh | User1;User4;User5;User9
```
I need to split the Column3 into 4 new columns - each column containing the... | Besides the fact that this is bad design here is a solution:
Just paste this into an empty query window and execute. Adapt to your needs...
```
declare @tbl TABLE(Column1 VARCHAR(15),Column2 VARCHAR(15),Column3 VARCHAR(150));
INSERT INTO @tbl VALUES
('ABC','123','User7;User9')
,('nbm','qre','User1;User2;User3')
... | Here is a method that will be 100% dynamic. It will produce any number of columns based solely on the data it finds. The prevailing method for this around SO is a dynamic pivot. I prefer a dynamic crosstab as I find the syntax less obtuse and it has a slight benefit from a performance standpoint too. :)
Here is an art... | Split semicolon-delimited column into multiple columns | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the following table:
```
crit_id | criterium | val1 | val2
----------+------------+-------+--------
1 | T01 | 9 | 9
2 | T02 | 3 | 5
3 | T03 | 4 | 9
4 | T01 | 2 | 3
5 | T02 | 5 | 1
6 | T03 ... | ## Prepare for crosstab
In order to use [`crosstab()`](http://www.postgresql.org/docs/9.4/static/tablefunc.html) function, the data must be reorganized. You need a dataset with three columns (`row number`, `criterium`, `value`). To have all values in one column you must *unpivot* two last columns, changing at the same... | I agree with Michael's comment that this requirement looks a bit weird, but if you really need it that way, you were on the right track with your solution. It just needs a little bit of additional code (and small corrections wherever val\_1 and val\_2 where mixed up):
```
select
sum(case when criterium = 'T01' the... | How to pivot or 'merge' rows with column names? | [
"",
"sql",
"postgresql",
"pivot",
""
] |
Excel's datetime values look like 42291.60493, which means MySQL sees them as strings and not as dates.
Is there a MySQL code that can convert them to MySQL datetime? (i.e. [like in MS SQL](https://stackoverflow.com/questions/13850605/t-sql-to-convert-excel-date-serial-number-to-regular-date)) | I can think of 2 solutions:
1. Convert your dates within excel to a formatted date string that conforms to mysql's date and time format using text() function within excel.
2. Convert the number using calculation to date within mysql:
(the expression below may be simplified)
```
select date_add(date_add(date('1899-12... | Excel stores date times as the number of days since 1899-12-31. Unix stores the number of seconds since 1970-01-01, but only non-negative values are allowed.
So, for a *date*, you can do
```
select date_add(date('1899-12-31'), interval $Exceldate day )
```
This doesn't work for fractional days. But, for a unix date ... | MySQL code to convert Excel datetime | [
"",
"mysql",
"sql",
"excel",
"type-conversion",
""
] |
```
DELETE FROM BIZ
WHERE [Orgnl_Cmpltn_Date]
BETWEEN '2014-02-31' AND '2014-04-01'
```
This is the `DELETE` statement I wrote. There is an error that says:
> Conversion failed when converting date and/or time from character string.
I know I have to write the correct date format, but I am not sure how that g... | You wrote 31st of February... Maybe..... that date doesn't exists.
```
DELETE FROM BIZ
WHERE [Orgnl_Cmpltn_Date]
BETWEEN '2014-02-28' AND '2014-04-01'
```
For a general idea of convert date:
```
DELETE FROM BIZ
WHERE [Orgnl_Cmpltn_Date]
BETWEEN CONVERT(date,'2014.02.28',102) and CONVERT(date,'2014.04.01',102)
```... | Use this instead
```
DELETE FROM BIZ
WHERE [Orgnl_Cmpltn_Date] >= '2014-02-28'
AND [Orgnl_Cmpltn_Date] <= '2014'04'01'
```
I don't know if this matters, but February has only 28 or 29 days. | SQL Server - Deleting rows between a date range using SQL. Date conversion fails | [
"",
"sql",
"sql-server",
"sql-server-2008",
"datetime",
"sql-delete",
""
] |
I need to write a query that will result with a "fail" condition when one test fails. Testing results are listed in the Fail and Pass columns. One manufacturer product can have many tests. My Data is like this:
```
MFG Name | Code | Breaker | Fail | Pass
-----------------------------------------
ABC R ... | Try:
```
select mfg_name,
code,
case when sum(fail) > 0 then 'FAIL' else 'PASS' end as result
from tbl
group by mfg_name,
code
```
This assumes you want to show combinations of (`mfg_name` and `code` pairs with no fails as a 'PASS', for only fails you would add `havi... | This is an aggregation query. Assuming `fail` only takes on two values (0 and 1):
```
select MFGName, Code,
(case when max(fail) = 1 then 'FAIL' else 'PASS' end) as Result
from tests
group by MFGName, Code;
``` | Sql query to compare the result between multiple records and provide a result | [
"",
"sql",
"coalesce",
"aggregates",
""
] |
I have a Select query:
```
Select left([Foundation_Account_Name],4)
From [dbo].[tbl_Foundation_Account]
Where [Foundation_Account_Name]
```
That returns
```
MAZA
SUMI
APLH
```
I have a second Select query that selects the same fields from a temp table
```
Select left([Foundation Account Name],4) ... | You can use `intersect` to get the common results from both the queries.
```
Select left([Foundation_Account_Name],4)
From [dbo].[tbl_Foundation_Account]
INTERSECT
Select left([Foundation Account Name],4)
From [dbo].[Import_tbl_RDO]
Where [Foundation Account Name] IS NOT NULL
``` | Just building on what you have already... and JOINING the tables together...
though intersect seems cleaner...
```
with A as (SELECT left([Foundation_Account_Name],4) ID
FROM [dbo].[tbl_Foundation_Account]),
b as (SELECT left([Foundation Account Name],4) ID
FROM [dbo].[Import_tbl_RDO])
SEL... | Issue with Subquery in Where Clause | [
"",
"sql",
"sql-server",
""
] |
I have an controller method like this:
```
def index
@categories = Category.all
end
```
How do I order `@categories` names alphabetically? | You can `order`:
```
@categories = Category.order(:name)
``` | In you Categories Controller:
```
class CategoriesController < ApplicationController
def index
@categories = Category.order(:name)
end
end
```
This will by default order the `:name` column in by alphabetical order. | Order ActiveRecord results alphabetically | [
"",
"sql",
"ruby-on-rails",
"activerecord",
"sql-order-by",
"rails-activerecord",
""
] |
I have joined 1 table twice on the same query, I keep getting error messages that the 'FROM clause have same exposed names. Even using AS does not seem to work, any ideas or suggestions?
here is the query I am using;
```
select Contact.*, PERSON.*, address.*
from address
full join Contact
on address.uprn = Contact.u... | ```
select Contact.*, PERSON.*, a1.*, a2.*
from address a1
full join Contact
on a1.uprn = Contact.uprn
full join PERSON
on Contact.contactno = PERSON.contact
full join address a2
on a2.uprn = PERSON.driveruprn
```
, however there is no full join in mysql, workaround
```
select * from t1
left join t2 ON t1.id = t2.id
... | You have to alias the second and subsequent usages of a table:
```
select ...
from address <---first usage
join contact ...
join person ...
join address AS other_address ... <---second usage
^^^^^^^^^^^^^^^^
```
Doesn't really matter exactly where you do the aliases, but if you u... | Joining 1 table twice in the same SQL query | [
"",
"mysql",
"sql",
""
] |
Hey I have a large database where customers request data that is specific to them. They usually send me the requests in a text or csv file. I was wondering if there is a way to get sql to read that file and take the content and put them into a sql query. This way I don't have to open up that file and copy and paste eve... | Steve already answered it.
Let me add few words only.
> you can not use the csv, text,excel or anyother format directly in
> query for DML/DDL.. you can use file directly only for export/import. | No. MySQL is not designed to do this.
You need an intermediate script that can interpret the files and generate the queries you require. | Putting a file content into an sql query? | [
"",
"mysql",
"sql",
""
] |
I have some strings like
```
2) Some text
34) Some text more
5 Some other text
```
and I need to find if certain text starts with pattern some numbers (not fixed) followed by a closing bracket ')'
I tried:
```
If (PATINDEX('[^a-zA-Z]%', @myString) > 0)
begin
print @myString
end
```
but it showed all the string... | SQL Server doesn't have great pattern matching but if you know that the numbers prefixing the `)` will always be less then 500, you can do this:
```
DECLARE @myString VARCHAR(100) = '266) Some text'
If (PATINDEX('[0-9])%', @myString) > 0) OR --Check for one digit
(PATINDEX('[0-9][0-9])%', @myString) > 0) O... | This will not consider all combinations but you can check. For example it certainly will fail if there will be several ')' symbols in string :
```
select * from t
where s like '[0-9]%)%' and s not like '[0-9]%[^0-9]%)%'
```
Fiddle here <http://sqlfiddle.com/#!3/3b5fd/3> | How to find if a string starts with a number and a bracket in SQL server? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
SELECT LTRIM(RTRIM(HOST0149.LOGINID)) AS LOGINID,
LTRIM(RTRIM(HOST0140.EMAIL)) AS EMAIL,
LTRIM(RTRIM(HOST0149.USERKEY)) AS ROLE
FROM HOST0149 LEFT JOIN
HOST0140 ON HOST0149.PERSONKEY = HOST0140.PERSONKEY
```
Hi, I am trying to apply a rule on the select for email column. Sometimes the login... | `CASE...WHEN` should do. Basically, you handle both cases explicitely.
```
SELECT LTRIM(RTRIM(HOST0149.LOGINID)) AS LOGINID,
CASE WHEN LTRIM(RTRIM(HOST0140.EMAIL)) = LTRIM(RTRIM(HOST0149.LOGINID)) THEN NULL ELSE LTRIM(RTRIM(HOST0140.EMAIL)) END AS EMAIL,
LTRIM(RTRIM(HOST0149.USERKEY)) AS ROLE
FROM HOST0149 LEFT ... | I think a `case` expression does what you want:
```
SELECT LOGINID,
(CASE WHEN LOGINID <> EMAIL THEN EMAIL END) as EMAIL,
ROLE
FROM (SELECT LTRIM(RTRIM(HOST0149.LOGINID)) AS LOGINID,
LTRIM(RTRIM(HOST0140.EMAIL)) AS EMAIL,
LTRIM(RTRIM(HOST0149.USERKEY)) AS ROLE
FROM HOST014... | Applying a rule | [
"",
"sql",
"sql-server",
"sql-server-2008",
"if-statement",
"constraints",
""
] |
I wrote a stored procedure who take a reference date, and add a hour to this element.
Here is my line doing the operation :
```
DATEADD(day, DATEDIFF(DAY, 0, @conductor_date), [HOUR])
```
For example, whith `@conductor_date = '2015-10-15'` and `[HOUR] = 23:00` it works and generate me a date like that : `'2015-10-15... | You can split your `@hour` field into hours and minutes and add them separately:
```
DECLARE @conductor_date datetime
DECLARE @hour varchar(5)
DECLARE @hours int
DECLARE @minutes int
DECLARE @offset datetime
SET @conductor_date = '2015-10-15'
SET @hour = '24:40'
SET @hours = cast(left(@hour, 2) as int)
SET... | According to the [documentation](https://msdn.microsoft.com/en-us/library/ms186724.aspx), date / time types don't support times larger then 23:59:59.9999999. You have to do manual string parsing for this.
First you need to extract the total hours, divide that by 24 to get total days. Then calculate leftover hours, and... | Data operations | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a dataset of 3 columns - Name, date-time, value
For ex:
```
Name DateTime value
----------------------------
A 1/1/2011 1:00:00 626
A 1/1/2011 2:00:00 2311
B 1/1/2011 3:00:00 775
A 1/1/2011 4:00:00 6621
A 1/1/2011 5:00:00 8491
B 1/1/2011 6:00:00 9061
B 1/1/2011 7:00:0... | i found a solution: find the max value for each Name within 24h and than to check which of the dates is the first and includes the current occurrence within
```
SET NOCOUNT ON;
CREATE TABLE #Temp
(
Name varchar(128)
,[Date] DATETIME
,[Value] INT
);
INSERT INTO #Temp
SELECT 'A','2011-01-01 1:00:0... | Try this way
```
select Name,SUM(Value) from Tblname group by Name,CONVERT(date,[Datetime],106)
``` | Sum values within 24 hours without repetition | [
"",
"sql",
"sql-server",
""
] |
I'm working on a huge DB in PostgreSQL. (Sorry if this is not redacted properly, I've been trying this for hours and still working on it)
This is part of structure of the table used for my query: (table user\_activities) with some sample data.
```
+---------------------+---------------------+---------------------+
| ... | [**SQL Fiddle Demo**](http://sqlfiddle.com/#!15/46e1f/8)
Just use a CASE to put together the groups you want.
```
WITH cte as (
SELECT "user_id", "activity", "operation",
CASE
WHEN "activity" = 1 THEN
CASE
WHEN "operation" IN (1,2) THEN '1_first' ... | Updated for your detailed specification:
```
SELECT COUNT(*) as cnt, ua.activity, array_agg(distinct ua.operation)
FROM users ua
JOIN (
SELECT 1 AS activity, 1 as operation, 1 as GROUP_CODE
UNION ALL
SELECT 1 AS activity, 2 as operation, 1 as GROUP_CODE
UNION ALL
SELECT 1 AS activity, 3 as operation, 2 a... | Group by group of values | [
"",
"sql",
"postgresql",
""
] |
I have two tables `Service` and `Status`. The service table only holds a `name` and an `id`
```
| id | name |
|----|-------|
| 1 | Test1 |
| 2 | Test2 |
```
And a Status table like this
```
| id | status | service_id | timestamp |
|----|--------|------------|---------------------------|
| 1 | ... | You can do this:
```
SELECT
ser.id,
ser.name,
s.status,
s.timestamp
FROM Service ser
INNER JOIN status as s ON s.service_id = ser.id
INNER JOIN
(
SELECT
service_id,
MAX(timestamp) AS MaxDate
FROM status
GROUP BY service_id
) AS a ON a.service_id = s.service_id
AND a.MaxDate ... | For each service, use `NOT EXISTS` to return status only when no later one exists:
```
select ser.id, ser.name, st.status, st.timestamp
from service ser
left join status st1 on ser.id = st1.service_id
where not exists (select 1 from status st2
where st2.service_id = st1.service_id
... | Selecting from two tables with inner join and limit | [
"",
"mysql",
"sql",
""
] |
I get an error `ORA-00907: missing right parenthesis` In sql developer shows there is syntax error`syntax error expected: (` in this line
> BUDGET\_MANAGEMENT\_SCENARIO.property\_id =
> u.property\_id,BUDGET\_MANAGEMENT\_SCENARIO.agency\_id = u.agency\_id
Here is my sql statement
```
SELECT
PROPERTY_NAME, AGENCY... | The correct select is:
```
SELECT PROPERTY_NAME, AGENCY_NAME, ADVERTISER_NAME,BUYING_AE_NAME,CLIENT_AE_NAME
FROM "BUDGET_MANAGEMENT_SCENARIO"
WHERE "BUDGET_MANAGEMENT_SCENARIO"."PROPERTY_ID" = 2 AND
"BUDGET_MANAGEMENT_SCENARIO"."QUARTER_ID" IN (17, 18, 19, 20) AND
( BUDGET_MANAGEMENT_SCENARIO.property_id, BUDGET_... | The following isn't valid SQL:
```
(BUDGET_MANAGEMENT_SCENARIO.property_id = u.property_id,BUDGET_MANAGEMENT_SCENARIO.agency_id = u.agency_id)
IN (SELECT ...
```
I'm not exactly sure what you're attempting to do, but you cannot compare columns and use the result of that comparison in an `IN (...)` clause. | I get error ORA-00907: missing right parenthesis | [
"",
"sql",
"oracle",
""
] |
Hopefully this is a quickie
```
SELECT *
FROM T
left JOIN J ON
CASE
WHEN condition1 THEN 1 --prefer this option even if CASE2 has a value
WHEN condition2 THEN 2
ELSE 0
END = 1 (edit: but if 1 does not satisfy, then join on 2)
```
Both cases return results, but I want THEN 1 to supersede THEN 2 and be... | It doesn't matter which of the conditions causes the rows to match in a join. There are legitimate reasons to use a `case` expression in a join but I think you just want to `or` your conditions and then use the `case` expression to output a ranked reason for the match.
```
SELECT *, CASE WHEN <condition1> THEN 1 WHEN ... | Well, you can always have several conditions in your CASE Statements:
```
SELECT *
FROM T
left JOIN J ON
CASE
WHEN condition1 THEN 1 --prefer this option even if CASE2 has a value
WHEN condition2 And !condition1 THEN 2
ELSE 0
END = 1
```
--UPDATED--
If both of your conditions are required to match, bu... | SQL LEFT JOIN with conditional CASE statements | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"case",
""
] |
I have the following table:
```
CREATE TABLE dbo.TestSort
(
Id int NOT NULL IDENTITY (1, 1),
Value int NOT NULL
)
```
The `Value` column could (and is expected to) contain duplicates.
Let's also assume there are already 1000 rows in the table.
I am trying to prove a point about unstable sorting.
Given this query ... | If you have ties when ordering the order by is not stable.
**[LiveDemo](https://data.stackexchange.com/stackoverflow/query/375976)**
```
CREATE TABLE #TestSort
(
Id INT NOT NULL IDENTITY (1, 1) PRIMARY KEY,
Value INT NOT NULL
) ;
DECLARE @c INT = 0;
WHILE @c < 100000
BEGIN
INSERT INTO #TestSort(Value)
VALUES ('... | Your intuition is correct. In SQL, the sort for `order by` is not stable. So, if you have ties, they can be returned in any order. And, the order can change from one run to another.
The [documentation](https://msdn.microsoft.com/en-us/library/ms188385.aspx) sort of explains this:
> Using OFFSET and FETCH as a paging ... | Can SQL return different results for two runs of the same query using ORDER BY? | [
"",
"sql",
"sql-server",
"sql-order-by",
""
] |
I want to model a database to store data of several types of tournaments (whith different types of modes: single rounds, double rounds, league, league + playoffs, losers, ...).
Maybe, this project would be a kind of Challonge: www.challonge.com
My question is: How to create a model in sql-relationship database to sto... | I can understand why you're struggling with modeling this. One of the key reasons why this is difficult is because of the [object relational impendance-mismatch](https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch). While I am a huge fan of SQL and it is an incredibly powerful way of being able to organi... | It's easy to make data models far more complex than they need to be. A lot of what you describe is business logic that can't actually be answered by a perfect data model. Most of the tournament logic should be captured outside the data model in a programming language, such as mysql functions, Java, Python, C# etc. Real... | How to model several tournaments / brackets types into a SQL database? | [
"",
"mysql",
"sql",
"database-design",
""
] |
I have stored Fiscal month as a Nvarchar column in a table and want to sort that table based on fiscal month.
Create Table sample(
id Ineger
,FiscalMonth Nvarchar(MAX)
);
Ex: Table contain this data
```
Id FiscalMonth
-----------------
1 FY15-Oct
2 FY15-Sep
3 FY15-Jul
4 FY15-Aug
```
Now if i sort ... | to sort for different years and then by month the `order by` in MS SQL should work as below:
```
SELECT [Id],[FiscalMonth]
From Sample
order by convert(date,Substring([FiscalMonth],6,3)+ ' 01 ' + Substring([FiscalMonth],3,2),103)
```
This assumes that your `FiscalMonth` Column is always the same format. | You should give a number for each month, distinguish them you can for the last three letter.
```
SUBSTRING (FiscalMonth , 5 , 3 )
```
And after that sorted by those numbers. | How to sort Fiscal month that are stored as Nvarchar in SQL server 2008 | [
"",
"mysql",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to figure out the best way to determine, for a specific ID within an Oracle 11g table that has 5 columns and say 100 rows against this ID, if all the column values are the same for these five columns.
For example:
Table Name: **TABLE\_DATA**
Columns:
```
TD_ID ID COL1 COL2 COL3 COL4 C... | See if the following is fast enough for you:
```
SELECT ID, CASE WHEN COUNT(*) > 1 THEN 'No' ELSE 'Yes' END As "Result"
FROM (SELECT DISTINCT ID, COL1, COL2, COL3, COL4, COL5
FROM Table_Data) dist
GROUP BY ID
``` | You may also try this :
```
Select ID
, case when count(distinct COL1 || COL2 || COL3 || COL4 || COL5) > 1
then 'N'
else 'Y' end RESULT
From TABLE_DATA
Group by id;
```
In this way you group by id and counts how many distinct combination are there.
If only 1 , so all the rows have the same set of values, otherw... | How to check Oracle column values are all the same for a specific ID? | [
"",
"sql",
"oracle",
"plsql",
"oracle11g",
""
] |
I use a view to generate affected rows. A table `t1` has five columns with Mo, Tu, We, Th and Fr. Each columns has 0 if this day is not relevant or 1 if this day is relevant (e.g. 1,0,1,0,1 - Mo, We and Fr are relevant, Tu, Th are not relevant). Now I define the day actual date + 1 and will receive all rows which have ... | `DATEPART` return a number, in case of `WEEKDAY` ranging (by default) from 1 (Sunday) to 7 (Saturday)
```
WHERE
-- choose the relevant column
CASE DATEPART(WEEKDAY, GETDATE() + 1)
WHEN 2 THEN t1.Mo
WHEN 3 THEN t1.Tu
WHEN 4 THEN t1.We
WHEN 5 THEN t1.Th
WHEN 6 THEN t1.Fr
-- compare with the expected value
END ... | You need to separate the value the `case` returns with the comparison, which is a different thing:
```
WHERE
1 = CASE SUBSTRING(DATEPART(WEEKDAY, GETDATE() + 1), 1, 2)
WHEN 'Mo' THEN t1.Mo
WHEN 'Tu' THEN t1.Tu
-- ...
END
``` | Case in Where Clause using datepart | [
"",
"sql",
"sql-server",
"select",
"case",
""
] |
is it possible to replace row value with empty string if duplicate value found?
For example
```
SELECT ProductCode, Color FROM Product
--------------------
ProductCode | Color
--------------------
00A0B | Red
00A0B | Blue
00A0C | Red
00A0C | Black
00A0C | White
--------------------... | Often, this type of transformation is better done at the application layer, because the result-set is not "SQL-ish". That is, the ordering is important for understanding the rows.
But, you can do this as:
```
select (case when row_number() over (partition by ProductCode order by (select NULL)) = 1
then P... | Use `ROW_NUMBER` and `CASE`:
```
WITH Cte AS(
SELECT *,
Rn = ROW_NUMBER() OVER(PARTITION BY ProductCode ORDER BY (SELECT NULL))
FROM Product
)
SELECT
ProductCode = CASE WHEN Rn = 1 THEN c.ProductCode ELSE '' END,
Color
FROM Cte c
ORDER BY c.ProductCode
``` | Replace row value with empty string if duplicate | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I need to count the number of changing values in a column sequentially. Please see image for illustration (correct or expected output)
In here, the column `Area` is changing, counter column should display the sequential counter based on the changing values in area.
[ OVER (ORDER BY grpOrder) AS counter
FROM (
SELECT tenant, area, date, sales,
MIN([date]) OVER (PARTITION BY area, grp) AS grpOrder
FROM (
SELECT tenant, area, [date], sales,
... | You can do it like this with window functions:
```
declare @data table(name varchar(10), area int, dates datetime, sales int)
insert into @data(name, area, dates, sales) values
('Little Asia', 18, '20150101', 10)
, ('Little Asia', 18, '20150102', 20)
, ('Little Asia', 20, '20150103', 30)
, ('Little Asia', 20, '2015010... | SQL Server Query to Count Number of Changing Values in a Column Sequentially | [
"",
"sql",
"sql-server",
"sql-server-2008",
"database-partitioning",
""
] |
I am trying to achieve **Case 3**:
**Case 1:** Customer is registered but did not placed an order yet. The query gives result for case 1.
```
SELECT c.customers_id,
c.customers_firstname,
c.customers_lastname,
c.customers_email_address,
c.customers_telephone,
c.customers_fa... | ```
SELECT c.customers_id,
c.customers_firstname,
c.customers_lastname,
c.customers_email_address,
c.customers_telephone,
c.customers_fax,
ab.entry_street_address,
ab.entry_city,
ab.entry_state,
ab.entry_country_id,
ab.entry_postcode,
... | Change `JOIN orders o` to `LEFT JOIN orders o` (which will fill a NULL row), then change your condition to
```
WHERE (o.date_purchased BETWEEN '2014-10-25' AND '2015-10-10' OR o.customers_id IS NULL)
```
That will find anyone with an order in that timeframe, or customers that have not yet placed an order. | Select query with optional condition | [
"",
"mysql",
"sql",
""
] |
How can I count pair-wise occurrences in a SQL Server table? Please note that the order of the given sequence has to be accounted for and shouldn't be changed.
Original table:
```
1 2 3 4
--------
1 | A A A B
2 | A # don't count
3 | B A A
4 | B # don't count
```
Result:
```
1 | AA = 3
2 | AB = 1
... | **[LiveDemo](https://data.stackexchange.com/stackoverflow/query/374429)**
```
CREATE TABLE #tab([1] NVARCHAR(100), [2] NVARCHAR(100),
[3] NVARCHAR(100), [4] NVARCHAR(100));
INSERT INTO #tab
VALUES ('A', 'A', 'A', 'B') ,('A' , NULL ,NULL ,NULL )
,('B' ,'A' ,'A', NULL),('B', NULL, NULL, NU... | I just want to point out a pretty easy way to *express* this logic:
```
with vals as (
select 'A' as val union all select 'B'
)
pairs as (
select t1.val as val1, t2.val as val2
from vals t1 cross join vals t2
)
select p.*,
(select count(*)
from original
where [1] ... | Count pair-wise occurrences in a T-SQL table | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
for a quick check I used a query
```
select COUNT(*) LargeTable
```
and was surprized to see
```
LargeTable
-----------
1
```
seconds later I realized my mistake, made it
```
select COUNT(*) from LargeTable
```
and got expected result
```
(No column name)
-----------
1.000.000+
```
but now I don't understand wh... | In SQL Server a `SELECT` without a `FROM` clause works as though it operates against a single row table.
This is not standard SQL. Other RDBMSs provide a utility `DUAL` table with a single row.
So this would be treated effectively the same as
```
SELECT COUNT(*) AS LargeTable
FROM DUAL
```
A related Connect Item ... | Because without the **FROM** clause DBMS cannot know [LargeTable] is a table. You tricked it in guessing it's a **COLUMN NAME** alias
You can try it and see
```
select count(*) 'eklmnjdklfgm'
select count(*) eklmnjdklfgm
select count(*) [eklmnjdklfgm]
select count(*)
```
The first 3 examples returns **eklmnjdklfgm**... | Why COUNT(*) is equal to 1 without FROM clause? | [
"",
"sql",
"sql-server-2008",
"count",
"sql-server-2012",
""
] |
```
CREATE VIEW dbo.myview1 As
SELECT
a.Id ,
a.Name ,
a.Age ,
CASE
WHEN b.PmtSched ='Monthly' THEN 12
WHEN b.PmtSched ='Quarterly' THEN 4
WHEN b.PmtSched ='Semi-Annual' THEN 2
WHEN b.PmtSched ='Annually' THEN 1
ELSE 12
END AS ABC,
SUM(a.Amount) *50 as TotalAmount ,
(a.AmtSpent - TotalAmount) * ABC as ... | Yes, you can use it and you don't need neither subqueries, nor CTEs. It's a simple [CROSS APPLY](https://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396). It's quite elegant and doesn't hurt readability. If you need more information, read [here](http://sqlmag.com/blog/tip-ap... | The simple solution to your problem is to repeat the expression, use a subquery, or use a CTE.
However, the more intelligent method is to add a reference table for payment schedules. This would look like:
```
create table PaymentSchedules (
PaymentScheduleId int identity(1, 1) primary key,
ScheduleName varcha... | Can alias column used in a view for calculation in some other column? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I'm pretty good at SQL but I haven't done this in a while.
I have a simple table with a common string:
```
TableName = ExampleTable1
ColumnName = ExampleColumn1
```
I have a string like this:
```
MYSTRING_10_TB_EXAMPLE1
MYSTRING_120_TB_EXAMPLE2
```
I have this query:
```
select ExampleColumn1, replace(ExampleColu... | Use `REPLACE` to trim away the first part of the string as you've already done.
Use `CHARINDEX` to find (in the resulting string) the position of the first `_`
Then use `LEFT` to keep only the left part of the string up to (but excluding) the first `_`
```
SELECT
ExampleColumn1,
LEFT( REPLACE(ExampleColumn1,... | Use `SUBSTRING_INDEX()` function.
This query:
```
SELECT SUBSTRING_INDEX(
SUBSTRING_INDEX('MYSTRING_120_TB_EXAMPLE2','_',2),
'_', -1);
```
will return `120` | Replace or trim string in SQL | [
"",
"sql",
"string",
""
] |
My table `myTab` has the column `startDate`, which has the datatype "DATE". The data in this column are stored like `dd.mm.yyyy`.
Now I'm trying to get data with this query:
```
SELECT * FROM myTab WHERE startDate like '%01.2015"
```
Somehow it doesn't work and I don't know why.
Hope someone can help. | To make a text search on the date you would have to convert the date to text.
It's more efficient if you calculate the first and last date for what you want to find and get everything between them. That way it's done as numeric comparisons instead of a text pattern match, and it can make use of an index if there is on... | ```
SELECT * FROM myTab WHERE TO_CHAR(startDate,'dd.mm.yyyy') LIKE '%01.2015'
``` | Oracle use LIKE '%' on DATE | [
"",
"sql",
"oracle",
"date-comparison",
""
] |
I have a string which contains data as follows:
```
'ID,MASTER_ID,DATA_SOURCE_ID,DATA_SOURCE_NAME,CHILD_COUNT,CHILD_COUNT_TEXT,PARENT_OR_CHILD,RECORD_TYPE,FULL_NAME_LNF,FULL_NAME_FNF,FIRST_NAME,LAST_NAME,PREFIX,SUFFIX,MIDDLE,TITLE,NAME_OF_ORGANIZATION,NAME_OF_BUSINESS,TYPE_OF_ENTITY,ADDRESS,CITY,STATE,PROVINCE,POSTAL_... | You are looking for this. It gives you your desired result
```
SELECT mycol, CONCAT('L.', mycol) AS newCol
FROM(SELECT * FROM test WHERE mycol REGEXP
'DATA_SOURCE_ID|LAST_MODIFIED_BY|LAST_MODIFIED_DATE|ATTRIBUTE[0-9]+')
as temp
```
**EXPLANATION**
```
SELECT * FROM test WHERE mycol REGEXP
'DATA_SOURC... | You can try like this:
```
replace( replace(myString, 'DATA_SOURCE_ID', 'yourReplaceValue1'), 'LAST_MODIFIED_BY', yourReplaceValu2).....
```
This `.....` is for you to make the similar replace for the rest of your replacing strings :) | Find and Replace a strings in oracle | [
"",
"sql",
"oracle",
"replace",
"oracle10g",
""
] |
Below is the requirement, can you help me to get desired query..
```
create table sales(Order_ID number, item varchar2(20));
insert into sales values (10, 'RICE');
insert into sales values (10, 'WATER');
insert into sales values (10, 'SALT');
insert into sales values (20, 'TOMATO');
insert into sales values (20, 'ONI... | Use the `row_number()` analytic function plus a case statement in order to only populate the order\_id for the first row:
```
select case when rn = 1 then order_id end order_id,
item
from (select order_id,
item,
row_number() over (partition by order_id order by item) rn
f... | I usually do it in **SQL\*Plus** and it is all about **formatting your output**.
You could use **BREAK ON *column\_name***.
For example,
```
SQL> break on deptno
SQL> SELECT deptno, ename FROM emp order by deptno;
DEPTNO ENAME
---------- ----------
10 CLARK
KING
MILLER
20 J... | Oracle Query with null values | [
"",
"sql",
"oracle",
""
] |
I am trying to access outputs from a database.
> Question : how many songs were released during each decade with classification of Pop music.
> How exactly can I output all the songs in different decades in one single query search.
The desired output should be different columns with all the songs from different decad... | Another alternative:
```
Select
sum(if(ReleaseYear < 1970, 1, 0)) as before1970,
sum(if(ReleaseYear >= 1970 AND ReleaseYear <= 1980, 1, 0)) as before1980
from Songs where classification = 'Pop'
``` | You can try something like this
```
SELECT
SUM(CASE WHEN ReleaseYear < 1970 THEN 1 ELSE 0 END) AS BEFORE1970,
SUM(CASE WHEN ReleaseYear BETWEEN 1970 AND 1980 THEN 1 ELSE 0 END) AS BEFORE1980
FROM Songs
WHERE Classification = 'Pop'
``` | How to return Multiple outputs from a database as different columns in SQL | [
"",
"mysql",
"sql",
""
] |
I am building an Oracle APEX application in which journalists can bring in articles, which a director selects for a broadcast, along with a newsreader (who can read the articles if the broadcast is created). I am kind of stuck with the following:
I would like to create an Oracle SQL query which selects the first and ... | Okay, so eventually, I was able to solve it. In my last update, the only lasting problem was that some variables weren't send to the next page. I wasn't able to find the root cause of the problem, so I did a workaround.
The only variable that was sent normally to the next page is P91\_UITZENDING (the PK of Uitzending)... | Do not use timestamps. se a date field, which includes date and time,
more info about date fields in oracle:
[Oracle Data types, see paragraph Overview of DATE Datatype](http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#i1847) | Oracle SQL: check if time is between two instances (excluding dd/mm/yyyy) | [
"",
"sql",
"oracle",
"time",
"oracle-apex",
""
] |
There are popular case, where is needed to select a row with max value (or min or whatever else aggregate function result) from a table. My case is more complex - it adds `JOIN` into the picture.
Here is an example:
```
CREATE TABLE spacecraft (
id serial PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE launch... | Assuming you want all columns from `spacecraft` in the result, plus the latest `launch` and the `success` of the same row.
Faster for few launches per spacecraft:
```
SELECT s.*, l.last_launch, l.success
FROM spacecraft s
LEFT JOIN (
SELECT DISTINCT ON (spacecraft_id)
spacecraft_id, started AS last_l... | If you want to get only max of success, so you have add a condition to filter only success. and using [Window Functions](http://www.postgresql.org/docs/9.4/static/tutorial-window.html) as you did:
```
select spacecraft.* , max(started) over (partition by spacecraft.id)
from spacecraft
left outer join
launc... | How to query row with max value in a column in a referencing table? | [
"",
"sql",
"postgresql",
"join",
"greatest-n-per-group",
""
] |
I am trying to automate a process of detaching and dropping a database (via a VBS objshell.run) If I manually use SSMS to detach and drop I can then copy to database files to another location... however if I use:
```
sqlcmd -U sa -P MyPassword -S (local) -Q "ALTER DATABASE MyDB set single_user With rollback IMMEDIATE"... | The MSDN Documentation on [DROP DATABASE](https://msdn.microsoft.com/en-us/library/ms178613.aspx) has this to say about dropping the database without deleting the files (under General Remarks):
> Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the dat... | Use SET OFFLINE instead of SET SINGLE\_USER
```
ALTER DATABASE [DonaldTrump] SET OFFLINE WITH ROLLBACK IMMEDIATE; DROP DATABASE [DonaldTrump];
``` | Drop DB but don't delete *.mdf / *.ldf | [
"",
"sql",
"sql-server-2008",
"sqlcmd",
""
] |
I can't seem to find out how to get the functionality I want. Here is an example of what my table looks like:
```
EmpID | ProjectID | hours_worked |
3 1 8
3 1 8
4 2 8
4 2 8... | You can do a basic query to get the grouped hours and use that as a basis for the rest, either in a CTE or as a subquery. For example, as a subquery:
```
SELECT *
FROM
(SELECT EmpID, ProjectID, SUM(hours_worked) as HoursWorked
FROM WorkHours
GROUP BY EmpID, ProjectID) AS ProjectHours
JOIN Projects
ON ... | You might want to use `OVER (PARTITION BY)` so you won't have to use `GROUP BY`:
```
Select a.EmpID
,W.ProjectID
,W.SUM(hours_worked) OVER (PARTITION BY W.EmpID,W.ProjectID)
,E.FirstName
FROM WorkHours W
INNER JOIN Projects P ON WorkHours.ProjectID = Projects.ProjectID
INNER JOIN Employees E ON WorkHours.EmpID = Emplo... | Multiple grouped items | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.