Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Let's say we have this silly query:
```
Select * From Emp Where Id In (Select Id From Emp)
```
Let's do a small modification inside `IN` condition by adding an `Order By` clause.
```
Select * From Mail Where Id In (Select Id From Mail Order By Id)
```
Then we are getting the following error:
> ORA-00907: missing r... | Consider the condition `x in (select something from somewhere)`. It returns true if `x` is equal to any of the `something`s returned from the query - regardless of whether it's the first, second, last, or anything in the middle. The order that the `something`s are returned is inconsequential. Adding an `order by` claus... | It would not make sense to sort the values inside the **IN** clause. Think in this way:
```
IN (a, b, c)
```
is same as
```
IN (c, b, a)
```
IS SAME AS
```
IN (b, c, a)
```
Internally Oracle applies **OR** condition, so it is equivalent to:
```
WHERE id = a OR id = b OR id = c
```
Would it make any sense to ord... | Using Order By in IN condition | [
"",
"sql",
"oracle",
"syntax-error",
""
] |
NOTE, this is a homework question.
Please show the department number and the lowest salary in the department whose average salary is the highest average salary.
This is what I have so far,
```
SELECT DEPARTMENT_ID, MAX_AVG_SALARY
FROM
(SELECT DEPARTMENT_ID, AVG(SALARY) AS MAX_AVG_SALARY
FROM EMPLOYEES
GROUP BY... | ```
SELECT MINIMUM_SALARY,DEPARTMENT_ID
FROM
(
SELECT AVG(SALARY) AS AVERAGE_SALARY,
MIN(SALARY) AS MINIMUM_SALARY,
DEPARTMENT_ID
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
)EMPLOYEE_AGGREGATED
WHERE
AVERAGE_SALARY = (SELECT MAX(AVG(SALARY)) FROM EMPLOYEES GROUP BY DEPARTMENT_ID)
``` | Solution with [analytic functions](http://oracle-base.com/articles/misc/analytic-functions.php):
```
select department_id, ms min_salary
from (
select department_id, max(avg(salary)) over () mav,
min(min(salary)) over (partition by department_id) ms,
min(avg(salary)) over (partition by departme... | ORACLE SQL: Show the lowest salary in the department with the highest average salary | [
"",
"sql",
"oracle",
""
] |
I have been looking through for answers for this question, and am still struggling.
```
Location Cashier TXN Date Product Date Time Ref
Toronto Z 15-01-04 15-01-04 090501 Transaction was a very
Toronto Z 15-01-04 15-01-04 090501 intresting one
NewYork X 1... | [Sample SQL Fiddle](http://sqlfiddle.com/#!6/6d498/1)
You can combine using STUFF and Group BY. Assuming you are using SQL Server.
```
Select location,Cashier,[Time],
stuff((SELECT distinct ', ' + cast(ref as varchar(500))
FROM t t2
where t2.location = t1.location
FOR XML PATH('')),... | well if you are using oracle you can use listagg
```
SELECT location, cashier, txn_date, product_date, time LISTAGG(ref, '; ') WITHIN GROUP (ORDER BY ref) as "ref_list"
FROM mytable;
``` | SQL two records, should be one | [
"",
"sql",
"join",
""
] |
(The following is a highly simplified description of my problem. The company policy does not allow me to describe the actual scenario in any detail.)
The DB tables involved are:
```
PRODUCTS:
ID Name
---------
1 Ferrari
2 Lamborghini
3 Volvo
CATEGORIES:
ID Name
----------
10 Sports cars
20 Safe ... | Here is the query. You should insert a list of selected cars Ids `pc.ProductId in (1,3)` and in the end you should correct condition to selected cars count so if you select 1 and 3 you should write `HAVING COUNT(DISTINCT pc.ProductId) = 2` if you select 3 cars then there have to be 3. This condition in `HAVING` give yo... | (This basically elaborates on @valex's answer, though I didn't realise that until I posted; please accept @valex's not this one).
---
This can be done using only joins and aggregation.
Build a join tree mapping locations to products, as normal. Then join it with the list of desired products (one-column values rows) ... | Postgres array query | [
"",
"sql",
"postgresql",
""
] |
I'm sorry to ask such a basic question, but I cant for the life of me spot the error here as far as I can see everything is correct. Yet I get the error, perhaps I need a pair of fresh eyes to have a look
> You have an error in your SQL syntax; check the manual that
> corresponds to your MySQL server version for the r... | There is no `WHERE` clause in the correct syntax of the [`INSERT` statement](http://dev.mysql.com/doc/refman/5.7/en/insert.html).
Depending on what you want to achieve, choose one of the following.
### Insert a new row, don't bother if another one having the same `event_id` already exists
```
INSERT INTO expiredEven... | Don't use where in insert statment, instead of just get the data from the respective tables which contains the exact records and insert necessary rows alone by adding your conditions in the select statement of that query.
Here is the simple one to resolve your error,
```
$sql="INSERT INTO expiredEvents
(event_id... | mysql error in WHERE clause | [
"",
"mysql",
"sql",
""
] |
I need to remove duplicates from a table that looks like this:
```
id post_author post_title
-----------------------------------------------------------------------------
21319 1 Youngstown State University
20535 1 Yo San University of Traditional Chinese Medicine
3... | You could set a condition on `post_author = 1` where there are more than one `post_title` with a temporary table:
```
CREATE TEMPORARY TABLE t_del AS SELECT post_title
FROM t
GROUP BY post_title
HAVING count(post_title)>1;
DELETE FROM t ... | You could use the `exists` operator:
```
DELETE FROM my_table t
WHERE post_author = 1 AND
EXISTS (SELECT *
FROM my_table s
WHERE t.post_title = s.post_title AND
s.post_author != 1)
``` | Removing duplicates in an SQL database on a condition | [
"",
"mysql",
"sql",
"sql-delete",
""
] |
I have a table, [Customer], which has [postcode] and [totalValue] fields.
I need to design a query that returns the first two characters of all [postcode], and then a SUM of the [totalValue] for that particular postcode group (so one value each for NW, L1, etc.).
I have this code, which is running fine:
```
SELECT L... | You can use `LIKE`:
```
where postcode like '[A-Z][A-Z0-9][0-9]%'
```
You might also want to check the length and other characteristics, but this answers your specific question.
EDIT:
For a separate entry, use `case`:
```
SELECT (CASE WHEN postcode like '[A-Z][A-Z0-9][0-9]%'
THEN LEFT(postcode, 2)
... | Your assumptions about valid postcodes is slightly out
> A valid UK postcode is always either one or two letters followed by a number (e.g. LE1, L12, etc.).
In its simplest terms the [valid formats for a UK Postcode](http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom) are:
```
+----------+-----------------... | Struggling with SQL Where filter | [
"",
"sql",
"sql-server",
""
] |
**I converted an RDD[myClass] to dataframe and then register it as an
SQL table**
```
my_rdd.toDF().registerTempTable("my_rdd")
```
**This table is callable and can be demonstrated with following command**
```
%sql
SELECT * from my_rdd limit 5
```
**But the next step gives error, saying Table Not Found: my\_rdd**
... | Make sure to import the implicits.\_ from the same SQLContext. Temporary tables are kept in-memory in one specific SQLContext.
```
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
my_rdd.toDF().registerTempTable("my_rdd")
val my_df = sqlContext.sql("SELECT * from my_rdd LIMIT 5")
my_df.collect().fore... | I found it easy to cause problems with temptables if there is more than one open zeppelin session, either in your own browser, or from someone else using the same server. The variable sqlContext is shared across those sessions and its easy to overwrite the value of it. | SparkSQL error Table Not Found | [
"",
"sql",
"scala",
"apache-spark",
"cassandra",
""
] |
We can try to get max age simply by using
```
SELECT TOP 1 age FROM Head1 ORDER BY Age DESC
```
But I've tried using while loop in SQL Server
**code**
```
declare @a int, @m int, @maxo int;
set @maxo = 0;
while(@a<10)
begin
select name, @m = age from head1 where ID = @a;
if @m>@maxo
@maxo = @m;
s... | ```
declare @a int, @m int, @maxo int
declare @name NVARCHAR(100)
set @maxo = 0;
while(@a<10)
begin
select @name = name, @m = age from head1 where ID = @a;
if @m>@maxo
SET @maxo = @m;
set @a=@a+1;
END
PRINT @name + ',' + CAST(@maxo AS NVARCHAR(50))
```
**ALTERNATE WAY IS**
```
SELECT Name, Ag... | There are two issues:
**Issue 1:**
The error which you are getting is self explanatory ie, you cant select the column while you are assigning the values to the variable.
You can resolve it like this:
```
select @name = name, @m = age from head1 where ID = @a;
```
**Issue 2:**
In this I dont think you need that qu... | Gettin error in SQL Server while finding out max age in a table | [
"",
"sql",
"sql-server",
""
] |
I have a table containing records all with a create date. I want to Select all the records created in January 2014 and have a count of how many were created each day. I've gotten as far as Selecting all the records created that month but I'm unsure how to proceed to get an output of all the days that month and a count ... | Is this what you are looking for? It is an aggregation query that does the count:
```
SELECT CAST(CREATE_DATE as Date) as date,
COUNT(*)
FROM WORK_ORDER
WHERE DATEPART(year, CREATE_DATE) = 2014 and DATEPART(month, CREATE_DATE) = 01
GROUP BY CAST(CREATE_DATE as Date)
ORDER BY CAST(CREATE_DATE as Date) ;
```
The... | ```
SELECT DATEPART(day,CREATE_DATE), count(*)
FROM WORK_ORDER
WHERE DATEPART(year,CREATE_DATE) = 2014 and DATEPART(month,CREATE_DATE) = 01
group by DATEPART(day,CREATE_DATE)
ORDER BY CREATE_DATE ASC
``` | Get a count of a number of records with same create date | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I am trying to use case and like statement. When I run this below query it is duplicating results on some rows where it is y on particular columns. I am using SQL Server 2000.
```
SELECT DISTINCT [rjvn_pound_reference]
,t_reference
,t_street_name
,t_zone_name
,(
CASE
WHEN rjvn_note... | Because the column references in the query are not qualified (to indicate *which* table they are returned from), and because we don't have a schema definition to go through to sort it out... we can't tell what table the `rjvn_note` column comes from.
As far as getting "duplicate" rows, the most likely explanation is a... | Try this:
```
SELECT [RJVN_POUND_REFERENCE],
T_REFERENCE,
T_STREET_NAME,
T_ZONE_NAME,
DECODE(MAX(CASE WHEN RJVN_NOTE LIKE '%CORRESPONDENCE%' THEN 1 ELSE 0 END), 1, 'Y', 'N') AS CORRESPONDENCERECEIVED,
DECODE(MAX(CASE WHEN RJVN_NOTE LIKE '%review form complete%' THEN 1 ELSE 0 END), 1, 'Y', 'N') AS REVIEWFORMC... | Using case and like statment without duplicate results | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I would like to use Now() to get current date and time, so trying to create a function, just cannot get syntax right
```
USE [db1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[Now]()
RETURNS [date] AS
BEGIN
Declare @Now1
Select GetDate()
-- Return the result of th... | You don't need to create your own function to get current date, you can use
```
Select GetDate()
```
just kidding :) I imagine that you want to do something more than returning only current date
Type the body this way:
```
Declare @Now1 datetime
Select @Now1 = GetDate()
```
so your full code should be
```
USE ... | This seems completely ridiculous and pointless but you are making this way more complicated than it needs to be.
```
create function Now()
returns datetime as
begin
return getdate()
end
select dbo.Now()
``` | Function for Using Now instead of GetDate in SQL Server 2012 | [
"",
"sql",
"sql-server",
""
] |
I need to count a value (`M_Id`) at each change of a date (`RS_Date`) and create a column grouped by the `RS_Date` that has an active total from that date.
So the table is:
```
Ep_Id Oa_Id M_Id M_StartDate RS_Date
--------------------------------------------
1 2001 5 1/1/2014 1/1/2014
1 ... | If using SQL SERVER 2012+ you can use `ROWS` with your the analytic/window functions:
```
;with cte AS (SELECT RS_Date
,COUNT(DISTINCT M_ID) AS CT
FROM Table1
GROUP BY RS_Date
)
SELECT *,SUM(CT) OVER(ORDER BY RS_Date ROWS BETWEEN UNBOUNDED PRECEDING AND CUR... | You need a cumulative sum, easy in SQL Server 2012 using Windowed Aggregate Functions. Based on your description this will return the expected result
```
SELECT p_id, RS_Date,
SUM(COUNT(*))
OVER (PARTITION BY p_id
ORDER BY RS_Date
ROWS UNBOUNDED PRECEDING)
FROM tab
GROUP BY p_id, RS_Date
``` | SQL Server : count types with totals by date change | [
"",
"sql",
"sql-server-2008",
"count",
"cumulative-sum",
""
] |
I have encountered a weird problem in a MySQL query. This following query is returning me 0 result whereas there are many rows which should be returned. the query is
```
SELECT DISTINCT SKU, EAN, URL, CID
FROM tab_comp_data
WHERE status =''
```
And in many rows there are NULL values in STATUS column but it retur... | I you want to query for `NULL` values, you should use the `IS NULL` operator.
So, your query should look like:
```
SELECT DISTINCT SKU, EAN, URL, CID
FROM tab_comp_data
WHERE status IS NULL
``` | if the value of status is null you have to use `is null`. That is different from `=''`
```
select DISTINCT SKU, EAN, URL, CID from tab_comp_data WHERE status is null
``` | NULL values in where condition is not working | [
"",
"mysql",
"sql",
"select",
"null",
""
] |
I have multiple tables, related by multiple foreign keys as in the following example:
* `Recipes(id_recipe,name,calories,category)` - `id_recipe` as PK.
* `Ingredients(id_ingredient,name,type)` - `id_ingredient` as PK.
* `Contains(id_ingredient,id_recipe,quantity,unit)` - `(id_ingredient,id_recipe)` as PK, and as Fore... | This is the general form of the kind of query you need:
```
SELECT *
FROM tableA
WHERE tableA.ID NOT IN (
SELECT table_ID
FROM ...
)
;
```
-- EXAMPLE BELOW --
The subquery gives the id values of all recipes that the "lactic" ingredient is used in, the outer query says "give me all the recipes not in that list"... | A common solution of this type of question (checking conditions over a set of rows) utilizes aggregate + CASE.
```
SELECT R.Name
FROM Recipes R
INNER JOIN Contains C
on R.ID_Recipe = C.ID_Recipe
INNER JOIN Ingredients I
on C.ID_Ingredient = I.ID_Ingredient
GROUP BY R.name
having -- at least one 'lactic' ingredient
... | Incomprehensible query behaviour | [
"",
"mysql",
"sql",
"database",
""
] |
How can I count the number of occurrences in a given column?
Follow this example. With a table like this:
```
+----------+---------+------+
| PersonID | Name | City |
+----------+---------+------+
| 1 | John | NY |
| 2 | Mohit | CA |
| 3 | Jay | AZ |
| 4 | Roger | NY ... | It's as simple as this.
```
SELECT *,
cityCounter = ROW_NUMBER() OVER (PARTITION BY city ORDER BY personID)
FROM yourTable
ORDER BY personID
``` | If I understand correctly, you just want to enumerate the values for each city and then sort by `id`:
```
select t.*
from (select t.*,
row_number() over (partition by city
order by personid) as CityCounter
from table t
) t
order by personid;
``` | ROW_NUMBER over column result | [
"",
"sql",
"sql-server",
"t-sql",
"window-functions",
""
] |
I have a query that I want to add some log to, to drop results that successfully match when I add one more table to the JOIN.
I'm accomplishing this now with an additional WHERE IN statement instead:
```
SELECT blah blah FROM donation
WHERE donation.id NOT IN (SELECT donation_id FROM donation_relation)
```
I just wo... | `LEFT OUTER JOIN` alternative:
```
SELECT blah blah
FROM donation
LEFT JOIN donation_relation ON donation.id = donation_relation.donation_id
WHERE donation_relation.donation_id IS NULL;
```
Probably faster, especially when MySQL.
`EXISTS` version:
```
SELECT blah blah FROM donation
WHERE NOT EXISTS (SELECT donat... | The common way in Standard SQL uses correlated NOT EXISTS (additionally NOT IN might have some non-intuitive side-effects when NULLs are involved):
```
SELECT blah blah FROM donation as d
WHERE NOT EXISTS
(SELECT * FROM donation_relation as dr
where dr.donation_id = d.donation_id)
``` | "Exclude" results with an SQL WHERE or JOIN? | [
"",
"mysql",
"sql",
""
] |
Hi there I am trying to execute a query but cannot seem to get it right.
```
SELECT *
FROM table
WHERE id IN (SELECT *
FROM table
WHERE description = 'A')
AND description = 'B'
```
Above is the query that I have got, the `select * from table where description = A` works as expected w... | You will be getting multiple columns from the sub query when I assume you only want the id column:
```
SELECT *
FROM table
WHERE id IN (SELECT id
FROM table
WHERE description = 'A')
AND description = 'B'
``` | No need for the select in the where clause
```
SELECT *
FROM table
WHERE id IN ('A', 'B')
``` | SQL select statement in where clause | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
"where-clause",
""
] |
Is it possible for Oracle to reuse the result of a function when it is called in the same query (transaction?) without the use of the function result cache?
The application I am working with is heavily reliant on Oracle functions. Many queries end up executing the exact same functions multiple times.
A typical exampl... | Add an inline view and a `ROWNUM` to prevent the Oracle from re-writing the query into a single query block and executing the functions multiple times.
---
**Sample function and demonstration of the problem**
```
create or replace function wait_1_second return number is
begin
execute immediate 'begin dbms_lock.s... | You can try the `deterministic` keyword to mark functions as pure. Whether or not this actually improves performance is another question though.
**Update:**
I don't know how realistic your example above is, but in theory you can always try to re-structure your SQL so it knows about repeated functions calls (actually ... | Oracle performance: query executing multiple identical function calls | [
"",
"sql",
"oracle",
"performance",
"function",
""
] |
I want to group data based on the time interval, let us say group of 3 hours. How can I group a data within a time frame of data.
My data is like
```
DocId, UserCode, ProcessCode, ProcessDone
1 1 10 21/11/2015 11:04:00
2 1 10 21/11/2015 12:14:00
3 ... | Try this way:
```
select UserCode, ProcessCode, count(1) Total
from tab
where convert(time,ProcessDone) between '10:00' and '12:00'
group by UserCode, ProcessCode
```
**[Sql Fiddle](http://sqlfiddle.com/#!6/ac293/6/0) Demo**
or
```
select UserCode, ProcessCode, count(1) Total
from tab
where DATEPART(hh,ProcessDo... | You should group by parsed date parts
```
select
DATEPART(YEAR,ProcessDone),
DATEPART(MONTH,ProcessDone),
DATEPART(DAY,ProcessDone),
DATEPART(HH,ProcessDone),
UserCode,
ProcessCode,
count(1) Total
from tab
group by UserCode,
ProcessCode,
DATEPART(YEAR,ProcessDone),
DAT... | SQL Server: How to group by a datetime column based on a time interval (Such as within 2 hours) | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"group-by",
""
] |
I know the title does not understand anything. But I would not know how to define it better.
I will explain more my problem.
I have 2 tables. A which in its interior has the following values:
Name table: battle
```
res1 res2 winner
225 552 552
```
In the second table I have:
Name table: fighters
```
ID nam... | You need to have three aliases of table fighters for the desired output. Please see below query:
```
Select f1.name as Fighter-1,
f2.name as Fighter-2,
f3.name as Winner
From
battel b,
fighters f1,
fighters f2,
fighters f3
Where
b.res1 = f1.id AND
b.res2 = f2.... | There's no need for three joins as the winner will always be one of the two opponents, so you simply need to do a CASE:
```
select f1.name as name1, f2.name as name2,
case when b.winner = b.res1 then f1.name else f1.name end as winner
from battle b
join fighters f1
on b.res1 = f1.id
join fighters f2
on b.res2... | Query for multiple column with multiple values but in the different table with same column | [
"",
"mysql",
"sql",
"inner-join",
""
] |
well i'm still new in oracle, i'm trying to query a table with a subquery..it looks like this
```
select id_user, count(*) as jumlah from (select * from users where username = 'usr' and pass = 'pwd' and company_id = 'PAN' and status = 1)
group by id_user;
```
the above code works. but when i try to put it inside a s... | Add one more variable below the line
```
the_sql varchar(200);
```
as
```
yid_user users.id_user%TYPE;
```
and change your execute immediate as
```
execute immediate the_sql into yid_user, the_count;
```
Also some tips for using variable types in Oracle:
```
1. VARCHAR is obsolete, use VARCHAR2 instead.
2. Inste... | Your query returns 2 columns, but there's only one column defined in INTO. | Oracle 00932. 00000 - "inconsistent datatypes: expected %s got %s" | [
"",
"sql",
"oracle",
"stored-procedures",
"ora-06512",
""
] |
I have the following table structure:
```
id int -- more like a group id, not unique in the table
AddedOn datetime -- when the record was added
```
For a specific `id` there is **at most** one record each day. I have to write a query that returns contiguous (at day level) date intervals for each `id`.
The expected re... | Here's answer without any fancy joining, but simply using group by and row\_number, which is not only simple but also more efficient.
```
WITH CTE_dayOfYear
AS
(
SELECT id,
AddedOn,
DATEDIFF(DAY,'20000101',AddedOn) dyID,
ROW_NUMBER() OVER (ORDER BY ID,AddedOn) row_num
FROM ... | In `Sql Server 2008` it is a little bit pain without `LEAD` and `LAG` functions:
```
WITH data
AS ( SELECT * ,
ROW_NUMBER() OVER ( ORDER BY id, AddedOn ) AS rn
FROM ( VALUES ( 0, GETDATE()), --dummy record used to infer column types
( 1,... | Determine contiguous date intervals | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
In MySQL `SELECT 2+NULL FROM tbl_name` will return `NULL`, since MySQL cannot interpret `NULL` as a number.
But why will `SELECT SUM(quantity) FROM tbl_name` not return `NULL` if just one of the values is `NULL`? The same goes for `MIN`, `MAX`, `AVG`, etc. Since MySQL doesn't know what NULL could be, shouldn't it retu... | This is a good question, and one that does not have a good answer. The treatment of `NULL` in your two examples is different.
The fundamental problem is what `NULL` means. Commonly, it is used to denote *missing* values. However, in the ANSI standard, it stands for an *unknown* value. I'm sure philosophers could devot... | According to the [MySQL Reference](https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html), NULL values are ignored in the aggregate functions. Here is the direct quote from the page:
> Unless otherwise stated, group functions ignore NULL values. | Sum, Avg, Max, Min, Count of NULL values | [
"",
"mysql",
"sql",
"null",
"sum",
""
] |
I am trying to save an old stored procedure into a string. When I use the following I do not get any line breaks.
```
SELECT @OldProcedure = Object_definition(object_id)
FROM sys.procedures
WHERE name = @ProcedureName
```
Any suggestions on how to get the stored procedure text with the line breaks?
I was thinking... | Two ways:
```
select name, object_definition(object_id)
from sys.procedures
```
or
```
select object_name(p.object_id), definition
from sys.sql_modules as m
join sys.procedures as p
on m.object_id = p.object_id
``` | I've recently come across the same question and made a quick and dirty script to get the definition of views, but the very same thing could also work for stored procedures and functions.
```
DECLARE @Lines TABLE (Line NVARCHAR(MAX)) ;
DECLARE @FullText NVARCHAR(MAX) = '' ;
INSERT @Lines EXEC sp_helptext 'sp_Procedure... | Get the text of a stored procedure in SQL Server | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have table booking in which I have data
```
GUEST_NO HOTEL_NO DATE_FROM DATE_TO ROOM_NO
1 1 2015-05-07 2015-05-08 103
1 1 2015-05-11 2015-05-12 104
1 1 2015-05-14 2015-05-15 103
1 1 2015-05-17 2015-05-20 101
2 ... | I think a good way to do this would be grouping by guest\_no, hotel\_no and room\_no, and sorting by the maximum (i.e. most recent) booking date in each group.
```
SELECT
guest_no,
hotel_no,
room_no,
COUNT(1) AS BookingCount
FROM
booking
GROUP BY
guest_no,
hotel_no,
room_no
ORDER BY
... | Maybe this is what you're looking for?
```
select
guest_no,
hotel_no,
room_no,
count(*) as Count
from
booking
group by
guest_no,
hotel_no,
room_no
order by
min(date_to) desc
```
Or maybe max() instead of min(). SQL Fiddle: <http://sqlfiddle.com/#!6/e684c/3> | SQL query to group by data but with order by clause | [
"",
"sql",
"sql-server",
""
] |
In my SQL Server 2008, a stored procedure `P_ABC` is scheduled to run everyday at 2 a.m.
But how can I verify that this procedure `P_ABC` is scheduled to run everyday at 2 a.m. or not and it is always running at 2 a.m.? Is there any query to get the lists of procedures that are scheduled to run at specific time? | It's too old question but still I am posting this. You can try -
```
CREATE PROCEDURE MyTask
AS
BEGIN
SET NOCOUNT ON;
-- For executing the stored procedure at 11:00 P.M
declare @delayTime nvarchar(50)
set @delayTime = '23:00'
while 1 = 1
begin
waitfor time @delayTime
begin... | Not sure this is exactly what you need but you can check this piece of code below.
You can also find it there:
[SQL Server Find What Jobs Are Running a Procedure](https://stackoverflow.com/questions/11828733/sql-server-find-what-jobs-are-running-a-procedure)
```
SELECT j.name
FROM msdb.dbo.sysjobs AS j
WHERE EXI... | How to check if the stored procedure is scheduled to run at specific time | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
"scheduled-tasks",
""
] |
I currently have a table named `DATA` it has entries like the following:
```
abc000
ab000cde
000abc
```
I just want to remove all 0 from beginning and the end. If 0 comes in between the character then it will remain same. | This also works for leading and trailing zeros at the same time:
```
declare @s varchar(15) = '00abc00efg000'
select substring(@s,
patindex('%[^0]%', @s),
len(@s)-patindex('%[^0]%', reverse(@s))-patindex('%[^0]%', @s)+2);
```
Description: this is substring from first nonzero symbol... | Say your data exists in column called `Col1`, then this expression should do it
```
select CASE
WHEN RIGHT(col1 , 1) = '0'
THEN SUBSTRING(col1,0,PATINDEX('%[A-Z1-9]%',REVERSE(col1)))
WHEN LEFT(col1 , 1) = '0'
THEN SUBSTRING(col1,PATINDEX('%[A-Z1-9]%',col1),LEN(col1))
... | How to remove the begining and ending characters if those are '0' in SQL Server | [
"",
"sql",
"sql-server",
""
] |
```
SN DATE
=========== =========
111 1/1/2014
222 2/1/2014
333 3/1/2014
111 4/1/2014
222 5/1/2014
333 6/1/2015
222 7/1/2015
111 8/1/2015
333 9/1/2015
111 10/1/2015
111 1... | One method is to use `exists`:
```
select t.*
from table as t
where date between #2014-01-01# and #2014-12-31# and
exists (select 1
from table as t2
where date between #2014-01-01# and #2014-12-31# and
t2.sn = t.sn and t2.date <> t.date
);
```
However... | Try this
```
SELECT SN , Count(SN) AS Dup
FROM [TableName]
WHERE DATE BETWEEN #2014-01-01# AND #2014-12-31#
GROUP By SN
HAVING Count(SN) >1
``` | Access SQL: How to find duplicate records between dates | [
"",
"sql",
"ms-access",
"duplicates",
""
] |
Trying to use FOR XML in SQL 2012. Need to have a result like this:
```
<Loader xmlns:xsi="url1" xmlns="url2">
<Buy_New>
<Ticker>IBM</Ticker>
<Acct>12345</Acct>
<Qty>10</Qty>
</Buy_New>
<Sell_New>
<Ticker>MSFT</Ticker>
<Acct>12345</Acct>
<Qty>15</Qty>
</Sell_New>
<Buy_New>
<Ticker... | **Refined Answer** (based on @JonC's suggestion to use CAST, but without needing a separate table to hold all the different possibilities for tags)
```
SELECT
(
SELECT
CAST('<' + t1.RecordType + '>' +
CAST(
(
SELECT
t2.Portfolio1 AS 'Portfolio',
... | I'm not sure about the condition to determine if the tag should be 'buy\_new' or 'sell\_new', but this may work for you:
```
SELECT
(
SELECT
Investment1 as Investment,
EventDate1 as Date,
Quantity1 as Quantity
FROM #temptable e1 where e1.temp_id = e.temp_id
AND (SOME CONDITION FOR 'Buy_New'... | SQL Server FOR XML PATH vary tags dynamically | [
"",
"sql",
"sql-server",
"xml",
""
] |
Let's say I have 2 tables (`tb1`, `tb2`) with both the following schema:
```
CREATE TABLE tb1 (
col1 INT NOT NULL,
col2 TEXT NOT NULL,
col3 TEXT NOT NULL,
col4 REAL
);
```
How do I find records of `tb1` which are not present in `tb2` on columns `col1`, `col2`, `col3`?
I researched on [this](https://stackover... | Try `NOT EXISTS` instead, of course performance might depend on existing indexes...
```
SELECT *
FROM tb1
WHERE NOT EXISTS
(
SELECT *
FROM tb2
WHERE
tb1.col1 = tb2.col1 AND
tb1.col2 = tb2.col2 AND
tb1.col3 = tb2.col3
)
``` | How about something like:
```
SELECT *
FROM tb1
WHERE NOT EXISTS (SELECT * FROM tb2
WHERE tb1.col1 = tb2.col1
AND tb1.col2 = tb2.col2
AND tb1.col3 = tb2.col3)
``` | Find records on multiple fields not in another table | [
"",
"sql",
"sqlite",
""
] |
I'm taking a intro to database class right now. For a homework assignment I was given a piece of SQL code and told to just run some queries and give the results back. The problem is I can't even build the schema given with the code my teacher gave me. Here is this code:
```
CREATE TABLE emp (
name char(15),
dno in... | It may be part of the exercise for you to figure this out. However, assuming that it is not, here are important observations:
* The foreign key reference should be to a primary key, and neither table has primary keys.
* The table being referenced has to be defined before it can be referred to.
You can work on fixing ... | The definition of the first table (emp) has a reference to a table that has not yeat been created (dept).You have to create first 'dept' to create a foreign key of it into another table.
Execute the queries in this order:
```
CREATE TABLE dept (
dno int,
location char(30)
);
CREATE TABLE emp (
name char(15),
... | Cannot add foreign key constraint SQL when building schema | [
"",
"mysql",
"sql",
"foreign-keys",
""
] |
I've got a table called **tblRoutes** that holds a unique list of from and to routes (f = from; t = to):
```
| fCity | fState | tCity | tState |
|========|========|========|========|
|New York| NY | Miami | CA |
|Houston | TX |New York| NY |
...
```
And then I have a table called **tblCarrierRates*... | I believe you are looking for an equivalent of the Sql Server and Oracle Analytic / Windowing functions like `ROW_NUMBER() OVER (PARTITION .. ORDER BY)`, e.g. [like so](http://sqlfiddle.com/#!6/a1c1a/2).
Although this isn't directly offered in MS Access, I believe it is possible to simulate a row numbering function in... | Your Inner Query needs to group by city and state. This will produce the 1 per city state that allows the outer join to join on those fields.
Debug your inner query independently until you see the results you would expect for your outer query to work. Take out the Top1 at first so you can see that the sorting and grou... | How to select the TOP 1 record per group (Partition) | [
"",
"sql",
"ms-access",
"ms-access-2010",
"ms-access-2013",
""
] |
In my query I have following part of the code:
```
CASE WHEN Field1 LIKE '%choice1%' OR Field1 LIKE '%Choice1%' .... THEN 'category 1'
WHEN Field1 LIKE '%choicea%' OR Field1 LIKE '%Choiceb%' .... THEN 'category 2'
END AS 'Cats'
```
I have numerous of those choices (1line about 20), (2line about 15 and son on).
... | If those choices are already known, put them in a table and use a join:
```
SELECT Field1, c.Category
FROM MainTable
LEFT JOIN Choices c ON Field1 LIKE ('%' + c.Choice + '%')
```
**Update:**
If there are sub-strings inside one category, add a `DISTINCT` to this query. | I think your using SQL for something it isn't designed for. Having that many like statements is going to cause your query to absolutely devastate the resources on the SQL server, and when you get more rows than a demo db you are going to have a runtime that makes your users cry.
If you need this kind of information yo... | SQL CASE LIKE with multiple choices | [
"",
"sql",
"sql-server",
"t-sql",
"case",
"sql-like",
""
] |
I'm trying to combine these two stored procedures so that it returns the values of both under their own headings/columns so the results are as followed "Support Hours Worked" "Support Hours Charged" "Development Hours Worked" and "Development Hours Charged"
Query One
```
USE [Database]
GO
/****** Object: StoredProce... | Welcome to the wonderful world of SQL! Hopefully the below code will help you out.
Basically create a query with the common select between the two queries and use a case statement to filter out further the unique results you want from both the queries:
```
WITH cte AS (
SELECT
DATEPART(Year, StartTime) AS Yea... | You can define 2 CTEs in one query, and then join them up on the UserID like this:
```
USE [Database]
GO
/****** Object: StoredProcedure [dbo].[usp_JobTimeSystem_FetchSupport] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_JobTimeSystem]
@FromDate date... | How can I combine these two stored procedures | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have got few sales offices, together with their sales. I am trying to set-up report that will basically tell how is each office performing. Getting some SUMs, COUNTs are quite easy, however I am struggling with getting rank of single office.
I would like to have this query return the rank of single office, during th... | You just need to wrap your code as derived table or use a `CTE` like this and then do the filter for `OfficeName = 'XYZ'`.
```
;WITH CTE AS
(
SELECT OfficeName, SUM(Value) as SUM,
RANK() OVER (ORDER BY SUM(VALUE) DESC) AS Rank
FROM Transactions t
JOIN Office o ON t.TransID=o.ID
WHERE OfficeName NOT IN ('GGG','QQQ')
G... | if i understand you correctly you want to do:
```
SELECT *
FROM (
SELECT OfficeName, SUM(Value) as SUM,
RANK() OVER (ORDER BY SUM(VALUE) DESC) AS Rank
FROM Transactions t
JOIN Office o ON t.TransID=o.ID
WHERE OfficeName NOT IN ('GGG','QQQ')
GROUP BY OfficeName
) dat
WHERE OfficeName = 'XYZ';
``` | SQL RANK with multiple WHERE clause | [
"",
"sql",
"t-sql",
"select",
""
] |
Could you please explain me why it is necessary to specify those foreign keys when creating tables?
I mean, I've created two tables which have a one-to-many relationship (on the ER-diagram) but I didn't specify the foreign keys and references. I can connect the tables using the where-clause and even perform joins and s... | It is not *necessary* to specify foreign key relationships. It is just a good idea.
When you specify the relationship, the database ensures relational integrity. That is, it ensures that the values in the foreign key column are legitimate values.
In addition, the `cascade` options on foreign keys are a big help when ... | The reason it's necessary is to ensure [data integrity](http://en.wikipedia.org/wiki/Data_integrity).
Suppose you have a table called `orders`, and a table called `order details`, both have a column called `order id`.
If you don't use foreign keys you might be inserting order details for an order that doesn't exist... | Why is it necessary to explicitly specify foreign keys and references in databases? | [
"",
"mysql",
"sql",
"foreign-keys",
"foreign-key-relationship",
""
] |
I have two tables:
Table 1 which the fields
```
o_id (Fk),
dt
```
I have Table 2
```
o_id (Fk),
attr1 (Number)
```
My objective is count how many occurrences of attr1 occur where the value is from 0-10, 11-20, 21+. I then need to take these occurrences and Group them by dt from Table 1
To make it more clear I pro... | You don't need subqueries. This will do what you seem to want:
```
SELECT
t1.dt,
count(CASE WHEN attr1 BETWEEN 0 AND 10 THEN 1 END),
count(CASE WHEN attr1 BETWEEN 11 AND 20 THEN 1 END),
count(CASE WHEN attr1 > 20 THEN 1 END),
FROM
table1 t1
JOIN table2 t2
ON t1.o_id = t2.o_id
GROUP BY
t1... | The issue is that you don't join the tables in the subqueries, but in any case this query can be done as a conditional aggregation which at least I would think look a bit better:
```
SELECT
t1.dt,
SUM(CASE WHEN attr1 BETWEEN 0 AND 10 THEN 1 ELSE 0 END) AS "count(0-10)",
SUM(CASE WHEN attr1 BETWEEN 11 AND 2... | Get counts based on a group of dates | [
"",
"sql",
"oracle11g",
""
] |
Consider the following MySQL table schema:
```
id int,
amount decimal,
transaction_no,
location_id int,
created_at datetime
```
The above schema is used to store POS receipts for restaurants. For getting daily report of count of receipts & their sum. tried following query:
```
SELECT location_id,count(distinct(trans... | How do you count a transaction that is repeated on *multiple* days?
I presume that you actually do *not* want to count a transaction, simply because it is the last one on the day, if there is another receipt on the next day. You can get the final record for each transaction in several ways. A typical way is to use `gr... | You can get sum up the amounts for just the last `created_at` value within the same day by joining to an inline view that determines the last `created_at` for each `transaction_no` in that day.
This avoids simply using `sum(distinct ...` because otherwise two different transactions with the same amount, if such exist,... | SQL Query for sum of unique amounts, remove duplicates | [
"",
"mysql",
"sql",
"select",
"distinct",
""
] |
I have a problem understanding how the combination of `NOT EXISTS` and subqueries works.
I understand that by adding `NOT EXISTS`, the query will return all the rows the subquery will not. What I don't understand is how it works when we use it in the following case.
```
+-------------+--------+
| id_employee | salary... | `NOT EXISTS` is usually used with a Correlated Subquery, i.e. there's a relation between the Outer and the Inner query (and you can't run the subquery code on its own without a "table not found" error). Your example is correlated but in a strange way.
Logically it's processed like this:
for each row in the employee t... | Since you are specifying no other condition in your subquery than:
```
F.salary > E.salary
```
You are getting any row from `E` where there is no other entry in `F` that has a salary greater then it. Since both `E002` and `E004` have a salary of `1001`, and no one else has a salary greater then `1001`, both `E002` a... | Confusion with NOT EXISTS and subqueries | [
"",
"mysql",
"sql",
"database",
""
] |
I am looking for the best way to build a query which would hide the record (row) in the event that three field values (in three different columns) would be null. The code below is giving me a syntax run time error message of 3075. Also, I am not sure if it is causing a problem but the code below is executed from a main... | This will return the data if not all three columns are NULL:
```
where not (col1 is null and col2 is null and col3 is null)
```
This is the same after applying algebra of logic: return the row if any of the three rows is NOT NULL
```
where col1 is not null or col2 is not null or col3 is not null)
``` | In a general sense, in a table of N columns, you can explicitly count the number of NULL columns in a table and then add them up and compare the count of nulls to `3` in a where predicate:
```
SELECT *
FROM MyTable x
WHERE
((IIF(x.COL1 IS NULL, 1 , 0) +
IIF(x.COL2 IS NULL, 1 , 0) +
IIF(x.COL3 IS... | Hiding a row in a table with a query when 3 columns have null values | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2010",
""
] |
I have a company table and a licence table. I need to insert a new row in the license table for every company in the company table that isn't already in the license table.
`License (ID,CompanyID,LicenseStart,LicenseEnd,CreatedDate,AddUser,UpdateUser,UpdateDate,TemplateId)`
The ID in this table is incremented by 1 when... | `license.id` is an identity column, so you do not need to insert it.
```
insert into license (CompanyID, LicenseStart, LicenseEnd)
select c.id, GetDate(), DATEADD(day, 14, GETDATE())
from company c
where not exists (select 1
from license l
where c.ID = l.CompanyI... | Do an `INSERT` with `SELECT`, use `NOT EXISTS` to make sure no existing company is inserted again. Something like:
```
insert into license (ID,CompanyID,LicenseStart,LicenseEnd,CreatedDate,AddUser,UpdateUser,UpdateDate,TemplateId)
select ID, theCompanyID, GetDate(), DATEADD(day,14,GETDATE()), null,null,null,null null
... | SQL - Insert new row into an existing table based on another table entry | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
What is wrong with this query:
```
SELECT AVG(price) as AVG_price FROM
(
(SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model = PC.model)
UNION ALL
(SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model)
)
```
It gives the following error:
> Incorrect syntax near ')' | Try This..
```
SELECT AVG(d.price) as AVG_price FROM
(
SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model = PC.model
UNION ALL
SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model
) as d
``` | Alias the derived table and converted to SQL-92 ANSI standards.
```
SELECT AVG(price) as AVG_price FROM
(
SELECT price FROM PC INNER JOIN Product on Product.model = PC.model
WHERE maker = 'A'
UNION ALL
SELECT price FROM Laptop INNER JOIN Product on Product.model = Laptop.model
WHERE maker = 'A'
) B
``` | Select from (select union all select) error | [
"",
"sql",
"sql-server",
""
] |
I have simple scala application with spark dependencies. I am just trying to create spark context using the follwing code.
```
def main(args: Array[String]) {
var sparkConfig : SparkConf = new SparkConf() ;
sparkConfig.setAppName("ProxySQL").setMaster("local");
var sc = new SparkContext(sparkConfig)
... | The problem was more or less related with conflicting dependencies.
The following task resolve my issue.
> Go to Project
>
> Build Path -> Order and Export tab -> Change the order of
> javax.servlet jar
> either to bottom or top.
This Resolved the problem. | Well,as I follow the suggestion:Go to Project Build Path -> Order and Export tab -> Change the order of javax.servlet jar either to bottom or top.
I find my buidpath libiaries was changed and it seems mussy(too many small libs),maybe this was caused by maven.
So I try to remove all of them and reimport the libs and c... | Scala with spark - "javax.servlet.ServletRegistration"'s signer information does not match signer information of other classes in the same package | [
"",
"sql",
"scala",
"apache-spark",
""
] |
I have a table and would like to find minimum and maximum values of price.
I would like to get minimal price from action\_table when current date between "from" and "to".
```
from to action_price price
2015-04-02 2015-08-02 20 25
2015-04-02 2015-04-20 0 30
2015-04-03 2015-0... | If I understand correctly, you want minumum and maximum of these values:
> ~~25~~ 20, 30, 40
You simply need to wrap the case statement inside the aggregate functions instead of other way round:
```
SELECT
MIN(CASE WHEN CURDATE() BETWEEN `from` AND `to` THEN action_price ELSE price END) AS `min`,
MAX(CASE WHEN CURDA... | I think a "HAVING" statement will work here:
<http://sqlfiddle.com/#!9/4653c/4> | Conditional select between dates | [
"",
"mysql",
"sql",
"date",
"datetime",
"between",
""
] |
I would like to use `INNER JOIN` on one table. But I get this error message:
> Msg 208, Level 16, State 1, Line 1
> Invalid object name 'a'.
My query is :
```
select *
from
(select
*,
ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row
from [SarMem].[dbo].[Book_Data1]
where GoodN... | Do it with cte:
```
;with a as(select *, ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row
from [SarMem].[dbo].[Book_Data1]
where GoodName like '%A%' and GroupCode = 115)
select * from a
join a b on b.GoodMainCode = a.GoodMainCode
where a.row > 0 and a.row <= 100
``` | I think here `a` is an alias name not the table name. So SQL SERVER won't allow `a` to create one more alias `b`.
So if you wanna use same table as `a`, then you have to rewrite subquery for `b` also.
Like,
```
select * from (
select *,ROW_NUMBER() OVER (ORDER BY GoodMainCode) as row from [SarMem].[dbo].[Book_Data1]... | Self-join a table in SQL Server 2008 | [
"",
"sql",
"sql-server",
""
] |
I have a university graduate database and would like to extract a random sample of data of around 1000 records.
I want to ensure the sample is representative of the population so would like to include the same proportions of courses eg

I could do t... | You want a stratified sample. I would recommend doing this by sorting the data by course code and doing an nth sample. Here is one method that works best if you have a large population size:
```
select d.*
from (select d.*,
row_number() over (order by coursecode, newid) as seqnum,
count(*) ov... | It is not necessary to partition the population at all.
If you are taking a sample of 1000 from a population among hundreds of course codes, it stands to reason that many of those course codes will not be selected at all in any one sampling.
If the population is uniform (say, a continuous sequence of student IDs), a ... | SQL random sample with groups | [
"",
"sql",
"sql-server",
"sample",
"random",
""
] |
I have following table (master\_group) structure :
```
code name under
1 National Sales Manager 1
2 regional sales manager 1
3 area sales manager 2
4 sales manager 3
```
How do I get the ultimate parent of a particular row like :
```
code ... | With recursive cte going from top to childs:
```
with cte as(
select *, code as ultimate from t where code = under
union all
select t.*, c.ultimate from t
join cte c on c.code = t.under
where t.code <> t.under
)
select * from cte
```
For data:
```
create table t (code int, name varchar(100), under int)
ins... | You can use a recursive CTE to walk the tree and then choose the highest level for each code:
```
with cte as (
select mg.code, mg.name as name, mg.under as under, mg.under as parent, 1 as lev
from master_group mg
union all
select mg.code, mg.name, mg.under, cte.under as parent, cte.lev + 1
... | SQL Server function to get top level parent in hierarchy | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a stored procedure, which I've temporarily filled with values that returns the time spent on logged jobs at my company, I've grouped the JobTypeID's that should fit into 4 different Columns, Dev hours worked, Dev hours charged, Support hours worked, and Support hours charged. Upon running the code procedure, due... | Apologies this didn't work first time round, You can use the following which should now give you the result you're looking for:
```
WITH cte AS (
SELECT
DATEPART(Year, StartTime) AS YearNumber,
DATEPART(Month, StartTime) AS MonthNumber,
DateName(Month, StartTime) + ' ' + CAST(DatePart(Year, Start... | Use sum on the columns with nulls, or you will lose results, then group by date | Combing two returned rows in SQL | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have a PostgreSQL database. What I'm asking is when I have a table where `A`, `B` and `C` are the column names and the other numbers beyond are the values:
```
A | B | C
---------
0 | 1 | 2
1 | 2 | 3
2 | 1 | 3
0 | 3 | 2
```
And my search requires that the row must contain `1` and `3` the valid rows would be row 2 a... | Just use two `in` statements:
```
select *
from table t
where 1 in (A, B, C) and 3 in (A, B, C);
``` | @GordonLindoff's answer works for testing equality. If you have to use LIKE, however, you'll have to use regular logic:
```
WHERE ((A LIKE '%1%' AND (B LIKE '%3%' OR C LIKE '%3%'))
OR (B LIKE '%1%' AND (A LIKE '%3%' OR C LIKE '%3%'))
OR (C LIKE '%1%' AND (A LIKE '%3%' OR B LIKE '%3%')))
```
Bear in mind that ... | SQL Create Statement for Multiple Columns Containing all Given Values | [
"",
"sql",
"database",
"postgresql",
""
] |
I have a business problem that I formulated to the following example for easier communication.
Say I have three tables `Employee`, `Project`, `EmpWorkProj`. `EmpWorkProj` is used to link employees and the projects they worked on (or link table between `Employee` and `Project`). This is an example of the table data:
Tab... | You can solve this using `group by` and `having`. For each employee, count the number of projects they are in with NY as the city. Then, in the `having` clause, see if that is all the projects:
```
select ewp.employeeid
from EmpWorkProj ewp join
Project p
on ewp.projectid = p.projectid
where p.projectcity = ... | This also works:
```
declare @e table(EmployeeID int, EmpName varchar(10))
declare @p table(ProjectID int, ProjectCity varchar(10))
declare @ep table(EmployeeID int, ProjectID int)
insert into @e values
(1 , 'Alex'),
(2 , 'Pete'),
(3 , 'Mike')
insert into @p values
(11, 'NY'),
... | Get records that match all corresponding records on conditional join | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
## Question:
For each month in 2014, display the total profit (i.e. using the attributes purchasedPrice and agreedPrice) generated from car sales only.
Tables:
## Car
```
(VIN, dateAcquired, yearBuilt, purchasedPrice, askingPrice, currentMileage, modelNo)
```
## Sales Transaction
```
(VIN, custID, agentID, dateOf... | Some issues:
* The profit is made when you sell the car (not when it is aquired).
* You need to `SUM` all the profits to get the total profit.
* When using `GROUP BY`, you need to `SELECT` either the exact statements in the `GROUP BY` or use aggregate functions.
Like this:
```
SELECT TRUNC( s.dateOfSale, 'MM' ) AS m... | Columns in `SELECT` list which are not aggregate functions should match your group by expression accurately.
This means `c.dateacquired` does not equal `extract(month from c.dateacquired)`, thus giving you the error.
You would like to group by months, yet you try to select the exact, not truncated `date`.
Correct co... | Oracle find total profit for each month in a certain year | [
"",
"sql",
"oracle",
""
] |
Essentially, I have an `orders` table and each day I'm running a cronjob to check the logs and see which customers ordered 11 months ago, because I need to warn them that their warranty expires in 1 month. What's the best way this query is accomplished?
I could do it a few ways, but I'm interested in seeing opinions o... | ```
SELECT *
FROM orders
WHERE order_date = CURDATE() - INTERVAL 11 MONTH
;
```
This will find all rows with order\_date value exactly 11 months old. | I'd use [`date_add`](https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add) with a month `interval` and compare it to `now()`:
```
SELECT *
FROM orders
WHERE DATE_ADD (order_date, INTERVAL 11 MONTH) <= NOW()
``` | Query MySQL Datetime Field For Any Records Made 11 Months Ago | [
"",
"mysql",
"sql",
"datetime",
"select",
""
] |
I have an Excel sheet that looks as given below:
```
+---------+----------------+
| ItemNum | Substitutes |
+---------+----------------+
| ABCD | XXXX/YYYY/ZZZZ |
| PQRS | AAAA/BBBB/CCCC |
+---------+----------------+
```
I need to load this into a table in MS Access or SQL Server in the following way:
```
... | Import the data as is, then you can use this query to split them down:
```
SELECT T1.ItemNum, T2.mySplits as Substitute
FROM
(
SELECT *,
CAST('<X>'+replace(T.Substitutes,'/','</X><X>')+'</X>' as XML) as my_Xml
FROM Table1 T
) T1
CROSS APPLY
(
SELECT my_Data.D.value('.','varchar(50)') as mySplits
FROM T1.... | You should take a staging table approach. Because you have this tagged for both SQL Server and Access, here are two options.
If you *know* the codes are always the same length, then put the data in a staging table and extract with something like:
```
select ItemNum, substring(substitutes, 1, 4) as substitute
from sta... | How to load a column with multiple values into separate lines into a table | [
"",
"sql",
"sql-server",
"excel",
"ms-access",
""
] |
The question may be very simple but i don't know how to fix it,
I have this table structure
```
sno left Right
1 2 1
2 2 2
3 1 2
4 3 1
5 2 4
6 7 1
7 2 8
```
How do I get a result set like the one below
```
sno left Right Result
1 2 1 1
2 ... | One of the possible solutions:
```
DECLARE @t TABLE ( sno INT, l INT, r INT )
INSERT INTO @t
VALUES ( 1, 2, 1 ),
( 2, 2, 2 ),
( 3, 1, 2 ),
( 4, 3, 1 ),
( 5, 2, 4 ),
( 6, 7, 1 ),
( 7, 2, 8 )
SELECT *,
(SELECT MIN(v) FROM (VALUES(l),(r)) m(v)) AS m
FROM @t
```
Ou... | The following SQL will return the positive value of a subtraction operation between the left and right values - in a column with Result as the header. It will calculate the difference between left and right values - ABS will make the result positive.
```
SELECT
sno,
left,
Right,
ABS(left - right) AS Re... | Select Query on Sql Server | [
"",
"sql",
"sql-server-2008",
""
] |
I am running a SQL query with a while constraint containing some "id's".
For example:
```
SELECT table.id
FROM TableOne table
WHERE table.id IN (1, 2, 3, 4)
AND some conditions
```
The query might return [1, 2] granted that some conditions are met. How would I go about returning [3, 4], that is, all the id's that hav... | If this is how you get result of ID you want to include and meet condition
```
SELECT table.id
FROM TableOne table
WHERE table.id IN (1, 2, 3, 4)
AND some conditions
```
Then, this is how to get result of ID you want to include but not meet condition
```
SELECT table.id
FROM TableOne table
WHERE table.id IN (1, 2, 3... | You can create a table with list of your ids and then do a `EXCEPT` from your query.
```
SELECT ID FROM
(
SELECT 1 ID
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
)List
EXCEPT
SELECT table.id
FROM TableOne table
WHERE table.id IN (1, 2, 3, 4)
AND some conditions
```
***Assumption:*** If your table does ... | SQL - remainder / not belonging | [
"",
"mysql",
"sql",
"sql-server",
"database",
"where-clause",
""
] |
My problem is auto populating Table.
I have table with 1000 record in it, but for testing purpose, i need to insert more data.
**ID | PersonID | Date | Time | Sum | TypeID | PlaceID | StatusID**
So i need to populate the database with 10000 records where the date is between 1/3/2015 and 1/5/2015, Time is Random, SUM ... | You need a small t-sql to do it:
```
--CREATE TABLE TEST (CID INT, PERSONID INT, TEST_DATE DATE, TEST_TIME TIME, TEST_SUM INT, TYPEID INT, PLACEID INT, STATUSID INT);
--TRUNCATE TABLE TEST;
SET NOCOUNT ON;
DECLARE @X INT, @PERSONID INT, @DATE DATE, @TIME TIME, @SUM INT, @TYPEID INT, @PLACEID INT, @STATUSID INT,@R INT;... | Here is some brutal solution but completely randomized:
```
with rows as(select row_number() over(order by(select null)) as dummy from
(values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t1(n)
cross join (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t2(n)
cross join (values(1),(1),(1... | Auto Populate Table With Date Range SQL | [
"",
"sql",
"sql-server",
""
] |
So, the problem is that report on SSRS is executing immediately after opening. I use query based default parameters.. And i saw the solution with adding additional parameter without default value. It doesn't work for me because of the textbox which cannot be hidden (i tried to hide it and report stop working).
So is th... | The problem is happening because you are setting a required parameter as nullable or you are giving it a default value that is invalid. To fix the problem, remove the default values. When you go to the report it will not be able to run until you give it the required value(s). | There can be two solutions to it.
1. Set the default of the parameter in question to such a value that would absolutely have no matches in dataset. Say for example, the parameter is Location. Give the defalut value as "Mars". (Unless of course you build software of extra terrestrial beings). This way the report will e... | SSRS how to show report without executing it immediately | [
"",
"sql",
"reporting-services",
"rdl",
""
] |
I have two tables category and adverts, i need to select all categories and the number of adverts it has in the adverts table that has at least count greater than zero
the category table
```
cat_id | Name
----------------
1 | Toys
2 | fashion
3 | electronics
```
The adverts table
```
cat_id ... | If you want to make sure that the `cat_id` from `category` table are in `adverts` table you need to join as
```
select
c.cat_id,
c.Name,
count(a.cat_id) as `count`
from category c
join adverts a on a.cat_id = c.cat_id
group by c.cat_id ;
``` | ```
select cat_id, count(*)
from adverts
group by cat_id;
```
So the mySQL query engine will grab every single row from the adverts table, it'll put them into neat piles where all rows in the pile have the same category, it'll count the number of rows in each pile, and then it'll return to you a result row for each pi... | select count items each group | [
"",
"mysql",
"sql",
""
] |
I am trying to rename a column in `MySQL` community server `5.5.27` using this SQL expression:
```
ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;
```
I also tried
```
ALTER TABLE table_name RENAME old_col_name TO new_col_name;
```
But it says:
> Error: check the Manual that corresponds to your ... | Use this query:
```
ALTER TABLE tableName CHANGE oldcolname newcolname datatype(length);
```
The `RENAME` function is used in `Oracle` databases.
```
ALTER TABLE tableName RENAME COLUMN oldcolname TO newcolname datatype(length);
```
---
[@lad2025](https://stackoverflow.com/a/49925232/4762528) mentions it below, bu... | In Server version: 5.6.34 MySQL Community Server
```
ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name data_type;
``` | Rename a column in MySQL | [
"",
"sql",
"mysql",
"rename",
"alter",
""
] |
I'm currently trying to answer the following question:
Display the name of the customer who has purchased the most cars from Archie’s Luxury Motors.
Tables I'm working with:
**Customer**
```
(custID, name, DOB, streetAddress, suburb, postcode,
gender, phoneNo, email, type)
```
**SalesTransaction**
```
(VIN, custI... | Probably this should work:
```
select * from (
select customer.name
from customer, salestransaction
where customer.custID = salestransaction.custID
group by (salestransaction.custID), customer.name
order by count(*) desc
) where rownum=1
``` | Easiest way utilizes a RANK:
```
select customer.name, st.cnt
from customer
join
(
select
custid,
count(*) as cnt,
rank() over (order by count(*) desc) as rnk
from salestransaction
group by custid
) st
on customer.custid = st.custid
where st.rnk = 1;
``` | Oracle display customer who purchased most cars | [
"",
"sql",
"oracle",
"group-by",
""
] |
I have locations in longitude and latitude coordinates. My goal is eventually to be able to select all rows from myTable Where distance is less than 2km.
1. How can one use the longitude and latitude to store location within a geography column?(because it's supposed to be only one geographic point not two right? not o... | > How can i use the longitute and latitute to store location within a geography column?(because it's supposed to be only one geographic point not two right? not one for longitute and one for latitute?)
You can use [`geography::STPointFromText`](https://msdn.microsoft.com/en-us/library/bb933979.aspx) / [`geography::Poi... | You can convert lat and long to a point and save it in table.
```
Declare @geo Geography,
@Lat varchar(10),
@long varchar(10)
SET @Lat = '34.738925'
SET @Long = '-92.39764'
SET @geo= geography::Point(@LAT, @LONG, 4326)
``` | How to store longitude & latitude as a geography in sql server 2014? | [
"",
"sql",
"sql-server-2014",
""
] |
I need a solution for the scenario below:
```
TABLE A:
col1
1
-1
6
-5
2
4
-2
5
```
I want the OUTPUT as:
```
POSITIVE NEGATIVE
1 -1
2 -2
4 NULL
5 -5
6 NULL
``` | You can try something like:
```
SELECT t1.col1 AS POSITIVE, t2.col1 AS NEGATIVE
FROM (
SELECT col1
from tableA
WHERE col1 > 0 ) t1
FULL OUTER JOIN (
SELECT col1
FROM tableA
WHERE col1 < 0 ) t2 ON t1.col1 = ABS(t2.col1)
ORDER BY ABS(COALESCE(t1.col1, t2.col1))
```
[**SQL Fiddle Demo**](http://sqlfidd... | This correlated subquery does what you want using [`ABS`](https://technet.microsoft.com/en-us/library/ms189800%28v=sql.110%29.aspx):
```
SELECT POSITIVE = a1.col1,
NEGATIVE = (SELECT TOP 1 a2.col1
FROM TableA a2
WHERE a2.col1 < 0
AND ABS(a2.col1) = a1.... | Need to get the output as positive and negative numbers from one column into different columns from a single table | [
"",
"sql",
"sql-server-2008",
""
] |
I have a large database with a lot of tables and I want to know if I can select the table that have less columns of them. How can I do that? Is there some info in the `INFORMATION_SCHEMA`? | I feel like the other answers gave you plenty of info to help you answer your own questions with a little effort, but you don't seem satisfied, so maybe this helps.
If this isn't what you're looking for, you really need to edit your question so we can understand exactly what type of result you want.
This returns a si... | This will give you the list of tables and the count of columns for each table
```
SELECT TABLE_NAME,
COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS col INNER JOIN
sys.objects obj
ON obj.name = col.TABLE_NAME
WHERE obj.type = N'U'
GROUP BY col.TABLE_NAME
``` | How to select the table with less columns in a database with Sql Server | [
"",
"sql",
"sql-server",
""
] |
I need to generate a table with the date values that look like this:
```
01/31/2015
02/28/2015
03/31/2015
04/30/2015
....
12/31/2015
```
Each value represents the last day of each month. What is the best approach to accomplish this? | @sDate is the starting date, @eDate is the ending date.
```
declare @sDate datetime,
@eDate datetime
select @sDate = '2013-02-25',
@eDate = '2013-04-25'
;with cte as (
select convert(date,left(convert(varchar,@sdate,112),6) + '01') startDate,
month(@sdate) n
union all
select dateadd(m... | ```
SELECT MonthEnd = DATEADD(ms, -3, DATEADD(m, DATEDIFF(m, 0, GETDATE()) + 1 + A.N, 0))
FROM (VALUES -- Feel free to replace this with some sort of numbers table
(0), (1), (2), (3), (4), (5)
) A (N)
``` | How to generate a table, where each row represents the last day of each month? | [
"",
"sql",
"sql-server-2008",
""
] |
I needed guidance and help with a question I have never done in SQL SERVER.
I have this data:
```
Cust_Nr Date FilmName
157649306 20150430 Inside Llewyn Davis
158470722 20150504 Nick Cave: 20,000 Days On Earth
158467945 20150504 Out Of The Furnace
158470531 20150504 FilmA
157649306 ... | You can do this with conditional aggregation and window/analytic functionality:
```
SELECT *,CASE WHEN [Date] < MIN(CASE WHEN FilmName = 'Gladiator'
THEN [Date]
END) OVER(PARTITION BY Cust_Nr)
THEN 1
ELSE 0
... | You need agregation and details in the same query, so use a Windowed Aggregate Function:
```
case
when Date < min(case when FilmName = 'Gladiator' then Date end)
over (partition by Cust_Nr)
then 1
else 0
end
``` | purchased a movie earlier than Gladiator date SQL SERVER | [
"",
"sql",
"select",
"sql-server-2012",
"row",
"rank",
""
] |
i have a table with these value, and here is a small sample
```
order state item id
10064315 ON MCM1L162L116
10064315 ON MCM1R162R116
10064315 ON SHIPPING
10064316 MS 00801-1778
10064316 MS SHIPPING
10064317 AZ CHM110439-1
10064317 AZ SHIPPING
10064318 TX 2607
10064318 TX SHIPPI... | ```
SELECT DISTINCT [order]
FROM MYTABLE
WHERE [order] not in (SELECT [order]
FROM MYTABLE
WHERE [item id] = 'SHIPPING')
```
EDIT:
According to Aaron Bertrand's article (hat tip @TTeeple in the comments) the best performance for this problem (needing the distinct) is don... | One option is to use `not exists`:
```
select ordernumber
from yourtable y
where not exists (
select 1
from yourtable y2
where y.ordernumber = y2.ordernumber and y2.itemid = 'SHIPPING'
)
``` | SQL exclude all rows that with have certain value? | [
"",
"sql",
"sql-server",
""
] |
Consider the relation account (customer, balance) where customer is a primary key and there are no null values.
I would like to rank customers according to decreasing balance. (The customer with the largest balance gets rank 1. Ties are not broke but ranks are skipped: if exactly two customers have the largest balance... | Let's try this [Example](http://sqlfiddle.com/#!9/e7e62/23)
**Ranking without skipping a rank**
```
set @number:=0;
set @balance:=0;
select customer, balance, rank
from (
select
*,
@number:=if(@balance=balance, @number, @number+1) as rank,
@balance:=balance
from account
order by balance
) as ran... | This has nothing to do with the count.
You are doing a join between A and B and show only the records where A.balance < B.balance since there is no such record for your top rank customer (by definition there is no account with higher balance) you don't get any record.
This should do the trick
```
select A.customer, ... | Why is count(column_name) behaving like this? | [
"",
"mysql",
"sql",
"database",
"group-by",
""
] |
I currently want to do some sort of conditional union. Given the following example:
```
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
```
Say I wanted to only union the second statement if the count of 'users' was >=2 , otherwise do not union the two.
In summary I want to append a table wi... | You could use an ugly hack something like this, but I think [Tim's answer](https://stackoverflow.com/a/30327097/3094533) is better:
```
SELECT age, name
FROM users
UNION ALL
SELECT 25, 'Betty'
WHERE (SELECT COUNT(*) FROM users) > 1;
``` | If it's in a stored-procedure you could use `If...Else`:
```
IF (SELECT COUNT(*) FROM users) < 2
BEGIN
SELECT age, name
FROM users
END
ELSE
SELECT age, name
FROM users
UNION ALL
SELECT 25 AS age, 'Betty' AS name
```
Otherwise you could try something like this:
```
SELECT age, name
FROM ... | Case statement to determine if I should union | [
"",
"sql",
"sql-server",
"sql-server-2012",
"case",
"union",
""
] |
I have two tables
```
Table 1 Table 2
|leadid|Location| |leadid|leadstatus|
|---------------| |-----------------|
|1 |Japan | |1 | Hired |
|2 |China | |2 | Failed |
|3 |Korea | |3 | Hired |
|4 |Japan | |4... | This should work for you:
```
SELECT Location, COUNT(*) as Interview,
SUM(CASE WHEN leadstatus = 'Hired' THEN 1 ELSE 0 END) as Hired,
SUM(CASE WHEN leadstatus = 'Failed' THEN 1 ELSE 0 END) as Failed
FROM table1
LEFT JOIN table2 ON table1.leadid = table2.leadid
GROUP BY Location
ORDER BY Inter... | You can use conditional sum along with ranking system using the user defined variable as
```
select
@rn:=@rn+1 as rank,
location,
interview,
hired,
failed
from(
select
t1.location,
count(*) as interview,
sum(t2.leadstatus='Hired') as hired,
sum(t2.leadstatus='Failed') as failed
... | SQL select total and split into success and failed | [
"",
"mysql",
"sql",
""
] |
So I want to select a range of rows in an Oracle DB. I need to do this because I have millions of rows in the table and I want to paginate results to the user (if you know another way to do this on the client side, I'm using JavaFX if it matters but I don't think it's a good idea to send all the datas over the network ... | You have 4 questions, and all revolve around the usage and functionality of **ROWNUM**. I will answer each question one-by-one.
> Why (this was my first attempt until I search on SO) Select \* From Person Where rownum > 100 and rownum < 110; returns 0 rows ?
Nice explanation by Thomas Kyte regarding ROWNUM and pagina... | Answer to question 2: In Oracle 12 you can use pagination
```
select owner, object_name, object_id
from t
order by owner, object_name
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;
``` | How ROWNUM works in pagination query? | [
"",
"sql",
"oracle",
"pagination",
"rownum",
""
] |
There are two types of results I want to return:
* Unread notifications
* Read notifications
If there are > 10 unread notifications available I want to select as many as there are
If there are <= 10, I want to select all (say there were 7) the unread notifications and 3 'filler' read notifications. How can I accompl... | This should help you: <http://sqlfiddle.com/#!9/e7e2a/2>
```
SELECT * FROM
(
SELECT @rownum := @rownum + 1 AS rownum, name, read
FROM notifications,
(SELECT @rownum := 0) r --initialise @rownum to 0
) t
WHERE read = 0 OR (read = 1 AND rownum <= 10)
ORDER BY rownum
```
The records are numbered with @rown... | What you can do is union the two results, order by most important, and then limit the Union:
```
SELECT Col1, Col2, ...
FROM
(
SELECT Col1, Col2, `read`, ... FROM notifications WHERE read = 0
UNION
SELECT Col1, Col2, `read`, ... FROM notifications WHERE read = 1
) x
ORDER BY x.`read` -- And probably a column lik... | SQL query to select minimum of 10 results | [
"",
"mysql",
"sql",
""
] |
I have a table ("table1") with 3 columns called col1, col2 and col3 (each is VARCHAR) with 4 values as shown below:
```
col1 col2 col3
datA1 datB1 datC1
datA2
```
I need an ability to add a data at any time into any column NOT affecting on the other ones. The very popular code in the Internet is that (say, we n... | I found the solution (a chain of logical operations):
1) `CHECK` if there is a cell (in the target column) with values either `""` or `NULL`.
2) `IF` it has one of those then rewrite the FIRST one keeping the values of the other cells in this row at their places (assumably we use `UPDATE`))) ).
3) `ELSE` just add a ... | ```
UPDATE table1
SET col2 = dataB2, col3 = dataC2
WHERE col1 = dataA2;
```
This may serve your purpose. | How to INSERT data into a specific column without NULLs in the other columns? | [
"",
"sql",
"postgresql",
"insert",
""
] |
Below is the SQL Server query I want to convert to MySQL:
```
SELECT SaleDetail.cTaxiNo, Category.cCarName, qryDriverExpenses.nAmount,
Sale.nInvoiceNo, Sale.cCustomerName, IIf([cPackageType] ='GENERAL',
[nProviderRate],[nProviderRate]/[nProviderKM]) AS nARate, SaleDetail.nKM,
SaleDetail.nAmount,... | `IIf` in `SQL Server` is `If` in `MySQL`
```
SELECT SaleDetail.cTaxiNo, Category.cCarName, qryDriverExpenses.nAmount,
Sale.nInvoiceNo, Sale.cCustomerName,
IF(cPackageType ='GENERAL', nProviderRate, nProviderRate/nProviderKM) AS nARate,
SaleDetail.nKM, SaleDetail.nAmount, Sale.dInvoiceDate, qryFuel.nAmount, ... | Using those sort of joins are just asking for trouble. Please study up on proper joining syntax, <https://technet.microsoft.com/en-us/library/ms191517%28v=sql.105%29.aspx>. Here is formatted query:
```
SELECT SaleDetail.cTaxiNo
,Category.cCarName
,qryDriverExpenses.nAmount
,Sale.nInvoiceNo
,Sale.cCustomerName
,CASE WH... | Convert SQL Server SQL query to MySQL | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I'm doing SQL query with Excel VBA.
Below is the SQL string that I'm using:
```
SELECT DESC, SEQNUM, INSTRUCTION FROM TABLE
WHERE DESC = 'ITEM1' AND SEQNUM <=3
```
Here is the query result:
```
DESC SEQNUM INSTRUCTION
ITEM1 1 002.000
ITEM1 2 137.000
ITEM1 3 005.000
```
How can I make... | If supported - do a self full outer join, ANSI SQL syntax here:
```
select coalesce(t1.desc, t2.desc, t3.desc),
t1.INSTRUCTION SEQNUM1,
t2.INSTRUCTION SEQNUM2,
t3.INSTRUCTION SEQNUM3
from (select * from TABLE where SEQNUM = 1) t1
full outer join (select * from TABLE where SEQNUM = 2) t2 on t1.de... | Like this, **provided there is one DESC-SEQNUM each**:
```
SELECT DESC, S1.INSTRUCTION, S2.INSTRUCTION, S3.INSTRUCTION
FROM TABLE AS S1 INNER JOIN
TABLE AS S2 ON S1.DESC = S2.DESC
INNER JOIN TABLE AS S3 ON S3.DESC=S1.DESC
```
For Access SQL you may need to enclose the INNER JOINs like mentioned here:
[SQL multiple ... | Excel VBA - How to pivot sql result | [
"",
"sql",
"vba",
"excel",
""
] |
I'm creating a foreign table (`foo_table`) in database\_a. `foo_table` lives in database\_b. `foo_table` has an enum (`bar_type`) as one of its columns. Because this enum is in database\_b, the creation of the foreign table fails in database\_a. database\_a doesn't understand the column type. Running the following in d... | I summarize the answer I received from the pgsql-general mailing list:
1. A foreign table is basically an ad-hoc remote data source for the local database, so the onus is on the local database to maintain its definition of the remote table, whether it's in another (or even the same) PostgreSQL server or a completely d... | You can create a script to transfer the enums by making this query and then create them on your server:
```
SELECT format(
'CREATE TYPE %s AS ENUM (%s);',
enumtypid::regtype,
string_agg(quote_literal(enumlabel), ', ')
)
FROM pg_enum
GROUP BY enumtypid;
```
Thanks @laurenz-albe
[Po... | SQL: error when creating a foreign table that has an enum column | [
"",
"sql",
"postgresql",
"enums",
"foreign-data-wrapper",
""
] |
I have two tables appointments and line\_items.
```
appointments
id integer primary key
price decimal
line_items
id integer primary key
price decimal
appointment_id integer foreign key
```
I need to get sum of appointments.price with sum of associated sum of line\_items price.
For example, I have 2 appointment... | This should give you what you're looking for, it seems you were close to the answer:
```
SELECT SUM(app.price + IFNULL(li.price,0)) AS total_sum
FROM appointments app
LEFT JOIN
(Select appointment_id, Sum(price) price from line_items group by appointment_id) li on li.appointment_id = app.id
``` | I think what you are looking for is a `SUM() GROUP BY` in a derived table and then a `join` with `appointments`. Something like this.
```
SELECT SUM(appointments.price + line_items.price) AS total_sum
FROM appointments
INNER JOIN
(
SELECT line_items.appointment_id,SUM(price) as price
line_items
GROUP BY appointment_... | sum column with sum of joined table | [
"",
"mysql",
"sql",
""
] |
I have two tables whose key is a zip code. I'm trying to join them, but it's inaccurate because one table has leading zeros and the other does not, so it's not matching up.
Is there a simple way to format this? I have read access only, and no write access - so physically changing the tables is not an option unfortunat... | You can "normalize" zipcodes by adding leading zeros using lpad function. It adds "padding" - in this case zeroes, so that every zipcode will have the same length. I assume that you have zipcodes of 4 or 5 characters, then this might work:
```
SELECT lpad(zipcode, 5, '0')
``` | You can use `RIGHT` function [documentations here](http://www.postgresql.org/docs/9.1/static/functions-string.html)
Which allows you to get x number of characters.
```
SELECT RIGHT('00000' || zip_code ,5)
``` | Trying to join two tables on a zip - one table has no leading zeros, the other has leading zeros | [
"",
"sql",
"postgresql",
""
] |
I have two tables `account_agent` and `bulk_index`. The data on each table is as follows
`account_agent`
```
name code account remark scheme
avi 10 151362 first as
babi 11 123478 new as
avi 10 ... | This query worked for me
```
SELECT A.name, A.code, A.Account, A.remark, A.scheme
FROM account_agent A
INNER JOIN bulk_index B ON A.account = B.account
WHERE A.scheme = 'as' AND A.code = '10'
``` | Assuming your `account` column is unique, you could just do a simple join and a where clause to get this:
```
SELECT A.name, A.code, A.Account, A.remark
FROM account_agent A
INNER JOIN bulk_index B ON A.account = B.account
WHERE a.scheme like '%as%' and a.code = '10'
--remove the preceeding or succeeding % in like a... | How to filter data on one table based on reference data on another table? | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I have following SQL
```
SELECT tsd.ID
FROM test_series_details tsd
WHERE tsd.DIV_ID =1
AND tsd.END_DATE > NOW()
AND tsd.ID NOT IN
((SELECT tsr.TEST_ID
FROM test_series_results tsr
WHERE tsr.STUDENT_ID=3)
UNION
(SELECT tsrlv.TEST_ID
FROM test_series_restore_log_viewe... | The best way to write this is as two separate clauses:
```
SELECT tsd.ID
FROM test_series_details tsd
WHERE tsd.DIV_ID = 1 AND
tsd.END_DATE > NOW() AND
tsd.ID NOT IN (SELECT tsr.TEST_ID
FROM test_series_results tsr
WHERE tsr.STUDENT_ID = 3
) AND... | Try to use `LEFT JOIN` as below
```
SELECT tsd.ID
FROM test_series_details tsd
LEFT JOIN ((SELECT tsr.TEST_ID
FROM test_series_results tsr
WHERE tsr.STUDENT_ID=3)
UNION
(SELECT tsrlv.TEST_ID
FROM test_series_restore_log_viewer tsrlv
WHERE tsrlv.STUDENT_ID=3
GRO... | MySQL , How to give output of UNION to WHERE clause | [
"",
"mysql",
"sql",
""
] |
I am trying to create some tables within a database, however the tables are not appearing in my object explorer view.
my code is as follows:
```
use testDB
GO
create table dbo.teacher (id varchar(5), name varchar(24));
insert into teacher values ('dm112', 'Magro, Deirdre');
insert into teacher values ('je232', 'Elkn... | This would happen if you have the tables node open in object explorer and don't refresh after running your DDL. It is annoying that SSMS doesn't autorefresh explorer after DDL. Refresh is available via the right-click context menu in object explorer. | I had a scenario in which refreshing the folders in Object Explorer did not lead to my missing table appearing in either of the Tables or Views folders. Like the original post, I am able to query the table - but not find it in Object Explorer.
The [Microsoft docs on the FROM clause](https://learn.microsoft.com/en-us/s... | Can't see created tables in Object Explorer - Microsoft SQL Management Studio | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
table1:
I need all the item\_id records where image\_id=1 and the item\_id appears in the table more than one time:
So, for the following table (lets call it my\_table):
```
item_id image_id
------- --------
1 1
1 5
1 6
2 1
3 1
4 1... | ```
SELECT item_id FROM my_table
WHERE image_id = 1
AND item_id IN (SELECT item_id FROM my_table GROUP BY item_id HAVING COUNT(*) > 1);
``` | One way is using `exists`
```
select
t1.item_id
from my_table t1
where t1.image_id = 1
and exists(
select 1 from my_table t2
where t2.item_id = t1.item_id
and t2.image_id <> 1
);
``` | MySql get duplicate id where other column condition | [
"",
"mysql",
"sql",
""
] |
I have the following table:
```
+------------------------------------+
| Number Name Date |
+------------------------------------+
| 1 1050 Name1 2015-01-01 |
| 2 1051 Name2 2015-04-27 |
| 3 1057 Name3 2015-04-27 |
+------------------------------------+
```
How shoul... | Try this
```
select number, name, date
from Recent_Table
where Date = (SELECT MAX(DATE) AS recent_date
FROM Recent_Table
WHERE DATE < '2015-05-19')
```
there is problem with `name` column not with `having` clause. I think you don't need `having`.
**[Sql fiddle](http://sqlfiddle.com/#!3/92... | ```
SELECT
number,
name,
DATE AS recent_date
FROM Recent_Table
WHERE DATE = (SELECT MAX(t2.DATE)
FROM Recent_Table t2
WHERE t2.number = t1.number)
``` | How do I get the most recent records based on as of date? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a sql file that I need to modify so that the ID section of a row is increased by 3. How can I increased the ID field and keep the rest of the line as it is in BASH?
Ex:
```
insert into info.names values (35, 'John', 'C', 2);
insert into info.names values (36, 'Mark', 'C', 1);
insert into info.names values (37, ... | awk is the more appropriate tool for this task
```
awk '{tmp=$5 ;sub(/^\(/, "", tmp); tmp+=3; $5="("tmp","; print $0}' file > file.new && mv file.new file
```
To explain, I'll add comments and use a more verbose format
```
awk '{
# Capture the 5th field '(35,' into a tmp variable
tmp=$5 ... | Using gnu-awk you can do this:
```
awk 'BEGIN{ FPAT="[^(]+|\\([0-9]+" } {$2="(" substr($2,2)+3} 1' file.sql
insert into info.names values (38 , 'John', 'C', 2);
insert into info.names values (39 , 'Mark', 'C', 1);
insert into info.names values (40 , 'Bob', 'C', 5);
``` | Add a number to a number located in a string in BASH | [
"",
"sql",
"bash",
"parsing",
""
] |
I have a table with 2 columns TimeStamp and ID in `MS SQLSERVER`
```
TimeStamp ID
2015-05-20 1
2015-05-20 2
2015-05-20 1
2015-05-21 1
2015-05-21 2
2015-05-21 2
2015-05-21 1
```
My requirement is to calculate number of records for every Id according to date.
Requirement:
```
D... | Using Pivot - can look like this:
```
SELECT [TimeStamp], [1] AS [No of records for Id=1], [2] AS [No of records for Id=2], [1]+[2] AS Total
FROM dbo.YourTable
PIVOT
(
COUNT(ID) FOR ID IN ([1],[2])
) pvt
ORDER BY [TimeStamp]
``` | I've got your answer using subqueries:
SQLFIDDLE: <http://sqlfiddle.com/#!3/8c28c/5>
```
SELECT DISTINCT t1.myts,
(SELECT COUNT(*)
FROM mytable t2
WHERE t2.myts = t1.myts
AND t2.id = 1) AS id_1_count,
(SELECT COUNT(*)
... | Write a query to count different kind of records in single line result | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"group-by",
"sql-server-2012",
""
] |
I have this query in SQL Server:
```
SELECT
cr.formno, cr.controlid as formid,
min(cr.series) as formstartseries,
max(cr.series) as formendseries,
(SELECT currentseries
FROM af_inventory
WHERE objid=cr.controlid) AS afi_currentseries,
(SELECT currentseries
FROM af_control
... | You cannot use your ALIASed column names in the HAVING clause. Try the following:
```
SELECT
cr.formno,
cr.controlid AS formid,
MIN(cr.series) AS formstartseries,
MAX(cr.series) AS formendseries,
(
SELECT
currentseries
FROM
af_inventory
WHERE
objid = cr.controlid
) AS afi_curr... | An alias assigned in the `SELECT` cannot be used in the `HAVING` clause because the `SELECT` phase is executed later, have a look at [Logical Query Processing](http://www.nickyvv.com/2013/02/logical-query-processing.html).
You could use a `cte` and then include a `WHERE` clause like this:
```
WITH cte
AS (
SELECT ... | Invalid column error in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This has probably been asked before, but I have no idea on how to find it in the first place.
In the following query (with respective returned values):
```
select * from tbChapter where idLesson in(12, 13)
```
-- Result --
```
id idLesson name sequence
52 12 Intro 1
53 ... | Try this:
```
select * from tbChapter where id in
(select MAX(id) from tbChapter group by idLesson)
``` | Try this:
```
select *
from tbChapter as a
where sequence = (select max(sequence)
from tbChapter as b
where a.id_lesson = b.id_lesson)
``` | How to select only one entry based on each parameter | [
"",
"sql",
"sql-server",
"database",
""
] |
I found a solution for this here,
[sql query that groups different items into buckets](https://stackoverflow.com/questions/6669730/sql-query-that-groups-different-items-into-buckets)
It works well as long as there is data for all the ranges. I want the query to return 0 if there is no data.
So if my table is:
```
it... | You need to build an inline table containing all price ranges. Then perform a `LEFT JOIN` with a derived table based on your query to get the expected result:
```
SELECT x.PriceRange, COALESCE(TotalWithinRange, 0) AS TotalWithinRange
FROM (
SELECT "0 - 10" AS PriceRange
UNION SELECT "10 - 20"
UNION SELECT "20 -... | Group by `TotalWithinRange`, so it will count each category | MySQL query to group data into different ranges | [
"",
"sql",
"postgresql",
""
] |
I have a table with duplicate item's ...
I need show the list of all columns without duplicate item's
for example i have this table:
```
ID CODE RANK TIME
1 12345 2 10:00
2 12345 2 11:00
3 98765 3 20:00
4 98765 3 ... | try this:
```
SELECT * FROM myTable WHERE ID IN(SELECT MIN(ID) FROM myTable GROUP BY Code)
``` | If there is no specific way the ID should show (just like the time column), and the ID and TIME column are always sorted that way,this should work.
`SELECT MIN(id), code, rank, MIN(time)
FROM table
GROUP BY code, rank` | SQL Show All column by one column distinct | [
"",
"sql",
"oracle",
"select",
"duplicates",
"distinct",
""
] |
How can I write query which would output this below?
```
ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"
DECLARE @x XML;
SET @x = N'<?xml version = "1.0"?>
<EVENT_INSTANCE>
<EventType>ALTER_TABLE</EventType>
<PostTime>2015-05-19T14:01:46.930</PostTime>
<SPID>52<... | Bit of a hack, but this should work:
```
DECLARE @x XML;
SET @x = N'<?xml version = "1.0"?>
<EVENT_INSTANCE>
<EventType>ALTER_TABLE</EventType>
<PostTime>2015-05-19T14:01:46.930</PostTime>
<SPID>52</SPID>
<ServerName>computer1</ServerName>
<LoginName>domain\user</LoginName>
<UserName>dbo</UserName>
<Data... | Assuming you want to get string containing all attributes of `<SetOption>` as output, one possible way is using XQuery for loop like so :
```
SELECT @x.query('
for $attr in /EVENT_INSTANCE/TSQLCommand/SetOptions/@*
(: return value in format : attribute_name="attribute_value" :)
return concat(local-name($attr)... | TSQL to get XML data into a column | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
""
] |
I have a simple table named HotelRate
```
HID | START_DATE | END_DATE | PRICE_PER_DAY
--------------------------------------
1 01/1/2015 10/1/2015 100
1 11/1/2015 20/1/2015 75
1 21/1/2015 30/1/2015 110
```
what is the most simple way to calculate pric... | Something like this should do the trick:
```
declare @startdate date, @enddate date
set @startdate = '20150105'
set @enddate = '20150125'
select
start_date,
end_date,
datediff(
day,
case when @startdate > start_date then @startdate else start_date end,
case when @enddate < end_date then @enddate ... | You will need a calendar table, but every database should have one.
The actual implementation is always user and DBMS specific (e.g. [MS SQL Server](http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html)), so searching for "calen... | Calculate Price For Overlapping Date Range | [
"",
"sql",
"sql-server",
""
] |
I have a table with Three columns:
GEOID, ParcelID, and PurchaseDate.
The PKs are GEOID and ParcelID which is formatted as such:
```
GEOID PARCELID PURCHASEDATE
12345 AB123 1/2/1932
12345 sfw123 2/5/2012
12345 fdf323 4/2/2015
12346 dfefej 2/31/2022 <-New GEOID
```
Wh... | How about using sub-query to count the sum
```
WITH data AS
(
SELECT *
FROM [Table]
WHERE
YEAR(PURCHASEDATE) * 100 + MONTH(PURCHASEDATE) = 201505
)
SELECT
GEOID,
COUNT(*) AS Nbr_Parcels_Sold,
CONVERT(decimal(18,8), COUNT(*)) /
(SELECT COUNT(*) FROM data) AS Perc_Total
FROM
... | Hopefully you are using SQL Server 2005 or later version, in which case you can get advantage of [windowed](https://msdn.microsoft.com/en-us/library/ms189461.aspx "OVER Clause (Transact-SQL)") aggregation. In this case, windowed aggregation will allow you to get the total sale count alongside counts per `GEOID` and use... | how to perform multiple aggregations on a single SQL query | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I'm a novice with my coding so forgive me if my question seems basic but I'm having some trouble extracting my variables from this While Loop in order to then use the results of my SQL query for validation.
This script below is the event handling for a login button on an .aspx form processing an email and login field ... | If you move the `If` block inside the loop, do you get closer to the behaviour that you're expecting?
```
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Passwo... | It could be that your query is returning no rows or that the values returned are dbNull or nothing. I would check the data getting returned and error if appropriate.
Try running the query against the database directly. Are you getting a row back?
To avoid the error, you can declare the string as String.empty
```
Dim... | Need help extracting variables from a While Loop in VB.Net | [
"",
"sql",
"vb.net",
"variables",
"while-loop",
""
] |
I have list of items that have start and end date. Items belong to user. For one item the period can range from 1-5 years. I want to find the count of days that are between the given date range which I would pass from query. Period start is always `sysdate` and end `sysdate - 5 years`
The count of days returned must a... | > Period start is always `sysdate` and end `sysdate - 5 years`
You can get this using: `SYSDATE` and `SYSDATE - INTERVAL '5' YEAR`
> Item 1) 01.01.2010 - 31.12.2010. Valid range: 15.05.2010 - 31.12.2010
> = ~195 days
>
> Item 2) 01.01.2015 - 31.12.2015. Valid range: 01.01.2015 - 15.05.2015
> = ~170 days
Assuming the... | Assuming the time periods have no overlaps:
```
SELECT SUM(LEAST(i.end_date, DATE '2015-05-15') -
GREATEST(i.start_date, DATE '2010-05-15')
) AS total_days
FROM items i
WHERE i.start_date >= DATE '2010-05-15' AND
i.end_date <= DATE '2015-05-15' AND
i.user = 'me';
``` | Count of days in a period | [
"",
"sql",
"oracle",
""
] |
I am trying to make a view that has 6 columns, and each row is the first 3 rows from 2 columns of another table.
For Example:
```
Asset Table
Asset_ID Asset_Name
1 Kitchen
2 Bathroom
3 Bedroom
4 Bed
5 Knife
6 Basement
View Combined
Asset_ID_A As... | Let me be clear here: this is a *really bad idea* to do this in SQL. That said, it's entirely possible:
```
WITH Ordered As (
select Asset_ID, Asset_Name, row_number() over (order by Asset_ID) as Sequence
from Asset
)
SELECT o1.Asset_ID Asset_ID_A, o1.Asset_Name Asset_Name_A
,o2.Asset_ID Asset_ID_B, o2.A... | If you only have 6 rows
```
SELECT
t1.Asset_ID as Asset_ID_A,
t1.Asset_Name as Asset_Name_A,
t2.Asset_ID as Asset_ID_B,
t2.Asset_Name as Asset_Name_B,
t3.Asset_ID as Asset_ID_C,
t3.Asset_Name as Asset_Name_C
FROM yourtable t1
INNER JOIN yourtable t2
ON t2.Asset_ID - 1 = t1.Asset_... | SQL View Statement | [
"",
"sql",
"sql-server-express",
""
] |
I have a simple table like this
```
firstname, lastname , nb_payments
a, b , 10
a, b , 20
b, a , 30
b, a , 40
b, b , 50
```
I want to select the 3 max payments grouped by the couple firstname, lastname
The output desired is like this
```
firstname, lastname , top3
b, a , 70
b, b , 50
a, b , 30
```
I did this query... | You need to sum the payments and group by `firstname` and `lastname`
```
SELECT firstname, lastname , SUM(nb_payments)
FROM account
GROUP BY firstname, lastname
ORDER BY 3 DESC LIMIT 3
``` | I think this produces the output you want:
```
select firstname, lastname, sum(nb_payments)
from (select t.*,
row_number() over (partition by firstname, lastname
order by nb_payments desc) as seqnum
from table t
) t
where seqnum <= 3
group by firstname, lastname;... | selecting max values grouped by two column | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
Why I get the following syntax error in this section of stored procedure :
> Incorrect syntax near the keyword 'FROM'.
---
```
WITH CTE_Residence_Overtime
AS
(
SELECT *
FROM #Residence
)
UPDATE t1
SET t1.over_time = t1.over_time + CONVERT(TIME, CAST(CTE_Residence_Overtime.overtimeHo... | I think you are missing one bracket
```
WITH CTE_Residence_Overtime
AS
(
SELECT *
FROM #Residence
)
UPDATE t1
SET t1.over_time = t1.over_time + CONVERT(TIME, CAST(CTE_Residence_Overtime.overtimeHours AS VARCHAR(2)))
FROM r_overtime AS t1
INNER JOIN CTE_Residence_Overtime
... | You are missing a closing paren on the `set`:
```
SET t1.over_time = t1.over_time +
CONVERT(TIME,
CAST(CTE_Residence_Overtime.overtimeHours AS VARCHAR(2)
)
)
------------------------------^
``` | Update query using inner join | [
"",
"sql",
"sql-server",
"stored-procedures",
"inner-join",
"common-table-expression",
""
] |
I know how to change the length of a column, but my SQL statement fails because the column I'm trying to change is a PK, so I get the following error:
> Msg 5074, Level 16, State 1, Line 1
> The object 'PK\_TableName' is dependent on column 'PersonID'.
PersonID = PK.
I've read [What is the sql to change the field ... | See below sample example how to increase size of the primary column
1. Create a sample table
`create table abc (id varchar(10) primary key)`
2. Find primary constraint in key constraints tables
`select object_name(object_id),* from sys.key_constraints where object_name(parent_object_id) = 'abc`
3. Drop constra... | ```
ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>
ALTER TABLE table_name
ALTER COLUMN column_name datatype
ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)
``` | How to change the column length of a primary key in SQL Server? | [
"",
"sql",
"sql-server",
"primary-key",
""
] |
I have problem here.
I have 2 tables want to join with `group by.`
```
tbl_1
NO userID users status branchID
1 1 abc ok 2
2 2 da ok 1
3 3 fe ok 3
4 1 abc ok 1
5 3 fe ok 2
tbl_2
branchID branch
2 medan
1 jakarta
3 batam
``... | This isnt very elegant but will do the job based on your data and output
```
SELECT DISTINCT Users,
STUFF((
SELECT ', ' + branch
FROM(
SELECT DISTINCT Users,
branch
FROM #tbl_1 t1
... | ```
select distinct tbl_1.userID, tbl_1.users, tbl_1.status, tbl_1.branchID, tbl_2.branch
from tbl_1
left join tbl_2
on tbl.branchID = tbl_2.branchID
```
this will only show you all the field that have different value. | JOIN 2 Table SQL Server with group by | [
"",
"sql",
"sql-server",
""
] |
this is not duplicate of [How to get time part from SQL Server 2005 datetime in 'HH:mm tt' format](https://stackoverflow.com/questions/3201432/how-to-get-time-part-from-sql-server-2005-datetime-in-hhmm-tt-format)
be cause all answers of that question returns 12:06PM (without space and need space)
I am trying to get o... | You can use:
```
select CONVERT(VARCHAR(5), GETDATE(), 108) + ' ' +
RIGHT(CONVERT(VARCHAR(30), GETDATE(), 9),2)
```
SQL fiddle: <http://sqlfiddle.com/#!6/a7540/2377> | For SQL 2012 above:
```
SELECT FORMAT(GETDATE(), 'h:mm tt', 'en-US')
``` | How to get time part from GetDate() As hh:mm tt in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.