Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
Similar to the following:
```
[Columns to Rows in MS Access](https://stackoverflow.com/questions/9183764/columns-to-rows-in-ms-access)
I want to know how , within the MS-Access Query Design environment, I can transform the following sample data from state #1 to state #2.
Here is what the data currently look lik... | Starting with our data in a table named [CurrentData]
```
Row School LocationCode Year
--- ------ ------------ ----
001 ABC 1000A 2011
002 DEF 1000A 2011
003 GHI 1000X 2011
```
the query
```
SELECT
cd1.Year,
cd1.LocationCode,
cd1.School,
COUNT(*) AS Schoo... | I think what you'll want to try for this is the UNPIVOT operation.
UNPIVOT (LocationCode FOR Locations IN (Locationcode2011, LocationCode2012, LocationCode2013)
I found a short [tutorial](http://mangalpardeshi.blogspot.com/2009/04/unpivot-multiple-columns.html) that demonstrates how to do a very similar problem if you... | What SQL code is best for the following column to row transformation? | [
"",
"sql",
"database",
"ms-access",
"rows",
""
] |
I am trying for an hour now but I am still not able to figure out what's the problem in this query. :/
```
SELECT * FROM question ORDER BY question_id DESC LIMIT 3 WHERE topic_name = (SELECT * FROM topic WHERE subject_name = 'Maths')
```
This is the error:
> 1064 - You have an error in your SQL syntax; check the man... | Your statements are all out of order. The correct statement is:
```
SELECT *
FROM question
WHERE topic_name = (SELECT * FROM topic WHERE subject_name = 'Maths')
ORDER BY question_id DESC LIMIT 3 ;
```
However, that won't work because of the subquery. Perhaps you mean something like:
```
SELECT *
FROM question
WHERE ... | Your WHERE clause needs to go before your ORDER BY clause:
```
SELECT * FROM question WHERE topic_name IN (SELECT topic_name FROM topic WHERE subject_name = 'Maths') ORDER BY question_id DESC LIMIT 3
``` | Can't figure out the error in the mysql query | [
"",
"sql",
"mysql",
""
] |
I've been trying to build an sql query that finds from (table) the most recent date for selected id's that fulfill the condition where 'type' is in hierarchy 'vegetables'. My goal is to be able to get the whole row once max(date) and hierarchy conditions are met for each id.
```
Example values
ID DAT... | I figured this out. Please see the query below as an example:
```
SELECT * FROM (table) t
WHERE t.date in
(SELECT max(date) FROM table sub_t where t.ID = sub_t.ID and (date !> (currentdate))
and preference in
(SELECT preference FROM (hierarchy_table) WHERE hierarchy ='vegetables')
and ID in ('124')
``` | ```
SELECT max(date) FROM (table) WHERE id in (123,124,125)
```
is giving you the max date from all dates, you need to group them.
Try replacing with:
```
SELECT max(date) FROM (table) GROUP BY id
```
This way you will get the max date for each id | How to find most recent date given a set a values that fulfill condition * | [
"",
"sql",
"sybase",
""
] |
I have a table that includes these columns:
```
Nameplate
Model
Segment
```
A sample table looks like:
```
Nameplate Model Segment
Acura ILX Small Lux Car
Audi Q5 Compact Lux Car
Audi Q5 Mid Lux Car
Audi SQ5 Compact Lux Car
```
I need to find all `Nameplate, Model` combination... | Try this :
```
SELECT [Nameplate], [Model]
FROM dbo.[Weighted Extract]
GROUP BY [Nameplate], [Model]
HAVING COUNT(distinct [Segment]) > 1;
``` | You can use `EXISTS`:
```
SELECT [Nameplate], [Model], [Segment]
FROM dbo.[Weighted_Extract] we1
WHERE EXISTS
(
SELECT 1 FROM dbo.[Weighted_Extract] we2
WHERE we1.Nameplate = we2.Nameplate
AND we1.Model = we2.Model
AND we1.Segment <> we2.Segment
);
```
`Demo` | SQL - Finding rows with duplicate values in one column | [
"",
"sql",
"sql-server",
""
] |
i got a requirement to write a MS-SQL stored procedure, the requirement is
**Table 1**
It consists total student fee to be paid in installments
**EX:**
```
SID SNAME INST.Date Amount
123 XYZ 01-01-2013 3500
123 XYZ 01-05-2013 3500
123 XYZ 01-10-2013 3500
123 XYZ 01-04-2014... | Here's a query that will give you what you want, expect `Balance.Installments` I don't know what it means :
```
SELECT distinct t1.SID
, t1.SNAME
, t1.Total_Inst
, t2.Paid_amount AS 'Paid.Amount'
, t1.Total_Inst - t2.Paid_amount as 'Balance amt'
, CEILING( (t1.Total_Inst - t2.Paid_amount) / t.Amount ) as 'Balance.Inst... | why you will need to run for 36000 record at one time.Also what is actially installment.There is only one instalment for any student no several.So i think database is lil wrong.
There should only one instalment amount and time interval(due date) per student in table.
Check the latest change.It is only for one student ... | count of Balance installments | [
"",
"sql",
"sql-server",
""
] |
I'm trying to figure out how to write an SQL query to find the distinct pairs of student ids that have the same quarter and year and class id and that have been in more than one classid together.
So the database looks like this
```
Studentid courseid quarter year
11035 1020 Fall 2012
11035... | Self join twice - once for the match, and again for to find a different match:
```
SELECT s.studentid, st.studentid, s.year, s.quarter, s.courseid
FROM enrolled s
JOIN enrolled st ON st.COURSEID = s.COURSEID
AND st.quarter = s.quarter
AND st.year = s.year
AND s.studentid < st.studentid
JOIN enrolled e2 ON e2.COU... | ```
SELECT a.*,b.courseid
FROM (SELECT a.year
,a.quarter
,a.studentid AS Student1
,b.studentid AS Student2
FROM enrolled a
JOIN enrolled b
ON a.COURSEID = b.COURSEID
AND a.QUARTER = b.quart... | SQL finding distinct pairs | [
"",
"sql",
"database",
"relational-division",
""
] |
I am new in Sql Could you please help it with this problem.
```
id |name |reportingTo
----------------------
1 A NULL
2 B 1
3 C 1
4 D 2
5 E 2
6 F 5
```
I want the expected output as below. How i can impliment this with one query.
```
Output
------------------------
Nam... | How about a self join? So something like
```
SELECT r.Name ,
rTo.Name Reporter
FROM testLevel r LEFT JOIN
testLevel rTo ON r.ReportingTo = rTo.id
```
Based on the fact that you have picked 3 RDBMSs you might want to take a look at
MySQL [IFNULL](https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions... | Keep joins and subselects out of your select statement.
MySQL and Oracle are two seperate databases...choose on or the other
```
select a.name, b.name
from reportingto a left join reportingto b on a.id = b.reportingto
```
that will give names..use a isnull statement to resolve the 'no one' when bnot found. Note the ... | Couldn't Create the Expected Query | [
"",
"mysql",
"sql",
"oracle",
"sql-server-2008",
"sql-server-2005",
""
] |
I'm having a problem with organizing SQL scripts that contain more than 10k lines of code.
Let's say there's a declaration of 10 variables:
```
-- declaration
DECLARE @SaleId1 int
DECLARE @SaleId2 int
DECLARE @SaleId3 int
DECLARE @SaleId4 int
DECLARE @SaleId5 int
DECLARE @SaleId6 int
DECLARE @SaleId7 int
DECLARE @Sal... | Code regions are not natively supported in SQL Server Management Studio.
In order to organize your code, you have a few options:
* Refactor to introduce stored procedure and user defined functions
* Use the “code region hack” defined in [this](https://stackoverflow.com/questions/4386099/sql-server-region) post
* Ins... | In SSMS , goto **Tools** > **Options** .
In dialog box find node **Transact-SQL** > **Intellisense**
Check **Outline Statements** option.
Reopen the Sql Script. | How to organize parts of T-SQL scripts in SQL Server Management Studio? | [
"",
"sql",
"sql-server",
"t-sql",
"ssms",
""
] |
I am writing a query to join 3 tables, I have the following tables:
* `Apn [ID, QualHolderID, RecvDate, Barcode]`
* `QualHolder [ID, Surname, FullName, DOB, ResCountryID, Gender]`
* `Country [ID, Name]`
* `Gender [ID, Name]`
I wrote the following SQL statement to retrieve the data:
```
SELECT
a.QualHolderID, b.... | You don't need to join `dbo.QualHolder` table two times.
Try it this way:
```
SELECT a.qualholderid,
b.fullname,
b.surname,
d.name,
b.dob,
b.rescountryid,
a.recvdate
FROM dbo.apn a
INNER JOIN dbo.qualholder b
ON a.qualholderid = b.id
IN... | I think that the correct query is:
```
SELECT a.QualHolderID, b.FullName, b.Surname, d.Name, b.DOB, b.ResCountryID, a.RecvDate
FROM dbo.Apn a
INNER JOIN dbo.QualHolder b ON a.QualHolderID = b.ID
INNER JOIN dbo.Gender c ON b.Gender = c.ID
WHERE b.ResCountryID = 48
``` | Joining Multiple Tables in SQL Server 2008 causes error | [
"",
"sql",
"sql-server",
"inner-join",
"where-clause",
""
] |
I am using the following stored procedure to fetch some data from a database.
The column meetingDate is formatted as datetime and only contains valid data.
How do I have to amend the stored procedure so that it only shows me the next matching record and not all of them ?
**Example:**
Today = 18/02/2014;
the database... | Use SELECT TOP 1
```
SELECT A.meetingID,
CONVERT(VARCHAR(11), A.meetingDate, 106) AS meetingDate,
A.createdBy,
B.speaker AS speaker,
B.topic AS topic
FROM MeetingDates A
INNER JOIN MeetingDetails B
ON A.meetingID = B.meetingID
WHERE... | Use windowed function. it's compatible sql server 2005+
here is an example with my data
```
with p as (
select *, dense_RANK() over (order by foryear desc, formonth desc) as rnk
from RISK_TRANS.dbo.mytable
)
select * from p
where rnk = 2
```
My keys are 2014 - 1 for last and 2013-12; 2013-11. It only picks me 20... | SQL Server: How to limit stored procedure to only show one (next) matching record | [
"",
"sql",
"sql-server",
"datetime",
"stored-procedures",
""
] |
*Sorry for my English*
I have two tables:
**Partners**
```
ID | NAME | IS_FAVORITE
```
**PartnerPoints**
```
ID | PARTNER_ID | NAME
```
And I want to get all rows from `PartnerPoints` which related to `Partners` (by `PARTNER_ID`) with the field `IS_FAVORITE` set to `1`. I.e. I want to get all *favorite* partner p... | You just need to use a `WHERE` clause:
```
SELECT PartnerPoints.*
FROM PartnerPoints
WHERE EXISTS ( SELECT *
FROM Partners
WHERE Partners.ID = PartnerPoints.PARTNER_ID
AND Partners.IS_FAVORITE = 1
)
``` | You can do this by **JOINING** the tables.
```
SELECT PartnerPoints.*
FROM PartnerPoints JOIN Partners ON PartnerPoints.Partner_ID=Partners.ID
WHERE Partners.Is_favorite = 1
```
This is an **INNER JOIN**. Oscar Pérez’s answer, with the subquery, is called a **SEMI-JOIN**. The database may execute the same plan, or th... | SQLite3 - Complex WHERE expression that uses two tables | [
"",
"sql",
"sqlite",
"android-sqlite",
"where-clause",
""
] |
## Description
I have four models:
1. User
2. Organization
3. Role
4. OrganisationUserRole
The idea is that one user can belong to many organizations and can have many roles, but just one per organization.
My models look like this:
**user.rb**
```
class User < ActiveRecord::Base
has_many :roles, :through => :or... | I ended up following the instructions here:
[How to join mutli-role, multi organisation tables in Rails](https://stackoverflow.com/questions/16771503/how-to-join-mutli-role-multi-organisation-tables-in-rails)
And it worked like a charm. | you need to add a database unique key for the three params, something like
```
add_index "organization_user_roles", ["user_id", "organization_id", "role_id"], name: "unique_roles", unique: true, using: :btree
```
then in your organization\_user\_role model
```
validates_uniqueness_of :role_id, scope: [:user_id, :org... | duplicate rows in join table with three has_many :through associations | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have an aggregation problem that can probably best be described with some example data.
Below is a dataset with transports, identified by `trp_no`. Each such transport is loaded in a container. A container may hold multiple such transports, and in this example any transport may only be loaded in one container.
```
... | This uses Rachcha's bigger sample set, which I think is necessary to really test this problem.
```
with sample_data as(
select 1 as trp_no, 10 as transport_volume, 'SE' as country, 'A' as container_id, 80 as container_max from dual union all
select 2 as trp_no, 20 as transport_volume, 'SE' as country, 'A' as c... | I added a little more sample data for illustrating a minor fix in the query that solved it-
```
with sample_data as(
select 1 as trp_no, 10 as transport_volume, 'SE' as country, 'A' as container_id, 80 as container_max from dual union all
select 2 as trp_no, 20 as transport_volume, 'SE' as country, 'A' as contai... | Conditional aggregation - once for each key | [
"",
"sql",
"oracle",
""
] |
I would like to return a product together with its latest value and values from last hour.
I have a product-table :
```
id, name, type (and so on)...
```
I have a values-table :
```
id_prod, timestamp, value
```
Something like :
```
12:00:00 = 10
12:15:00 = 10
12:30:00 = 10
12:45:00 = 10
13:00:00 = 10
13:15:00 = ... | If I understand correctly what you're trying to do, then You would have something like:
```
SELECT p.id, max(date_created), sum(value), mv.max_value
FROM product p
JOIN values v on p.id = v.product_id
JOIN (SELECT product_id, value as max_value
FROM values v2
WHERE date_created = (SELECT max(date_created) ... | Aleks G and mhasan gave solutions, but not the reason why this fails. The reason this fails is because the alias S is not known inside the subquery. Subqueries have no knowledge about the tables outside their scope. | mysql : Get latest value and sum of values from previous hour | [
"",
"mysql",
"sql",
""
] |
How can I insert string which includes quotes in oracle?
my code is
```
INSERT INTO TIZ_VADF_TL_MODELS (name)
VALUES ('xxx'test'yy');
```
if I use
```
INSERT INTO TIZ_VADF_TL_MODELS (name)
VALUES ("xxx'test'yy");
```
I get identifier is too long error because xxx'test'yy is clob.
how can I do that?
thx. | You can also use the ['alternative quoting mechanism' syntax](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements003.htm#i42617):
```
INSERT INTO TIZ_VADF_TL_MODELS (name)
VALUES (q'[xxx'test'yy]');
```
The pair of characters immediately inside the first set of quotes, `[]` in this case, delimit the qu... | Try escaping the quotes:
```
'xxx''test''yy'
```
In SQL quotes can be escaped by adding another quote before them. | insert string which includes quotes in oracle | [
"",
"sql",
"string",
"oracle",
"sql-insert",
"clob",
""
] |
I have a mysql database column named like `telephoneNo`
```
Telephone No
25645656
45454545
45565656
```
I want to prepend two digits XX to every value of `telephoneNo` column
```
Telephone No
xx25645656
xx45454545
xx45565656
```
I was trying to workout with concat but its not with integer values in my case please... | You can use [`CAST()`](http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast) to convert your integers explicitely:
```
UPDATE t SET phone=CAST(CONCAT('10', phone) AS UNSIGNED)
```
That will work with integer prefixes. However, I don't see solid reason to store phone numbers as integers and not str... | That's a hack change your col to varchar or something.
```
UPDATE table SET telephoneNo=9200000000+telephoneNo;
```
**EDIT**:
This method requires that all your numbers are of the same length, and 8 digits long, if all your numbers are more or less than 8 digits modify the number of 0's after the 92 accordingly | MySQL update query to prepend digit to existing column with integers values | [
"",
"mysql",
"sql",
"concatenation",
""
] |
I have a stored procedure in SQL Server 2012 that is executed by a console application (VB using MS Visual Studio 2013) by passing in 2 parameters. The code for the stored procedure is here:
```
ALTER procedure [dbo].[OptimiserReads_getMaxValue]
@ReadDate datetime,
@tagname nvarchar(50)
AS
Begin
declare @fir... | Just like you mentioned in your questions, all you need to do is to add alias for your case statement.
The format is as follows.
```
SELECT CASE WHEN @first > @second THEN @first
ELSE @second
END AS BiggerValue
```
Aliases can be used for columns, tables, joins, sub-queries and etc.
Format is alw... | ```
Select CASE when @first > @second then @first else @second end as columnname
``` | How to name a CASE statement | [
"",
"sql",
"sql-server",
"vb.net",
"stored-procedures",
""
] |
So I took accepted answer here [Select Parent and Children With MySQL](https://stackoverflow.com/questions/6240028/select-parent-and-children-with-mysql) for my `submissions_comments` schema which looks like:
```
+---------------+------------------+------+-----+---------+----------------+
| Field | Type ... | Is this what you mean?
```
SELECT parent.id, MAX(parent.comment) as pcomm,
GROUP_CONCAT(child.id ORDER BY child.id) as siblings,
GROUP_CONCAT(child.comment ORDER BY child.id) as siblingComments
FROM submissions_comments AS parent
LEFT JOIN submissions_comments AS child
ON child.parent_id = parent... | Edit - Try this to see if you like it, otherwise skip forward to another group\_concat idea -
The following approach will show all column values for each parent only on the first row where there is a child comment (or none). On rows that show a 2nd, 3rd, etc. child comment, the values for the parent will all be blank,... | Combining nested child comments with MySQL | [
"",
"mysql",
"sql",
"join",
""
] |
Following is my schema detail:
* DB\_A : schema\_1, schema\_2, schema\_3
* DB\_B : schema\_3
some procedures in schema\_3 access resources(table, view, sp) from schema\_1 and schema\_2.
All procedures in schema\_3 are same on both the dbs. **How do I access schema\_1 from schema\_3 for both the dbs**.
Now I can har... | Well the best choice I found is as follows.
Create [Synonym](http://technet.microsoft.com/en-us/library/ms177544.aspx) (independent database `DB_B`) for individual objects (in shared database `DB_A`) with same name in same schema. That way your existing procedures need not change, and will work as required. [Synonym](... | If DB\_A and DB\_B are on same server, only sure you that the login have permission in two database.
Now, use [database].[schema].[object], when you use object of others database
eg: I have two database, ("helpdesk", "intranet")
from heldesk to intranet
```
create view dbo.users
as
select login, name, lastname
fro... | Accessing data from another database in stored procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
"dynamic-data",
"synonym",
""
] |
My code, as I thought it would work, is as follows:
```
WHERE cp.OwnerId = 1
AND CASE
WHEN [CustAccountNote] <> 'n/a' AND [CustRulesDocPath] <> 'n/a'
THEN (cp.NAME = 'IQRRulesLinks' OR cp.NAME = 'AccountNote')
END
AND pp.lastupdated BETWEEN '01/01/2013' AND GETDATE()
```
Inevitably what I want to do is OMIT... | something like this?
```
WHERE cp.OwnerId = 1
AND ( ([CustAccountNote] = 'n/a' AND [CustRulesDocPath] = 'n/a')
or (cp.NAME = 'IQRRulesLinks' OR cp.NAME = 'AccountNote')
)
AND pp.lastupdated BETWEEN '01/01/2013' AND GETDATE()
```
So, if **both** of `CustAccountNote` and `CustRulesDocPath` is equal... | You can't do it exactly as you want, since the Case can only return a single value, but you *could* hack it:
```
WHERE cp.OwnerId = 1
AND
(
cp.NAME = 'IQRRulesLinks'
OR cp.NAME = 'AccountNote'
Or 1 = CASE
WHEN [CustAccountNote] = 'n/a' AND [CustRulesDocPath] = 'n/a' Then 1
... | Case...When...In a WHERE CLAUSE | [
"",
"sql",
"sql-server",
"t-sql",
"where-clause",
""
] |
I have two table :- table a, table b.
table a
---ID---
```
1
2
3
4
5
7
```
table b
---ID----
```
2
3
4
5
6
```
I have to get Output Like this without **UNION** Command:-
----ID-----
```
1
2
3
4
5
6
7
```
*Note: I have one solution with union:-*
```
**select * from a
UNION
select * from ... | We need another table with (at least) 2 rows for this:
```
CREATE TABLE d
( id INT NOT NULL
);
INSERT INTO d
(id)
VALUES
(0), (1) ;
```
Then, if we want to have only one query, we can use (**this is for fun, DO NOT USE in production**, that's why we have **`UNION`**):
```
SELECT DISTINCT
COALESCE(aa.id... | try this:
I think it works well in MS-SQL, change it to MySQL if you need, but MYSql doesnot support full outer join! Good luck
```
SELECT (
CASE
WHEN b.ID IS NULL
THEN a.ID
WHEN b.ID=a.ID
THEN b.ID
ELSE b.ID
END)
FROM
(SELECT ID FROM table2
)b
... | Alternative to UNION clause in Mysql | [
"",
"mysql",
"sql",
"database",
""
] |
i am having difficulty when i try to group by but with using order by statement.
Here is my query
```
create table AllData(NoOfPerson int,NoOfMinutes int,StartTime Datetime);
INSERT INTO AllData VALUES(1,2,GETDATE()),
(0,3,GETDATE()+1),
(3,4,GETDATE()+2),
(2,5,GETDATE()+3),
(0,6,GETDATE()+4),
(3,7,GETDATE()+5),
(2,8... | try wrap query:
```
SELECT *
FROM (SELECT noofperson,
Sum(noofminutes) NoOfMinutes,
Min(starttime) StartTime
FROM alldata
GROUP BY noofperson) t
ORDER BY noofminutes ASC;
```
or simply:
```
SELECT noofperson,
Sum(noofminutes) NoOfMinutes,
Mi... | Try this:
```
SELECT NoOfperson, NoOfMinutes FROM
(
select NoOfperson,SUM(NoOfMinutes)NoOfMinutes,MIN(StartTime)StartTime from AllData
group by NoOfperson
) AS Data
GROUP BY NoOfperson, NoOfMinutes, StartTime
order by StartTime
``` | issue with group by when order by is used | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I've prepared sql query like this
```
UPDATE Towar
JOIN TowarZamowienie ON Towar.Tow_id = TowarZamowienie.Tow_id
SET Tow_ilosc = Tow_ilosc - CAST(TowZam_ilosc AS UNSIGNED);
```
and it returns me Modified records: 0. I will admit that I've got records in database
Here are my tables:
```
TowarZamowienie
1 TowZam_... | i guess you making wrong in the ON clause
try this
```
ON Towar.Tow_id = TowarZamowienie.TowZam_id
```
[DEMO](http://sqlfiddle.com/#!2/a9965/1) | ```
UPDATE Towar, TowarZamowienie
SET Towar.Tow_ilosc = Towar.Tow_ilosc - CAST(TowarZamowienie.TowZam_ilosc AS UNSIGNED)
WHERE Towar.Tow_id = TowarZamowienie.TowZam_id;
```
--OR
```
UPDATE Towar
JOIN TowarZamowienie ON Towar.Tow_id = TowarZamowienie.TowZam_id
SET Tow_ilosc = Tow_ilosc - CAST(TowZam_ilosc AS UNSIGNED)... | How to cast varchar into int properly? | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
This [screenshot](http://i.hizliresim.com/Kgb6lL.jpg) is my result.
How can I take top record in Same ID ? (query result have 3 record but i want to take top record)
Thank You
My Code İs but i have error (The column 'ID' was specified multiple times for 'CTE'.)
```
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (PAR... | There is no inherent "top" or "bottom" so you need to specify the column(s) you want to order by. However, you can use `ROW_NUMBER` to get one record per ID.
For example(assuming `UPDATEDDATE` as order-column):
```
WITH CTE AS
(
SELECT RN = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY UPDATEDDATE ASC), *
FROM rb... | You can use `top 1 with ties` option.
```
select top 1 with ties *
from ...
order by id
``` | Sql Query Select One Record | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a MS SQL Server 2012 table that contains daily reports of people. Each day contains maximum 1 record of a person and the day is stored as a DateTime, having the time part set to "00:00:00.000". Example: '2014-01-30 00:00:00.000'
```
+-----------+-------------------------+----------------+
| Person id | Date ... | OK well how about something like
```
DECLARE @StartDate DATETIME = '01 Jan 2014',
@EndDate DATETIME = '01 Feb 2014'
;WITH Dates AS (
SELECT @StartDate RunDate
UNION ALL
SELECT RunDate + 1
FROM Dates
WHERE RunDate + 1 <= @EndDate
)
, PersonIDs AS (
SELECT DISTINCT
PersonID... | Try this:
```
SELECT DISTINCT PersonID
FROM
[Table] A
WHERE
NOT EXISTS
(
SELECT 1 FROM [Table]
WHERE
[PersonID] = A.[PersonID]
AND TRY_CAST([Date] AS DATE) BETWEEN TRY_CAST('January 1, 2014' AS DATE) AND TRY_CAST('February 1, 2014' AS DATE)
)
``` | SQL query to get items that have no value for a certain day | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a dilemma, I would like to use JOIN on all of my 22 tables to combine them into one long row for each `company` I have a main table `company` that has a `CompanyID` as a primary key and 22 other tables that reference `company.CompanyID` some of the tables do not contain an entry of the company while others do. S... | To remove the duplicate ids, use the `using` clause:
```
SELECT *
FROM `company` C LEFT OUTER JOIN
sales S
USING (CompanyID) LEFT OUTER JOIN
owner O
USING (CompanyID);
```
The `using` clause will output only one copy of each ID (in the more recent versions of MySQL -- this behavior has changed... | When your Reference key table dost not have primary key record but still you need that record the use [LEFT JOIN](https://dev.mysql.com/doc/refman/5.0/en/left-join-optimization.html)
Try like this
```
SELECT * FROM `company` C
LEFT JOIN sales S ON S.CompanyID = C.CompanyID
LEFT JOIN owner O ON O.CompanyID = S.Company... | Using JOIN on several tables matching a foreign key | [
"",
"mysql",
"sql",
"join",
""
] |
I have a simple table with data as below:
```
col_1
==========
haddock
cod
hake
mackerel
tench
sprat
dace
rudd
pike
gudgeon
....
```
I want to select the data such that I can output it in 5 columns:
```
col_1 col_2 col_3 col_4 col_5
======== ======== ======== ======== ========
haddock cod ... | I have a solution which seems to work although not very elegant:
```
with tab1 as ( select col_1 as col_1 from my_table a where mod(rrn(a), 5) = 1 ),
with tab2 as ( select col_1 as col_1 from my_table a where mod(rrn(a), 5) = 2 ),
with tab3 as ( select col_1 as col_1 from my_table a where mod(rrn(a), 5) = 3 ),
with ta... | To show what's going on, I'll break this down in small stages a,b,c,.. with "common table expressions", but this is one SELECT statement
```
with a as
( select row_number() over(order by order of f) - 1 as nb,
col_1 as fish
from fishtable as f
), b as
( select smallint(nb/5)+1 as... | Rows to Columns with iSeries DB2 SQL | [
"",
"sql",
"db2",
"ibm-midrange",
"db2-400",
""
] |
I didn't have room to make the title more descriptive, sorry, but this is what I am trying to accomplish:
I am making a data table for a Google Histogram chart on a web page. I am looking at customer and invoice data, and I want to get a snapshot of the customer status for each week of a previous time period (week, mo... | I tried the solutions presented, and did not get the kind of performance I was looking for, oddly enough. It was taking 7 minutes or more. I am not sure why. Anyways, I ended up doing some filtering on the data and pulling it into memory, and then using LINQ on the dataTable and going from there. It may not be pretty, ... | You could use something like the following to create a temp table of however many weeks you want to go back and use a group by to partition your data.
This will make the temp table with the week numbers (in this example it makes weeks 1 - 150)
```
declare @digits table
(
digit int
)
insert into @digits values (1... | SQL - How to have multiple queries in a statement without a loop or union all | [
"",
"sql",
"sql-server-2008",
""
] |
The tables look like these:
```
Table: Shops
ShopCode ShopName
-------- --------
A Aladdin
B Backstreet
C Clerk's Store
D Debs Tool
Table: Sale
ShopCode Product
-------- -------
A Hammer
A Thermometer
A Compass
B Eraser
B Hamme... | There are two fairly straight forward options.
You can join twice with the sale table, once per item. If you skip the `DISTINCT`, you may get duplicate values if the store sells more than one hammer or thermometer.
```
SELECT DISTINCT s.shopname
FROM shops s
JOIN sale s1 ON s.shopcode = s1.shopcode AND s1.product='ha... | You can easily Join twice on the Sale table--once for hammers and once for Thermometers to get the store with BOTH Hammers and Theremoeteres
```
SELECT s.ShopName FROM Shops s
JOIN Sale s1 ON s.ShopCode=s1.ShopCode AND s1.Product='Thermometer'
JOIN Sale s2 ON s1.ShopCode=s2.ShopCode AND s2.Product='Hamm... | MySQL Select both This and That | [
"",
"mysql",
"sql",
"database",
""
] |
i got a problem of my homework~
i want execute different sql in proc to use CASE WHEN
and the code like this
```
CREATE proc [dbo].[removeFileNew] (@transerid int,@Type int)
as
--PRINT @file
--PRINT @transerid
CASE
WHEN @Type=1 --report
THEN
UPDATE order_report_path SET ReportPath=''
... | You can't use CASE WHEN like this. In SQL this is meant to return a value, not control flow.
Use IF statements instead.
```
IF @Type=1 --report
BEGIN
UPDATE order_report_path SET ReportPath=''
WHERE tran_ser_id=@transerid
END
ELSE IF @Type=2 --gl
BEGIN
UPDATE order_report_path SET GRpath=''
WHERE tra... | ```
IF @Type = 1
BEGIN
UPDATE order_report_path
SET ReportPath = ''
WHERE tran_ser_id = @transerid
END
ELSE IF @Type = 2
BEGIN
UPDATE order_report_path
SET GRpath = ''
WHERE tran_ser_id = @transerid
END
ELSE IF @Type = 3
BEGIN
UPDATE order_report_path
SET ICpath = ''... | How to Use Case When in a stored procedure to execute a different SQL | [
"",
"sql",
"sql-server",
""
] |
There are three tables in MySQL which looks like this
```
Table:Travel Table:Airline Table:Location
Code From To Code Name Port Country
----- ---- --- ---- ---- --- -------
ET PAR IST ET Ettihad PAR France
ET ... | Try:
```
select *
from Airline a
where not exists(
select 1
from Travel t
join Location l
on t.from = l.port
where t.Code = a.code
and l.Country = 'France'
)
```
demo: <http://sqlfiddle.com/#!2/0e7dd/1> | How about something like this...
```
SELECT a.*
FROM airline a
LEFT
JOIN travel t
ON t.code = a.code
LEFT
JOIN location l
ON l.port = t.from
LEFT
JOIN airline x
ON x.code = a.code
AND l.country = 'France'
WHERE l.country IS NULL;
``` | Values corresponds to NOT AT ALL in MYSQL | [
"",
"mysql",
"sql",
"database",
""
] |
A similar question is asked here [multiple foreign keys referencing single column in other table](https://stackoverflow.com/questions/20830116/multiple-foreign-keys-referencing-single-column-in-other-table/20830137#20830137)
but the syntax is not shown in the answer. I would like to know how this can be accomplished in... | You need to define two foreign keys, one for each column:
```
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID) REFERENCES Person (PersonID)
;
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemAdvisor_Person
FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID)
;
``` | It is impossible to create one foreign key for two columns referencing one column. Create them seperate:
```
ALTER TABLE ItemIssue
ADD CONSTRAINT FK_ItemIssue_Person_Person FOREIGN KEY (PersonID) REFERENCES Person (PersonID),
ADD CONSTRAINT FK_ItemIssue_Advisor_Person FOREIGN KEY (AdvisorID) REFERENCES Person (Person... | two columns referencing a single column in another table | [
"",
"sql",
"sql-server",
"foreign-keys",
"foreign-key-relationship",
""
] |
I've got some data with two times defining a time range.
```
CREATE TABLE MY_TIME_TABLE
(
MY_PK NUMBER(10) NOT NULL ENABLE,
FROM_TIME DATE NOT NULL ENABLE,
TO_TIME DATE NOT NULL ENABLE
);
INSERT INTO MY_TIME_TABLE(MY_PK,FROM_TIME,TO_TIME)
VALUES(1,TO_DATE('2014-01-01 09:00:00', 'YYYY-... | You can do it using a Hierarchical query or a CTE.
[SQL Fiddle](http://sqlfiddle.com/#!4/74704/7)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE MY_TIME_TABLE ( MY_PK, FROM_TIME, TO_TIME ) AS
SELECT 1, TO_DATE('2014-01-01 09:00:00', 'YYYY-MM-DD HH24:MI:SS'), TO_DATE('2014-01-01 13:00:00', 'YYYY-MM-DD HH24:MI:SS')... | If you're using 11gR2 you can use [recursive subquery factoring](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#SQLRF55268) (aka recursive CTE or recursive with):
```
with r (my_pk, from_time, to_time) as (
select my_pk, from_time, to_time
from my_time_table
union all
select my_pk, ... | Oracle: Get every half hour between two times | [
"",
"sql",
"oracle",
"date",
""
] |
```
SELECT RC.Name AS RiskCategory,
( SELECT
SUM(CASE WHEN IA.ImpactLevel = 'High' THEN 1 ELSE 0 END)
FROM
Rpt_ImpactAssess IA
JOIN
Rpt_Risk R
ON
IA.FKRiskID = R.RiskID
WHERE
R.RiskID IN
(
SELECT FKRiskID
FROM
... | I'm fairly certain this produces the same result, try it:
```
SELECT RC.Name AS RiskCategory,
SUM(CASE WHEN IA.ImpactLevel = 'High'
THEN 1
ELSE 0
END)
FROM RM_RiskCategories RC
LEFT JOIN Rpt_Risk R ON R.RiskCatrogry = RC.Name
LEFT JOIN Rpt_ImpactAssess IA ON IA.FKR... | try this,sorry for syntax if any.it will be definitely faster then that sub-query .also try creating relevant index.also knowing this that,which table return how much row when join then accordingly you can break them in CTR.sometime it help.Also you have very correctly use sum instead of count
```
SELECT RC.Name AS Ri... | Can someone help to optimize SQL Query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
RDBMS - Oracle 11g.
Question:
I have a table like this -
```
column1 column2
A 111
A 222
A 333
B 444
C 555
C 666
```
I want to write a query that picks up just one record for each distinct column1 value.
The output should be this way:
```
A 111
B 444... | Sure
```
SELECT column1, MIN(column2)
FROM your_table
GROUP BY column1
```
Since you don't care which `column2` value you get, you could also use `MAX` or many other aggregate functions instead of `MIN`. | If you don't care, let the column2 be MIN
```
SELECT column1,
MIN(column2)
FROM table
GROUP BY column1;
``` | how to retrieve just one record from (non-distinct) column2 for every distinct column1 value? | [
"",
"sql",
"oracle11g",
"distinct",
""
] |
I have a SQL server table RealEstate with columns - Id, Property, Property\_Value. This table has about 5-10 million rows and can increase even more in the future. I want to insert a row only if a combination of Id, Property, Property\_Value does not exist in this table.
Example Table -
```
1,Rooms,5
1,Bath,2
1,Addre... | I think it most cases the differences between that two are going to be small enough that the choice should mostly be driven by picking the implementation that ends up being most understandable to someone looking at the code for the first time.
However, I think exception handling has a few *small* advantages:
* Except... | Dependent on the cost of #1 (doing a lookup) being reasonable, I would do both. At least, in Oracle, which is the database I have the most experience with.
Rationale:
* Unique/primary keys should be a core part of your data model design, I can't see any reason to not implement them - if you have so much data that per... | UNIQUE constraint vs checking before INSERT | [
"",
"mysql",
"sql",
"sql-server",
"oracle",
""
] |
I have tables `Address`, `Property` and `Listing`:
```
Create Table Listing
( PropertyID int -- Property ID as per the Property table
, AgentID int
, ListingDate DateTime not null property
, AskingPrice Decimal(10,2) not null
, SaleDate Date
, SalePrice Decimal(10, 2)
, Primary Key (Pro... | Your query can be much more simple, it's enough to group without using subqueries:
```
select
a.City,
count(*) as Properties,
avg(l.AskingPrice) as AskingPrice
from Address a
inner join Property p on p.AddressID = a.AddressID
inner join Listing l on p.PropertyID = l.PropertyID
where l.AskingPrice is not ... | I think you don't need group by. Simple co-related query should work:
```
create view MarketStatistics as
select City = a.City,
Properties = (select count(PropertyID)from Listing l join Property p on p.PropertyID = a.PropertyID where l.AskingPrice is not Null and l.SaleDate is Null and p.addressID = a.addressID),
... | SQL view with count and group by | [
"",
"sql",
"sql-server",
""
] |
I believe this outputs the date of Sunday of the current week but I don't know why.
Can someone please break down what's going on here.
```
SELECT trunc(sysdate+1,'DAY') FROM DUAL;
``` | Run this to understand what `trunc` does
```
SELECT to_char(trunc(sysdate+1, 'DAY'),'dd/mon/yyyy hh:mi:ss') FROM DUAL;
```
`DAY` does returns starting day of the week but `trunc` will also cut off the hours, minutes, seconds of that date. `Sysdate` will have some hours and minutes, but after trunc it is defaulted to ... | The TRUNC function will return the starting day of the week when the second parameter is DAY. Today Sysdate returns Thursday, +1 returns Friday etc. So when you add 3 it gives you next Sunday which marks the start of a new week. | trunc / sysdate... funny syntax need explanation | [
"",
"sql",
"oracle",
""
] |
How can I turn this big query into a stored procedure *and should I? What would the benefit be?*
```
SELECT *
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id)
INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
INNER JOIN item_subcategories ON (item_subcategories.item_id = ... | If you want columns from brands and items tables only, you can do like below
```
"SELECT brands.brand_name,places.place_name,
user_items.*,items.*,item_categories .*,
item_subcategories.*,item_photos.*,place_items.*
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id... | In my experience, stored procedures have been more trouble than they're worth, being inflexible and therefore more difficult to maintain than inline SQL, residing outside version control, and failing to provide much if any performance benefit. And in this case a stored routine doesn't seem necessary or beneficial, beca... | How to turn this big query into a stored procedure | [
"",
"sql",
"stored-procedures",
""
] |
I am trying to get sum for some columns from across multiple mysql tables using python/sqlalchemy. The number of tables is dynamic, and each table has **same** schema.
```
Table_1
| col1 | col2| ... |
Table_2
| col1 | col2| ... |
Table_...
| col1 | col2| ... |
```
I studied sqlachemy, and realised that the better i... | Your general approach looks reasonable. Getting the SUMs from the individual tables as a single row, and the combining those, is the most efficient approach. There's just a couple of minor fixes.
It looks like you will need to provide an alias for each of the SUM() expression returned.
And you're going to need to wra... | Unless you have some where clauses to join those tables together, you're going to end up with a cartesian join, where every record from each table in the query is joined against all other combinations of records from the other tables. so if each of those tables has (say) 1000 records, and you've got 5 tables in the que... | Better SQL to sum same columns across multiple tables? | [
"",
"mysql",
"sql",
"sum",
""
] |
How do I get only the middle part of the data in my table? I tried the following code, but this only removes the right part... my output should only be middle part.
For instance when I select the data `1-021514-1` the output should be `021514` without the left and right dashes
```
select LEFT(ticketid, CHARINDEX('-',... | Try this:
```
select right(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), len(left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1)) - charindex('-', left(ticketid, charindex('-', ticketid, charindex('-', ticketid, 0) + 1) - 1), 0)) from Table
``` | Please try:
```
SELECT
LEFT(st, CHARINDEX('-', st)-1) TicketID
from
(
SELECT
SUBSTRING(TicketID, CHARINDEX('-',TicketID)+1, 10000) st
FROM Table
)x
``` | How to split dash-separated values in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a MySQL dump, which I tried to restore with:
```
mysql -u"username" -p"password" --host="127.0.0.1" mysql_db < mysql_db
```
However, this threw an error:
```
ERROR 1115 (42000) at line 3231: Unknown character set: 'utf8mb4'
```
This is lines 3231-3233:
```
/*!50003 SET character_set_client = utf8mb4 */ ;
/... | Your version does not support that character set, I believe it was `5.5.3` that introduced it. You should upgrade your mysql to the version you used to export this file.
The error is then quite clear: you set a certain character set in your code, but your mysql version does not support it, and therefore does not know ... | You can try:
Open sql file by text editor find and replace all
```
utf8mb4 to utf8
```
Import again. | ERROR 1115 (42000): Unknown character set: 'utf8mb4' | [
"",
"mysql",
"sql",
"character-encoding",
"utf8mb4",
""
] |
I am very new to Microsoft SQL Server and I have a problem with this `INSERT` query that inserts a new record in a very very big table (it has many columns).
I have this query:
```
INSERT INTO VulnerabilityAlertDocument ([Id],
[VulnerabilityAlertId],
[SourceId],
... | Try `SET IDENTITY_INSERT VulnerabilityAlertDocument ON` before `INSERT`
After `INSERT`, add `SET IDENTITY_INSERT VulnerabilityAlertDocument OFF` | you have an identity column then you don't have to insert the Id, you have to delete Id from your query and the value of the Id | Why this insert query go into error? | [
"",
"sql",
"sql-server",
"rdbms",
"database",
""
] |
Can somebody please help me with this 'simple' query.
I have a two tables: Tunes and SavedRatings
Tunes contains a load of tune info including a Rating (INTEGER) field and an MD5 field used to uniquely identify a tune.
SavedRatings is a table consisting of a Rating and an MD5 field so that when I delete the contents... | Try it
`update Tunes set Rating = ( select SavedRating.Rating from SavedRating where Tunes.md5 = SavedRating.md5)`
Hope this helps! | ```
UPDATE T
SET T.Rating = S.Rating
FROM Tunes T INNER JOIN SavedRatings S
ON T.MD5 = S.MD5
``` | SQL: UPDATE number of rows using another table | [
"",
"sql",
"sqlite",
""
] |
I have a football fixtures table in the following format.
```
date date primary key
homescore int(4)
awayscore int(4)
```
Data is stored in the following format
```
DATE | HOMESCORE | AWAYSCORE
------------------------------------------
01-01-2014 | 1 | 0
08-01-2014 | 2 ... | ```
SELECT SUM(homescore > awayscore) AS won,
SUM(homescore < awayscore) AS lost,
SUM(homescore = awayscore) AS tie
FROM ...
```
The boolean results of the `>`, `<` and `=` will get auto-converted to integer `0` or `1`, by mysql, which can then be summed up. | [**SQL Fiddle**](http://sqlfiddle.com/#!2/38644/1/0):
```
SELECT SUM(CASE WHEN homescore > awayscore THEN 1 ELSE 0 END) WonCount,
SUM(CASE WHEN homescore < awayscore THEN 1 ELSE 0 END) LostCount,
SUM(CASE WHEN homescore = awayscore THEN 1 ELSE 0 END) TieCount
FROM fixtures
``` | return multiple counts from single table | [
"",
"mysql",
"sql",
"select",
"count",
"case",
""
] |
I wanted to know how I can get the records for the current week.
The query I am using is :
```
DECLARE @TableX TABLE
([Date] DATETIME)
INSERT INTO @TableX
SELECT '2014-2-17' UNION ALL
SELECT '2014-2-18' UNION ALL
SELECT '2014-2-19' UNION ALL
SELECT '2014-2-20' UNION ALL
SELECT '2014-2-21'
SELECT * FROM @Tabl... | Please try using CTE. Below query returns 7 days of week considering Sunday as week start day.
```
;WITH t
AS (SELECT Dateadd(wk, Datediff(wk, 0, Getdate()), -1) AS WeekD,
1 cnt
UNION ALL
SELECT weekd + 1,
cnt + 1
... | This will get all reacords with same week number and same year.
```
select * from cal where date_format(cal_date,'%v') = date_format(now(),'%v') and date_format(cal_date,'%Y')=date_format(now(),'%Y');
``` | How to get the data for the current week from MSSQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I tried to solve this all day long but it doesn't seem to work for me. I would like to execute a command and get the result back to a recordset.
The problem is one of two things: either I'm getting an empty response or there is a problem with my code. I know for sure that this command should fetch few lines from the D... | Looked at this for a few minutes, and it's been a *long* time since I've worked with classic asp, but I did see three things to look at:
1. Do you need to `Open` the connection before calling `objCommandSec.Execute`?
2. Can you try writing out a string literal inside the loop, that does not depend at all on the record... | Couple of tips after working with [asp-classic](/questions/tagged/asp-classic "show questions tagged 'asp-classic'") for years
1. There is no need to create a `ADODB.Connection` you can pass a connection string direct to `.ActiveConnection` property of the `ADODB.Command` object. This has two benefits, you don't have ... | Using Stored Procedure in Classical ASP .. execute and get results | [
"",
"sql",
"asp-classic",
"ado",
""
] |
I have table for shift periods :
```
empoyeeid ShiftId PeriodId Description DateFrom DateTo TimeIn TimeOut Night
----------------------------------------------------------------------------------------------------------
5 9 17 Morning 2014-01-01 20... | **Thanks All**
**abs() function get nearest shift for time in**
```
select PeriodId from shifts
where EmployeeCode = @employeecode
and datefrom <= @INDat and dateto >= @INDat
order by abs((cast(DATEPART(HOUR,timein) as int))-(cast(DATEPART(HOUR,@INDat) as int)))
``` | ```
select periodid
from shifts s
inner join employeeTransactions e
on s.employeeid=e.employeeid
where timein <= eventtime and timeout >=eventtime and e.employeeid=5
``` | Select time in and time out from fingerprint transaction table according shiftperiod table | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a table like this:
```
InstallID |InstallationDate
1 |01-01-2014
1 |01-02-2014
1 |01-03-2014
1 |01-04-2014
2 |01-01-2014
2 |01-02-2014
3 |01-01-2014
3 |01-02-2014
3 |01-03-2014
4 |01-04-2014
4 |01-05-... | Query:
**[SQLFiddleExample](http://sqlfiddle.com/#!2/89e3b/1)**
```
SELECT t1.InstallID,
t1.InstallationDate
FROM yourTable t1
LEFT JOIN yourTable t2
ON t1.InstallID = t2.InstallID
AND t1.InstallationDate < t2.InstallationDate
WHERE t2.InstallID is null
```
Result:
```
| INSTALLID | INSTA... | i think s simpliest way is
```
SELECT t1.InstallID,
MAX(t1.InstallationDate)
FROM yourTable t1
Group by t1.InstallID
``` | SQL Get Last Record By Date | [
"",
"sql",
""
] |
I'm working on a school project.
I have a problem filling a dataset with 2 SELECT Queries
```
sql = "SELECT PhoneNo, Forename, Surname, Address, Postcode FROM tblCustomerInfo"
Conn.Open()
da1 = New OleDb.OleDbDataAdapter(sql, Conn)
'initialises connection with the database and runs sql statement
d... | Try to combine the two SQL statements into one, separating by semi colon. Then run that query using single DataAdapter. You will probably get it. I didn't test it. But it should work. | I normally perform queries like this in ASP.Net VB using the `System.Data.SqlClient` library (i.e., I use SqlConnection, SqlCommand, and SqlDataAdapter instead of OleDb), but assuming it works the same way, I can tell you what I think I see is wrong.
Change
```
Label1.Text = ds1.Tables("Order").Rows(0).Item(5)
```
T... | VB Forms, filling out a dataset with two SELECT statements | [
"",
"sql",
"vb.net",
"dataset",
""
] |
I have a sample database which you can view here: <https://class.stanford.edu/c4x/Engineering/db/asset/socialdata.html>
and I am trying to write an sql statement that does the following:
/*Display a list of students who are friends with someone at least two years older then themselves. Do not list any pair more than o... | Try:
```
SELECT distinct
A.name,
B.name,
A.grade,
B.grade
FROM
Highschooler A,
Highschooler B,
Friend F
WHERE
A.ID = F.ID1 AND
B.ID = F.ID2 AND
B.grade - A.grade >= 2
ORDER BY
B.name,
B. grade,
A.name,
A.grade ASC;
``` | Try the following
```
SELECT distinct
A.name,
B.name,
A.grade,
B.grade
FROM
Highschooler A,
Highschooler B,
Friend F
WHERE
A.ID = F.ID1 AND
B.ID = F.ID2 AND
-- check both ways
(B.grade - A.grade >= 2 OR A.grade - B.grade >= 2)
ORDER BY
B.name,
B. grade,
A.name,
A.grade AS... | how to generate a list where a column is twice as large as the other column in sql | [
"",
"sql",
"sqlite",
""
] |
My target RDBMS is SQL Server 2012 - but I'm interested in a general response here.
Let's consider the following SQL Update clause:
```
UPDATE MyTable SET Active = 0 WHERE EffectiveDate < GETDATE()
```
Assuming that there could be MANY entries in *MyTable* where Active is already set to "0" for past events, would th... | You would have less writes (possibly as you state most is already 0?) and less updates to the indexes if you have indexes on `Active` | Possibly the largest savings is in writing to the log. Every row being updated generates log records. By updating fewer rows, you will be logging fewer changes.
As noted not too long ago in another question, avoiding these updates can simplify some arcane aspects on triggers. The"update(column)" syntax would identify ... | Benefits of WHERE filtering before performing SQL UPDATE | [
"",
"sql",
"sql-server",
""
] |
Im designing MySql database for store multiple products such as computers,mobile phones,pen drives....etc.each product has different features such as
```
**Computers has**
Processor
Ram
HDD
Monitor Size
....etc
**Mobile phone has**
Display Size
Network type
OS
Internal Memory
....etc
**Pendrive has**
Capacity
USB V... | Consider this
Create three table product, feature, product\_feature and maybe product\_photos
Product database will be
```
pid, p_name, p_description, p_price, ...
insert query
INSERT INTO (p_name, p_description, p_price, ....) VALUES(?,?,?,...)
```
feature table will
```
fid, f_name, f_description, ...
insert que... | You need to design a table in such a way that it covers all attributes for all products. This would help you insert any type of product in to that table. But, keep in mind that if there are 4 products with 10 different attributes, you end up creating 40 columns and might use only 10 to insert data at any point of time. | Store multiple data tables in single database table | [
"",
"mysql",
"sql",
"database",
"orm",
"relational-database",
""
] |
I have this code:
```
SELECT ID, Name, 100 AS TempColumn
FROM MyTable;
```
And the table is this:
```
| ID | Name | TempColumn|
-------------------------
| 1 | A | 100 |
-------------------------
| 2 | B | 100 |
-------------------------
| 3 | C | 100 |
-------------------------
| 1 | ... | You can sum a constant:
```
SELECT ID, Name, SUM(100) AS SumOfTempColumn
FROM MyTable
WHERE ID = 1
GROUP BY ID, Name;
```
**[Example on SQL Fiddle](http://sqlfiddle.com/#!2/e135c/1)** | Should this not be reasonably straight forward using an aggregate query?
```
SELECT ID,
Name,
SUM(100) AS TempColumn
FROM MyTable
GROUP BY ID, Name;
``` | How to find the sum of a temporary column in SQL? | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
Here's an example query:
```
SELECT thing_id
FROM thing
WHERE thing_type IN (3, 7)
```
I would like to turn the 3 and 7 into human-readable names to help understand what the query is truly doing. Something like the following would be great:
```
SELECT thing_id
FROM thing
WHERE thing_type_id IN (OPENED, ONHOLD)
```
... | Assuming you have a linked table called ThingNames where there are two columns, id and ThingName, you could do this
```
SELECT thing_id
FROM thing
LEFT JOIN ThingNames on thing.thing_type_id = ThingName.id
WHERE ThingNames.ThingName IN ('OPENED', 'ONHOLD')
```
(Don't forget the quotes around the ThingNames in your... | You can do this by generating a lookup table for the values:
```
with Lookup(value, name) as (
select 3, 'OPENED' from dual union all
select 7, 'ONHOLD' from dual
)
SELECT thing_id
FROM thing t
WHERE thing_type_id IN (select value from Lookup where name in ('OPENED', 'ONHOLD'));
```
I would recommend... | Using human-readable constants in queries | [
"",
"sql",
"oracle",
""
] |
How can you get today's date and convert it to `01/mm /yyyy` format and get data from the table with delivery month 3 months ago? Table already contains delivery month as `01/mm/yyyy`. | ```
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
```
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on `Date_Column`.
or you can check against last 90 days.
```
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATE... | Latest Versions of mysql don't support DATEADD instead use the syntax
```
DATE_ADD(date,INTERVAL expr type)
```
To get the last 3 months data use,
```
DATE_ADD(NOW(),INTERVAL -90 DAY)
DATE_ADD(NOW(), INTERVAL -3 MONTH)
``` | SQL query for getting data for last 3 months | [
"",
"sql",
"sql-server",
"sql-server-2008",
"date",
"select",
""
] |
I have a complex query that feeds into a simple temp table named #tempTBRB.
select \* from #tempTBRB ORDER BY AccountID yields this result set:

In all cases, when there is only 1 row for a given AccountID, the row should remain, no problem. But whe... | ```
SELECT
AccountID
,MIN(SDIStatus) AS MinSDIStatus
INTO #MinTable
FROM #tempTBRB
GROUP BY AccountID
SELECT *
FROM #tempTBRB T
JOIN #MinTable M ON
T.AccountID = M.AccountID
AND T.SDIStatus = M.MinSDIStatus
DROP TABLE #MinTable
``` | Here is a little test that worked for me. If you just add the extra columns in your SELECT statements, all should be well:
```
CREATE TABLE #Temp ( ID int, AccountID int, Balance money, SDIStatus int )
INSERT INTO #Temp ( ID, AccountID, Balance, SDIStatus ) VALUES ( 1, 4100923, -31.41, 2 )
INSERT INTO #Temp ( ID, Acc... | SQL Server - How to filter rows based on matching rows? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I have Table A, Column 1.
This table has values such as:
```
1
2
3
3
4
4
4
5
```
I have Table B, Column 2.
Which lists certain values, like:
```
1
3
4
```
I need a query to Count each unique value in Table A, but ONLY if that value is present in Table B.
So with the above, the end result would be:
1 has a quant... | Based on your question, something like the following should solve your problem.
```
select b.column1,
count(a.column2)
from tableb as b
inner join tablea as a on b.column1 = a.column2
group by b.column1
```
Since you wanted only records which are in both tables, I am using an inner join. Then I am... | I would use an `INNER JOIN` query with `GROUP BY` aggregate function
```
SELECT a.column1,
count(a.column1) as total
FROM tablea a
INNER JOIN tableb b
ON a.column1 = b.column2
GROUP BY a.column1
``` | SQL Table Counting and Joining | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I have a csv large file (>1GB) sitting in network filestorage which gets updated weekly with new records. The file has colums similar to these:
```
Customer ID | Product | Online? (Bool) | Amount | Date
```
I need to use this file to update a postgresql database of customer IDs with the total amount in each month by ... | COPY the file to a staging table. This assumes of course you have a PK aka a unique identifier for each row that doesn't mutate. I checksum remaining columns and the same for the rows you already loaded into your destination table and compare source to destination this will find the updates, deletes, and new rows.
As ... | Don't store data in a CSV > 1 gigabyte. Store it in a file called something like `current_week_sales`. At the end of the week schedule a script which renames it to something like `2014_12_sales` and creates a new, empty `current_week_sales`. | Good way to pull new lines from (non indexed/non sequential) huge file | [
"",
"sql",
"ruby",
"postgresql",
"diff",
""
] |
I am trying to remove all records from table based on the date of another for example I have one table called `pd_course_mstr` that has the following fields
```
course_id
start_dt
```
Then I have another table called `pd_eval_dtl` that has the following fields in it
```
course_id
eval_question
```
The goal is to de... | The syntax is
```
DELETE FROM eval
FROM pd_eval_dtl AS eval
INNER JOIN pd_course_mstr AS course
ON eval.course_id = course.course_id
WHERE ( course.start_dt = '20140217' )
``` | Try this.
```
DELETE ped
FROM pd_eval_dtl ped
INNER JOIN pd_course_mstr pcm ON ped.course_id = pcm.course_id
WHERE pcm.start_dt='20140217'
``` | Delete from table on join | [
"",
"sql",
"sql-server",
""
] |
Below is my query which I am running against Postgres database.
```
SELECT ad.col1
,ad.col2
,md.col3
,ad.col4
,mcd.col5
,AVG(mcd.col5 / md.col3) AS dc
,AVG(md.col3 / ad.col4) AS cb
FROM tableCount AS md
INNER JOIN tablePop AS ad ON ad.col1 = md.col1
AND ad.col2 = md.col2
INNER JOIN tableDat... | You want to remove `col5` from the `group by`:
```
SELECT ad.col1
,ad.col2
,md.col3
,ad.col4
,sum(mcd.col5) as col5
,AVG(mcd.col5 / md.col3) AS dc
,AVG(md.col3 / ad.col4) AS cb
FROM tableCount AS md
INNER JOIN tablePop AS ad ON ad.col1 = md.col1
AND ad.col2 = md.col2
INNER JOIN tableData AS... | You can `SUM()` or take the `MAX()`, really it's only `col5` in your sample that is resulting in multiple rows, `GROUP BY` any non-aggregate field, and pick the appropriate aggregate for any other field:
```
SELECT ad.col1
,ad.col2
,MAX(md.col3)
,MAX(ad.col4)
,AVG(mcd.col5)
,AVG(mcd.col5 / md.col3)... | How to group by two columns to show only one single row? | [
"",
"sql",
"postgresql",
"group-by",
"aggregate-functions",
""
] |
I'm working on the Northwind Microsoft Access database in Acceess 2007. In the Orders table there are three date fields: OrderDate, RequiredDate and ShippedDate.
All of these fields are in 1994-1996. I'm trying to input this into an ETL system, but that system does not allow dates over 15 years old.
I'd like to add 1... | I ended up going into Create then Query Design. In there the ribbon now showed Design as a tab. I clicked on Update and then SQL view and pasted it, then switched to design view. After saving the query, I tried to run it and it failed due to some security feature that was disabled. I enabled it and updated the database... | The problem is definitely not due to a syntax error with `DateAdd`. This Immediate window example demonstrates your `DateAdd` syntax is valid.
```
? DateAdd("yyyy",10,Date())
2/18/2024
```
And it will work the same way in VBA code or in a query.
Beware that an Access field can have both *name* and *caption* properti... | How to add time (years) to a date column in a table | [
"",
"sql",
"ms-access",
"ms-access-2007",
"dateadd",
""
] |
I have a table named "star" with has two columns celeb, movie and an other table named "releases" with two columns celeb, album. I want to create a query that will show me a table with tree new columns: celeb, number of albums, number of movies.
So the idea is that I want to show the celeb that have played to a movie ... | Perhaps this is what you are looking for:
```
SELECT movie.celeb, movieCount, albumCount
FROM
(SELECT celeb, count(1) movieCount
FROM star GROUP BY celeb) movie INNER JOIN
(SELECT celeb, count(1) albumCount
FROM releases GROUP BY celeb) album ON movie.celeb=album.celeb
``` | I assume you meant "number of albums" and "number of movies". If that is correct, this should work:
```
select celeb,
sum(case when num_type = 'movie' then num_recs else 0 end as num_movies,
sum(case when num_type = 'album' then num_recs else 0 end as num_albums
from (select celeb, count(*) as num_recs... | Query sql with two table in one and show the counting the total number | [
"",
"sql",
"sqlite",
""
] |
I am having a class in computer security and are having a little trouble with the syntax when doing a sql injection on a local machine that we are suppose to hack.
below is the syntax of the sql syntax.
```
SqlCommand sqlc = new SqlCommand("SELECT Record FROM Table_Users WHERE Username='" + username + "' AND Password... | try
```
';INSERT Table_Users (Username, Password) VALUES ('hejsan', 'glenn');
```
-> you need to close the `'` after `Username=`.
In this case you don't even need a value for the password field.
You could put `--` after your injected statement to cancel the rest of the select statement:
```
';INSERT Table_Users (U... | My first take was to have
`INSERT INTO Table_Users` instead of `INSERT Table_Users` but as the poster noted `INTO` is optional(in MSSQL in contrast to the standard ANSI SQL).
On second thought depending on what the data type your columns are the query could work by appending N in front of the values as per [What is th... | SQL syntax error (SQL injection) | [
"",
"sql",
"sql-server",
"visual-studio-2010",
""
] |
The following statement works in my database:
```
select column_a, count(*) from my_schema.my_table group by 1;
```
but this one doesn't:
```
select column_a, count(*) from my_schema.my_table;
```
I get the error:
> ERROR: column "my\_table.column\_a" must appear in the GROUP BY clause
> or be used in an aggregate... | This error makes perfect sense. `COUNT` is an "aggregate" function. So you need to tell it which field to aggregate by, which is done with the `GROUP BY` clause.
The one which probably makes most sense in your case would be:
```
SELECT column_a, COUNT(*) FROM my_schema.my_table GROUP BY column_a;
```
If you *only* u... | When you have a function like `count`, `sum` etc. you need to group the other columns. This would be equivalent to your query:
```
select column_a, count(*) from my_schema.my_table group by column_a;
```
When you use `count(*)` with no other column, you are counting all rows from `SELECT *` from the table. When you u... | "group by" needed in count(*) SQL statement? | [
"",
"sql",
"postgresql",
""
] |
I've a requirement where in if the query string matches column1 , return me 1. If it matches column 2 return 2 else if it matches column 3 return 3.
Table strunctre:
```
col1 col2 col3
11 12 13
22 23 24
```
If my query string is 23, then i'm expecting a return value of 2 as it matches col... | There are a couple of approaches. If there is a guarantee that no more than one column will match at a time, a UNION will work:
```
SELECT 1 AS SomeCol
FROM table1
WHERE col1 = querystring
AND orderid = xxx
UNION
SELECT 2
FROM table1
WHERE col2 = querystring
AND orderid = xxx
UNION
SELECT... | Please try using `case`
```
declare @var int
set @var=23
select
case @var when col1 then 1
when col2 then 2
when col3 then 3 end
from YourTable
where
col1=@var OR
col2=@var OR
col3=@var
``` | sql query to return single value based on column it matches | [
"",
"sql",
"sql-server",
""
] |
Following code works in Oracle version >= 9i as displayed in [this fiddle](http://sqlfiddle.com/#!4/ddf2e/6)
```
SELECT T1.col1, T1.col3,count(T2.col1)
FROM T1
LEFT JOIN T2
ON T1.col3 = T2.col3
AND ',' || T2.col2 || ',' like '%,' || T1.col1 || ',%'
GROUP BY T1.col1, T1.col3
```
However based on [Oracle Le... | You could try to create subqueries containing the modified columns and then joining the tables as below:
```
Select Mt1.T1_Col1, Mt1.T1_Col3,Count(Mt2.T2_Col1)
From
(Select T1.Col1 As T1_Col1, T1.Col3 As T1_Col3, '%,' || T1.Col1 || ',%' As T1_Col1_New From T1) Mt1,
(Select T2.Col1 As T2_Col1, T2.Col2 As T2_C... | Following is working code from [fiddle](http://sqlfiddle.com/#!4/1ae4a/10)
```
Select Mt1.T1_Col1, Mt1.T1_Col3,Count(Mt2.T2_Col1)
From
(Select T1.Col1 As T1_Col1,
T1.Col3 As T1_Col3,
'%,' || T1.Col1 || ',%' As T1_Col1_New
From T1) Mt1
,
(Select T2.Col1 As T2_Col1,
T2.Col2 As T2_Co... | How to specify optional OUTER JOIN condition in Oracle 8i | [
"",
"sql",
"oracle",
""
] |
I Have the following table "Custumer":
```
Customer_ID Customer_Name
01 John
02 Mary
03 Marco
```
I would like to return the following result from a select:
```
Query_Result
01
02
03
John
Mary
Marco
```
Is it possible? Merge both columns in one? | One way (assumes Customer\_ID is a character type)
```
SELECT
Customer_ID
FROM Customer
UNION ALL
SELECT
Customer_Name
FROM Customer
``` | Try using `UNION ALL`, the following should work for you.
```
SELECT CONVERT(varchar(30), Customer_ID) FROM Customer
UNION ALL
SELECT Customer_Name FROM Customer
``` | Concat two SQL's Results in one Column | [
"",
"sql",
"sql-server",
""
] |
Note: I am pretty new to MySQL so bear with me please.
I have 2 tables in my database which are set up as follows:
```
guides table:
guide_id (primary) | cat_id | title
1 0 guide01
2 0 guide02
steps table:
step_id | guide_id (foreign) | step_txt
1 1 ... | Crude solution would be:-
```
SELECT DISTINCT guides.*
FROM guides
JOIN steps ON guides.guide_id=steps.guide_id
WHERE step_txt LIKE "%keyword%"
```
Possibly more elegant and giving you the matched text :-
```
SELECT g.guide_id, g.cat_id, g.title, GROUP_CONCAT(s.step_txt)
FROM guides g
INNER JOIN steps s
O... | `distinct *` is going to return rows where *all* the columns are distinct. For what you want, you can use:
```
SELECT *
FROM guides JOIN
steps
ON guides.guide_id = steps.guide_id
WHERE step_txt LIKE "%keyword%"
GROUP BY guides.guide_id;
```
This uses a MySQL extension to `group by` and it will not work in ... | MySQL DISTINCT function not working as I expected | [
"",
"mysql",
"sql",
"join",
"distinct",
""
] |
I was told my somebody for small project table count should be 10-15
some told me more tables better it is.
I don't have a requirement specification because i'm doing a small project at home. but its growing bigger. Typically I don't make requirement specification but end of the day I wish I should've made it.
Anyway... | This question is a bit like ["How long is a piece of string?"](http://en.wiktionary.org/wiki/how_long_is_a_piece_of_string)
The number of tables in a database depends on the domain model of your application. It is simply impossible to answer your question without doing a data analysis of your case.
There might be hug... | Though SO is not the right platform to answer this as this is a very opinion based discussion, still from my personal experience I tend to follow a thumb rule-
> "Only bare bones business entities which are absolutely needed must
> constitute as database entities."
Note that in all terms, database entities is not sam... | How many entities a database should have in a real world app? | [
"",
"sql",
"database",
""
] |
I have a table which contains a column that has a German umlaut in its name. Yes, I know this is an absolutely bad idea, but I did not create the table and can definitely not alter it, so I have to somehow deal with it.
My problem is that my queries don't seem to work when I use this column in the `WHERE` clause.
Whe... | It's nothing to do with the column name. it looks like the values in the column have a time component. You can query for the whole day with:
```
WHERE TRUNC(t.BadUmlautColumnÄ5) = TO_DATE('20.02.2014', 'DD.MM.YYYY')
```
But if the column is indexed it would be better to do it the other way around:
```
SELECT TO_CHAR... | Try that
```
SELECT t.BadUmlautColumnÄ5
FROM myTable t
WHERE t.BadUmlautColumnÄ5 = TO_DATE('20.02.2014', 'dd.mm.yyyy');
```
If wouldn't work -
```
SELECT t.BadUmlautColumnÄ5
FROM myTable t
WHERE t.BadUmlautColumnÄ5 = TO_TIMESTAMP ('20.02.2014', 'dd.mm.yyyy');
```
You can also try
```
SELECT t.BadUmlautColumnÄ5
FRO... | Query table with german Umlaut in column name | [
"",
"sql",
"oracle",
""
] |
I have a table (BUDDY) with these attributes
* id
* requestor
* requested
* status
if the status='a' means that requestor and requested are buddies
however how can i know the buddies of a certain user if the user can either be a requestor and a requested?
```
SELECT requestor, requested
FROM buddy,user
WHERE user_i... | If you want to get some fields from the user, you need to join `buddy` to the `user` table. Otherwise, you are going to get an uncorrelated cross-join.
However, it does not look like you need any of the user's columns, so a simple change below should do the trick:
```
SELECT requestor, requested
FROM buddy
WHERE user... | Given a user U
```
SELECT requestor
FROM buddy
WHERE requested = U AND status='a'
UNION
SELECT requested
FROM buddy
WHERE requestor = U AND status='a'
``` | SQL query not getting it right | [
"",
"sql",
"join",
""
] |
A very basic question, I have an update I would like to do when I do the update then it is affecting 2000+ rows but when I just do the select query in the subquery then I get 1726 rows. I know there is something wrong in my update statement, can someone please help?
```
update ship_plu
set pluc_dt='1-Jan-1999'
w... | Because you are updating rows, that shouldn't be updated.
`ship_plu.pluc_dt` might meet the conditions, while `ship_plu.ship_num` is **not**.
This is the wrong way to update.
You should try that:
```
update ship_plu sp
JOIN ship s
ON sp.ship_num=s.ship_num
set pluc_dt='1-Jan-1999'
where pl... | You want a correlated subquery. But you have the inner subquery referring to the outside table. Try this:
```
update ship_plu sp
set pluc_dt='1-Jan-1999'
where pluc_dt in (
select sp.pluc_dt
from ship s
where sp.pluc_dt between '16-Feb-2014' and '20-Fe... | Why are different values being affected in my update sql query? | [
"",
"sql",
"select",
"subquery",
""
] |
I have two tables say Table1(`id`,`name`) and Table2 with (`id`,`name`).
Table1 looks like:
```
id name
1 ABC
2 DEF
```
Table2 looks like:
```
id name
1 XYZ
2 ASD
```
Can someone shed light on how I can add Table2 rows to Table1 i.e.
Table1 must finally look like:
```
id name
1 ABC
2... | ```
Insert into table1 (name)
Select name from table2
``` | Try like below, If `id` in `table1` is not `auto_increment`
```
SELECT * FROM table1;
+------+------+
| id | name |
+------+------+
| 1 | ABC |
| 2 | DEF |
+------+------+
2 rows in set (0.00 sec)
SELECT * FROM table2;
+------+------+
| id | name |
+------+------+
| 1 | PQR |
| 2 | XYZ |
+------+-... | Adding rows from one table to another existing table where primary key is autogenerated | [
"",
"mysql",
"sql",
"pentaho",
""
] |
I want to get numOfItem from table BUY using ticketTypeId and then using the BUY.userId to find in the table USER to get the gender. So I can get numOfItem from table BUY and gender from table USER. I don't know how to write this in one query. Any idea?
table structure:
TABLE BUY:
> ticketTypeId
>
> numOfItem
>
> us... | You need to join your tables on a common field, in this case user id
```
Select b.ticketTypeId, b.numOfItem, b.userId, u.gender
From buy b inner join user u on b.userid = u.userid
Where b.ticketTypeId = <val>
```
You want to include `where` to get only needed `ticketTypeId` | Generally speaking a join between two tables is something like:
```
select table1.*,table2.*
from
table1
join table2 on table1.key=table2.key
``` | How to write a sql query to get data from two tables | [
"",
"mysql",
"sql",
""
] |
I am trying to figure if it is possible to concatenate the results of a SQL query if the output has more than one value
For example: If the below query returns more than one result
```
select * from employee
```
Output:
```
emp1
emp2
emp3
```
I want the results to show as
> emp1, emp2, emp3 | You can use "listagg"
Example:
```
SELECT LISTAGG(columnname, ',') WITHIN GROUP (ORDER BY columname)
```
Hope it resolves the issue! | ```
SELECT LISTAGG(empname,',') WITHIN GROUP(ORDER BY empname) FROM emp;
``` | concatenate results of a sql query | [
"",
"sql",
"oracle",
""
] |
Sorry for my bad English.
Please assume that we want to save all commercial actions(sell & buy) for all days and each day has
100 or more action. After 3 years we have a table with more than 100,000 row. Now we want to get a
report from the actions done in 2 years ago between 5/20 to 5/25.
```
SELECT *
FROM acti... | Don't assume that your query will behave bad when there is X amount of rows in your tables. You should test it!
It is very easy to create a few million rows of test data for each of your tables (Should be done in development or test environment). Then you can test each of your queries and see exactly how "slow" they w... | > The problem is that all 100,000 row must be read for doing this.
A: EVEN IF - that would be trivial unless you run it on an old mobile phone. I regularly aggregate 100 million rows from a 10 billion row table.
B: Learn what an index is, then not all the row must be read. | Speed up finding records in a very large sql table | [
"",
"sql",
"sql-server",
"entity-framework",
""
] |
I have a table with 2 columns: EntryID and its Version. Each entry can have many different version, the highest version is the latest version of that entry. Also each entryID may have more than 1 name
```
EntryID - Version - EntryName
212 - 1 - Car
212 - 1 - Car2
212 - 2 - Batr
212 - 2 - hoo
451 - 2 - Csert
451 - 3 - ... | ```
SELECT t1.*
FROM Table t1
JOIN (SELECT EntryID, MAX(version) maxversion
FROM Table
WHERE EntryID IN (212, 451)
GROUP BY EntryID) t2
ON t1.EntryID = t2.EntryID AND t1.version = t2.maxversion
``` | Try:
```
select y.*
from y.table y
where y.entryid in (212, 451)
and y.version =
(select max(x.version) from table x where x.entryid = y.entryid)
``` | How to query to get the Max value of a field in relating to another field? Group By Doesn't work? (MySQL) | [
"",
"mysql",
"sql",
""
] |
Let's say I have a table like this:
```
Event (eventID, StartDateTime, EndDateTime)
```
* `StartDateTime` is `datetime` datatype
* `EndDateTime` is `datetime` datatype
Now sample data could be like so:
```
EventID StartDateTime EndDateTime
-----------------------------------------------------------
... | use this query
```
SELECT * FROM Event
WHERE '2014-02-23 00:00:00.000' BETWEEN StartDateTime and EndDateTime
``` | You don't want `OR`, you want `AND`. You want events that started before or on the date you specified, *and* that end after the date you specified:
```
SELECT
*
FROM
Event
WHERE
StartDateTime <= '20130223'
AND
EndDateTime > '20130223'
```
Also, I'd seriously recommend that you start storing these date... | How to search Date in SQL Server 2012 over two columns | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a table CLIENT
```
CLIENT_ID NAME CP VILLE
1 razer 49004 St hallo
2 mayui 49005 Kubol
```
and another table AGENCE
```
CLIENT_ID AGENCE_ID ADDR CP VILLE
1 1 qsdf null null
2 2 qsdf null null
1 ... | So one way to do what you *asked* would be the following:
```
UPDATE A
SET A.CP = C.CP, A.VILLE = C.VILLE;
FROM AGENCE A
LEFT JOIN CLIENT C ON A.CLIENT_ID = C.CLIENT_ID
```
A better way to do what you *really* wanted, would be to drop the columns from the `AGENCE` table and just do the join whenever you need it... | i just update the answer of @compuchip
```
UPDATE A
SET A.CP = C.CP, A.VILLE = C.VILLE;
FROM AGENCE A
LEFT JOIN CLIENT C ON
A.CLIENT_ID = C.CLIENT_ID
AND
A.AGENCE_ID = C.CLIENT_ID
``` | How can i copy column table to another table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table in which one of the column is timestamp and I have the following query
> SELECT \* FROM test WHERE (timepacket BETWEEN 2014-02-16 00:00:00 and 2014-02-19 00:00:00) AND (shift = 1)
But this query gives me all the rows between the date range given in sql query. Thus my question is how can group the resul... | ```
SELECT * FROM test WHERE
timepacket BETWEEN '2014-02-16 00:00:00' AND '2014-02-19 00:00:00'
AND shift = 1
GROUP BY timepacket;
``` | Use GROUP BY or *Order by*
```
SELECT * FROM test WHERE (timepacket BETWEEN 2014-02-16 00:00:00 and 2014-02-19 00:00:00)
AND (shift = 1) GROUP BY timepacket
``` | Group results by days in a date range | [
"",
"mysql",
"sql",
""
] |
I have a database structured in the following way
```
ID | DATE | col_0 |
--------------------------
1 | 2014 | A_Ver2_data0 |
2 | 2014 | A_Ver2_data1 |
3 | 2014 | A_Ver2_data2 |
4 | 2013 | A_Ver1_data0 |
5 | 2013 | A_Ver1_data1 |
6 | 2012 | A_Ver0_data0 |
7 | 2012 | A_Ver0_data1 |
8 | 2013 | B_Ver3_dat... | I think this does what you want. It parses the column to get the first and last parts and then finds the maximum "DATE" for each. It returns the row that matches the date:
```
select id, "DATE", COL_A
from (select v.*,
max("DATE") over (partition by substr(col_A, 1, 1),
... | I am not sure but i think this would work : "HAVING date >= MAX(date)-1"
max(date)-1 will return 2014-1 = 2013 , which will eventually filter out the results based on date >= 2013 .
But this would list all the 2013,2014 entries .. | Using ORDER BY and getting most recent version of records | [
"",
"sql",
"oracle",
"sql-order-by",
""
] |
I have a table with below data
```
-------------------
ID Key Value
-------------------
1 1
2 0
3 1
4 0
5 0
6 0
7 1
8 0
9 0
--------------------
```
I want to update the `Value` column as below
```
-------------------
ID Key Value
--------------... | ```
SQL> create table t (id int, key int, value int);
SQL> insert into t (id, key)
2 select * from
3 (
4 select 1 x, 1 y from dual union all
5 select 2, 0 from dual union all
6 select 3, 1 from dual union all
7 select 4, 0 from dual union all
8 select 5, 0 from dual union all
9 select 6, ... | If there is no gaps in ID field, then this query will do the trick:
```
UPDATE TEST_T tm
SET VALUE = (SELECT CASE WHEN t1.KEY = 1 THEN 0
WHEN (SELECT MIN(ID) FROM TEST_T t2
WHERE t2.ID > t1.id
AND t2.key = 1) IS NOT NULL
... | Update rows based on values present in forthcoming rows | [
"",
"sql",
"oracle",
"oracle11g",
"oracle10g",
""
] |
I'm working on code written by a previous developer and in a query it says,
```
WHERE p.name <=> NULL
```
What does `<=>` mean in this query? Is it something equal to `=`? Or is it a syntax error?
But it is not showing any errors or exceptions. I already know that `<>` = `!=` in [MySQL](http://en.wikipedia.org/wiki/... | ### TL;DR
It's the [`NULL` safe equal](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_equal-to) operator.
Like the regular `=` operator, two values are compared and the result is either `0` (not equal) or `1` (equal); in other words: `'a' <=> 'b'` yields `0` and `'a' <=> 'a'` yields `1`.
... | is **<=>** `NULL-safe equal to operator`
This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL.
See here for the [documentation](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operat... | What is this operator <=> in MySQL? | [
"",
"mysql",
"sql",
"operators",
"spaceship-operator",
""
] |
I have a table that has a bunch of rows, but only three columns, `date`, `username` and `posts`.
`Username` has usernames, and they repeat a lot. `Posts` has a bunch of numbers. `Date` has the date something was posted in the `Y-m-D` format.
Now when I run `SELECT * FROM table WHERE date = '2014-02-20'`, I get a bunc... | Try like
```
SELECT * FROM table WHERE date = '2014-02-20' ORDER BY username,posts ASC
``` | ```
SELECT * FROM tablw WHERE date ='$something' ORDER BY username ASC, posts ASC
``` | How can I sort rows based on two columns in MySQL? | [
"",
"mysql",
"sql",
""
] |
Im quite new for all the hibernate and SQL scopes, so forgive me for the silly question.
I want to make a sql query using hibernate which will group all the results by the groupUserName.
I have the following tables in my DB:
ms\_GroupUser:
```
+-------------+---------------+----------+---------+
| groupUserId | gro... | ```
SELECT groupUserName,groupName
FROM ms_GroupUser u, ms_group g
WHERE g.groupId=u.groupId
AND u.password=654321
```
**Output**
```
| GROUPUSERNAME | GROUPNAME |
|---------------|-----------|
| BOB | TEST |
| BOB | TEST2 |
| Charlie | TEST |
```
**[Fiddle](http://sqlfiddle.... | Just simply add "groupt.groupName" in the group by. So the code will become like this
```
SELECT groupt.groupName,
usert.groupUserName
FROM Group1 AS groupt,
GroupUser AS usert
WHERE groupt.groupId = usert.groupId
AND usert.password = '654321'
GROUP BY groupt.groupName,
usert.groupUserName;... | SQL query group by results | [
"",
"mysql",
"sql",
"hibernate",
"select",
"group-by",
""
] |
I have two columns:
```
ID name
--------------
NULL Bose
NULL Bose
NULL Computer
NULL Bose
NULL Monitor
NULL Monitor
NULL Computer
NULL Bose
NULL Phone
NULL Computer
```
Need to add unique values like this:
Values should start from some number like 400.
```
ID name
------------
400 Bose
400 Bose
401 C... | Try this:
```
UPDATE your_table s
JOIN
(SELECT (@r:=@r+1) rn, t.name FROM
(SELECT DISTINCT name FROM your_table) t
,(SELECT @r:=399) nums) tab
ON tab.name = s.name
SET s.ID = tab.rn;
```
Here is working code at SQL Fiddle: <http://www.sqlfiddle.com/#!2/b831ed/1> | You can do this in various ways. One method is to use variables.
```
update table t cross join
(select @name := '',@prevname := '', @id := 399) const
set id = (case when (@prevname := @name) is null then null
when (@name := name) is null then null
when @prevname = name... | SQL query - How to add same ID values to values from another column? | [
"",
"sql",
"phpmyadmin",
""
] |
need to write a sql query to fetch all tables in a schema
that was updated on sysdate.
```
select distinct(table_name)
from All_Tab_Columns
where owner = 'DBO'
and last_analyzed = sysdate;
```
It doesn't seem to work properly. | As mentioned in answers to the question I linked to, you can use the `ORA_ROWSCN` pseudo-column to get an idea of when the table was last updated. This will example all tables in your schema and list those which were modified on the specified date, according to the `ORA_ROWSCN`. This may take a while to run, of course.... | You need to apply `TRUNC` function on `last_analyzed` and `sysdate` and then it will work
```
select distinct(table_name)
from All_Tab_Columns
where owner = 'DBO'
and trunc(last_analyzed) = trunc(sysdate);
``` | sql query to fetch all tables in a schema that was updated on sysdate | [
"",
"sql",
"oracle",
""
] |
I have the following database structure
```
table_countries
----------
country_id
country_name
table_cities
----------
city_id
country_id
city_name
table_streets
----------
street_id
city_id
street_name
table_people
----------
person_id
street_id
person_name
```
There multiple countries, which can have multiple ci... | For the expected result mentioned in your edit I would change the left joins to inner joins and select only country name with a group by clause. Note the foreign key names in the on clauses, I think you have to clarify/correct your table structures:
```
SELECT
table1.country
FROM
table1 JOIN table2 ON table1.... | ```
SELECT * FROM table1 WHERE id IN (
SELECT DISTINCT table1.id
FROM table1
LEFT JOIN table2
ON table1.id = table2.id
LEFT JOIN table3
ON table2.id = table3.id
LEFT JOIN table4
ON table3.id = table4.id
);
```
ought to do the trick then? You don't even need `DISTINCT`, but it will ma... | MySQL left join limit to one row | [
"",
"mysql",
"sql",
""
] |
In my Data Table I have a Date Column Format = `yyyy/mm/dd` and a Time column Format `hh:mm:ss`. I am trying to concat the two so I can use it in a calendar. I keep getting an error. Here is my qry:
`CAST(T0.[Date]) AS Date) + CAST(T0.[Time]) AS Time(7))`
Where am I going wrong? | probably the bracket near the [date] and [Time]
```
CAST(T0.[Date]) AS Date) + CAST(T0.[Time]) AS Time(7))
```
change to:
```
CAST(T0.[Date] AS Date) + CAST(T0.[Time] AS Time(7))
```
**UPDATED:**
The data types datetime and time are incompatible in the add operator.
```
select cast(CAST(T0.[Date] AS date)as nvarch... | Try this
```
CAST(T0.[Date] AS SmallDateTime) + CAST(T0.[Time] AS Time)
``` | CAST Date and Time in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I need to load some test data into the Channel field on my Account table. The Channel can be one of 10 different values, so I thought I'd randomly assign the Channel one of the values using a `CASE` expression along with `ABS(CHECKSUM(NewId())) % 10` like so:
```
SELECT
id,
name,
Channel =
CASE ABS... | The written form of the query is expanded to:
```
Channel =
CASE
WHEN ABS(CHECKSUM(NewId())) % 10 = 0 THEN 'Baby Only'
WHEN ABS(CHECKSUM(NewId())) % 10 = 1 THEN 'Club'
WHEN ABS(CHECKSUM(NewId())) % 10 = 2 THEN 'Drug'
WHEN ABS(CHECKSUM(NewId())) % 10 = 3 THEN 'Food'
WHEN A... | A new "random" number will be calculated for every WHEN clause - you can instead use a derived table:
```
SELECT ID, Name,
Channel =
CASE Rand
WHEN 0 THEN 'Baby Only'
WHEN 1 THEN 'Club'
WHEN 2 THEN 'Drug'
WHEN 3 THEN 'Food'
WHEN 4 THEN 'Internet'
WHEN 5 THEN ... | How does this CASE expression reach the ELSE clause? | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
Hello what I want is to write a query which will fetch me 3 column:-
1. nvarchar column1
2. integer Values column2
3. single cell of the summed column2
is it possible , I am getting the following error:-
Msg 8120, Level 16, State 1, Line 1
Column 'tablename.columnname' is invalid in the select list because it is not... | You can do it in the following way, because you need to add all non aggregated values in the group by, which makes it difficult
```
Select column1, column2, SUM(column2) OVER (PARTITION BY column1) as Total from [Table]
```
This should work.
You can do it with a subselect from your edited answer, but why do you want... | i suspect you are using some aggregate function on some columns and not listing your remaining columns in group by clause. your query should look like this.
```
select sum(column2), column1 from table1
group by column1
``` | How to create a result from sql server with a summed column | [
"",
"sql",
"sql-server",
"sum",
"correlated-subquery",
""
] |
This is my SQL CODE:
```
SELECT `qty`,`unitprice`, qty * unitprice as Stock FROM item where Stock<1000
```
but it is saying:
> #1054 - Unknown column 'Stock' in 'where clause'
how to fix it? | As documented under [Problems with Column Aliases](http://dev.mysql.com/doc/en/problems-with-alias.html):
> Standard SQL disallows references to column aliases in a `WHERE` clause. This restriction is imposed because when the `WHERE` clause is evaluated, the column value may not yet have been determined.
You must ins... | You can't have an alias in a where condition. It will only be exposed to the next layer up - the calling application, or a parent query if this is written as a subquery.
```
where qty * unitprice < 1000
``` | Mysql alias in where condition | [
"",
"mysql",
"sql",
""
] |
Writing queries (a sql file) that can run both in MySQL and PostgreSQL, everything is OK so far except the following:
```
SELECT MONTH(Date), YEAR(Date) FROM Ticket;
```
for extracting the month number (9,10,11 ..) and year (2011, 2012..) from the Date column (yes thats true, I cannot change the name of this column) ... | Well if you use an alias on the front of your field and use ***EXTRACT*** instead, the same query will work for both PostgreSQL and MySQL:
```
SELECT EXTRACT(MONTH FROM t.Date) AS MonthOfDate,
EXTRACT(YEAR FROM t.Date) AS YearOfDate
FROM Ticket t;
```
[**PostgreSQL SQL Fiddle**](http://sqlfiddle.com/#!15/4177... | Because you are open for any possible solution I have two ideas.
As long as you need to write plain sql statements I would suggest a table prepopulated with dates and their corresponding attributes in columns.
Sometimes I used a table like this:
```
ID THE_DATE THE_MONTH_OF_DATE THE_YEAR_OF_DATE ...
-------... | Any alternative to MONTH() and YEAR() functions which are common to both MySQL and PostgreSQL | [
"",
"mysql",
"sql",
"database",
"postgresql",
""
] |
I have 5000 rows of data. and I want to delete all the rows after 1000 how would I do this?
```
Delete from table
where *
limit 1000
```
is this correct? | SQL Server
```
WITH cte
AS (SELECT *,
row_number() OVER (ORDER BY some_column) AS rn
FROM TABLE)
DELETE FROM cte
WHERE rn > 1000
``` | ```
DELETE FROM TABLE
WHERE ID NOT IN
(
SELECT ID FROM TABLE LIMIT 1000
)
```
This query will :
1 - Select THE FIRST 1000 records from your database
2 - Deletes all the records that are not in the list of the first 100 records | Delete All Rows After a certain number | [
"",
"sql",
"sql-server",
""
] |
I have 2 tables Joined by StudentID and ParkingID. My Table B has duplicate parking information. Im looking to get StudentID, StudentName, ParkingSpace number and the count of duplicates. This is my first post so forgive me if I dont follow all the correct protocols here. I appreciate the help.
Example:
```
Table A:
... | Here is a solution for your problem.
```
select studentid, studentname, parkingspace , count(*) dupcount
from tablea inner join tableb on tablea.studentid=tableb.parkingid
group by studentid, studentname, parkingspace having count(*)>1
```
We count the duplicates and by `having count(*)>1` showing only real duplicate... | **Test Data**
```
DECLARE @Table_1 TABLE (StudentID VARCHAR(100),StudentName VARCHAR(100))
INSERT INTO @Table_1 VALUES
('001','Mary'),('002','Jane'),('003','Peter'),
('004','Smith'),('005','Kathy')
DECLARE @Table_2 TABLE
(ParkingID VARCHAR(100),ParkingSpace INT)
INSERT INTO @Table_2 VALUES
('001',25),('001',25),('0... | SQL Query that joins one table where the second table has duplicates | [
"",
"sql",
"join",
"duplicates",
""
] |
```
.....
temp Varchar2 (20);
e_name Varchar2 (255);
.....
Begin
e_name := e_name || temp;
Dbms_Output.Put_Line('names: ' || e_name);
Output result
-------------
names: 'John', 'Sam', 'David', 'Sam', 'John', 'Alex'
```
How do I format my e\_name to remove the duplicate names so that I have the output result
```
r... | Well you can modify your program like this
```
Begin
e_name := e_name || temp;
SELECT listagg ( names, ',' ) within GROUP (ORDER BY rn )
INTO e_name
FROM
(
SELECT level rn,
regexp_substr ( e_name, '[^,]+', 1, level ) names,
row_number ( ) over ( partition BY regexp_sub... | Replace WM\_CONCAT with LISTAGG - I'm running Oragle 10g, LISTAGG is 11g:
```
SELECT wm_concat(ename) AS employees
FROM emp_test
WHERE deptno = 20
/
Output - SMITH repeats twice:
SMITH,JONES,SCOTT,ADAMS,FORD,SMITH
SELECT wm_concat(distinct ename) AS employees
FROM emp_test
WHERE deptno = 20
/
The distinct ... | Oracle PL SQL remove duplicate data in string | [
"",
"sql",
"oracle",
"format",
""
] |
I am just starting to learn SQL.
How do you add a condition to a statement? I am trying to sort the destination to 'BNA' which is the airport code.
```
SELECT
CHARTER.CUS_CODE,
CHARTER.DESTINATION "AIRPORT",
CHARTER.CHAR_DATE,
CHARTER.CHAR_DISTANCE,
CHARTER.AC_NUMBER,
FROM C.CHARTER ;
WHERE DESTINATION = '... | The following is your query with the syntax corrected:
```
SELECT CHARTER.CUS_CODE,
CHARTER.DESTINATION "AIRPORT",
CHARTER.CHAR_DATE,
CHARTER.CHAR_DISTANCE,
CHARTER.AC_NUMBER
FROM CHARTER
WHERE DESTINATION = 'BNA';
```
1. The semicolon goes at the end only.
2. Get rid of "c." from the t... | ```
SELECT
CHARTER.CUS_CODE,
CHARTER.DESTINATION "AIRPORT",
CHARTER.CHAR_DATE,
CHARTER.CHAR_DISTANCE,
CHARTER.AC_NUMBER,
FROM C.CHARTER
WHERE DESTINATION = 'BNA' ;
```
The `;` character is a statement terminator; you only need one per SQL statement. | SQL- Adding a condition | [
"",
"sql",
"conditional-statements",
""
] |
In Microsoft SQL Server 2012, I need to remove adjacent duplicate rows in the `Flow` column below, and just keep the first ones (marked `*` to illustrate). After that, I need to take the time difference between the `1`s and `0`s for all rows and get the total cumulative time.
```
Record Number Downhole Time Fl... | I believe this does the job you requested:
```
WITH FlowIntervals AS (
SELECT
FromTime = Min(D.[Downhole Time]),
X.ToTime
FROM
dbo.vLog D
OUTER APPLY (
SELECT TOP 1 ToTime = D2.[Downhole Time]
FROM dbo.vLog D2
WHERE
D.[Downhole Time] < D2.[Downhole T... | Not sure what kind of database you are using. Here is a solution with analytical functions and Oracle:
```
SELECT
un,
mytime,
flow,
lead (mytime) OVER (ORDER BY UN) lead_time,
(lead (mytime) OVER (ORDER BY UN) - mytime)*24*60 minutes
FROM ( SELECT un,
mytime,
flow,
... | In SQL, remove adjacent duplicate rows and perform time calculation | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have some code record in Oracle DB
for example:
A00105XYZ
CC000036QWE
How to write the criteria, if users input A105XYZ, CC36QWE, these records can still be searched? | You'll probably want to use a regular expression:
```
SELECT STR, REGEXP_REPLACE(STR,'([^[:digit:]]*)(0*)(.*)','\1\3') NEW_STR
FROM
(SELECT 'A00105XYZ' STR FROM DUAL UNION
SELECT 'CC000036QWE' STR FROM DUAL UNION
SELECT 'FD403T' STR FROM DUAL UNION
SELECT '000000010' STR FROM DUAL)
╔═════════════╦═════════╗
║ ... | One way would be to replace the `0`s on both sides:
```
where replace(code, '0', '') = replace (:var, '0', '')
```
Note that `A00105XYZ` will also match `A15XYZ`. | Oracle, how to match leading zero number in varchar? | [
"",
"sql",
"oracle",
"varchar",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.