Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a DAG in my relational database (Firebird) with two tables `edge` and `node` (adjacency list model). I want to query them recursively, but found recursive queries very inefficient. So I tried to implement triggers to maintain the transitive closure following the Dong et.al. paper <http://homepages.inf.ed.ac.uk/l...
I just fixed up a slow delete operation by extending to the transitive reflexive closure table model described here: <http://www.dba-oracle.com/t_sql_patterns_incremental_eval.htm>. It took a little more work to fully maintain the paths count within it, but it payed off big when deletes went from a 6 second each indivi...
SQL is not the right tool for dealing with graphs. Use one of these : <http://en.wikipedia.org/wiki/Graph_database> I like very much ArangoDB, wich have a syntaxe close to mongodb.
How to maintain a transitive closure table efficiently?
[ "", "sql", "firebird", "directed-acyclic-graphs", "transitive-closure-table", "" ]
I have a table in an SQL Server database with a date field in it, presented as varchar in `yyyymmddhhnn` format (where `nn` is minutes). For example, `200012011200` would be `01 Dec 2000 12:00`. I need to convert this to a `datetime` value, but none of the `convert` codes seems to cover it. It's closest to ISO format `...
Try this ``` declare @t varchar(20) set @t='200012011200' select cast(stuff(stuff(@t, 11,0,':'),9,0,' ') as datetime) ```
``` SELECT convert(varchar, cast(SUBSTRING('200012011200',1,4)+ '-'+SUBSTRING('200012011200',5,2)+ '-'+SUBSTRING('200012011200',7,2)+ ' '+SUBSTRING('200012011200',9,2)+ ':'+SUBSTRING('200012011200',11,2)+ ':00'+ '.000' AS DATETIME), 109) ``` This will result in `Dec 1 2000 12:00:00:000PM` Using the 112 as parameter w...
Convert string formatted as yyyymmddhhnn to datetime
[ "", "sql", "sql-server", "datetime", "" ]
Thanks in advance for your help. I have two tables, a reference table and a details table. The reference table lists current production step of an order paired with the next step, as so: **Reference Table** ``` Current_Step | Next_Step | ID ------------------------------------------------- Step 1 ...
``` declare @Today datetime select @Today = dateadd(dd, datediff(dd, 0, getdate()), 0) update od2 set start_date = @Today, planned_end = dateadd(dd, od2.planned_duration, @Today) from order_details as od inner join reference_table as rt on rt.current_step_id = od.step_id inner join order_details as od...
Try this (for SQL Server 2005): ``` UPDATE n SET Start_Date = CONVERT(VARCHAR, GETDATE(),112), Planned_end = DATEADD(dd, n.Planned_Duration, CONVERT(VARCHAR, GETDATE(),112)) FROM order_details AS d JOIN refernce_table AS r ON d.step_id= r.ID JOIN order_details AS n ON n.step_id = CONVERT(in...
Updating a row in the same SQL table based on information from another table - MSSQL
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
Are there any command line tools (Linux, Mac, and/or Windows) that I could use to scan a delimited file and output a DDL create table statement with the data type determined for me? Did some googling, but couldn't find anything. Was wondering if others might know, thanks!
[DDL-generator](https://github.com/catherinedevlin/ddl-generator) can do this. It can generate DDL's for YAML, JSON, CSV, Pickle and HTML (although I don't know how the last one works). I just tried it on some data exported from Salesforce and it worked pretty well. Note you need to use it with Python 3, I could not ge...
You can also try <https://github.com/mshanu/idli>. It can take csv file as input and can generate create statement with appropriate types.It can generate for mysql, oracle and postgres. I am actively working on this and happy to receive feedback for future improvement
Generate DDL SQL create table statement after scanning CSV file
[ "", "sql", "csv", "ddl", "delimited", "" ]
I have a oracle table which is similar to the one below which stores people's lastname firstname and age. If last name is same people belong to same family. ``` LastName FirstName Age =========================== 1 miller charls 20 2 miller john 30 3 anderson peter 45 4 Bates ...
`DENSE_RANK()` is a ranking function which generates sequential number and for ties the number generated is the same. I prefer to use `DENSE_RANK()` here considering that a family can have twins, etc. ``` SELECT Lastname, FirstName, Age FROM ( SELECT Lastname, FirstName, Age, ...
Another way, a bit *shorter*: ``` select lastname , max(firstname) keep(dense_rank first order by age) as first_name , max(age) keep(dense_rank first order by age) as age from you_table_name group by lastname order by lastname ``` Result: ``` LASTNAME FIRST_NAME AGE -------- ----------...
selecting a row using MIN or ROWNUM
[ "", "sql", "oracle", "" ]
I have something like - ``` IF EXISTS (SELECT 1 FROM systable st JOIN sysuserperm sup ON st.creator = sup.user_id WHERE sup.user_name = 'TEST' AND st.table_type = 'BASE' AND st.table_name = 'Table1') THEN IF EXISTS (SELECT 1 FROM systable st ...
Try this one out, ``` SELECT 1 FROM systable st INNER JOIN sysuserperm sup ON st.creator = sup.user_id WHERE sup.user_name = 'TEST' AND st.table_type = 'BASE' AND st.table_name IN ('Table1', 'table2') GROUP BY sup.user_name, st.table_type HAVING COUNT(DISTINCT st.table_...
This should do the task ``` IF EXISTS ( (SELECT 1 FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='TABLE1') INTERSECT (SELECT 1 FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='TABLE2') ) ```
Check for multiple tables existence using single exists query?
[ "", "sql", "sybase", "exists", "" ]
I'm getting this error: > 1452 - Cannot add or update a child row: a foreign key constraint > fails. I've located them and try to get rid of the references with ``` alter table tillhör drop foreign key kat_id; ``` But getting this error instead: > #1025 - Error on rename of '.\recept\tillh@1ir' to > '.\recept#sql2...
Before you query run ``` SET FOREIGN_KEY_CHECKS=0 ``` then set it to 1 after you`re done.
I face same problem. I solve this issue by clearing, i.e. deleting all data from child table and successfully done. This is occur if child table contain some data with the foreign key that that are not in parent table i.e, if there are two table called **Person** (with column id, name, address) and **order**(with colu...
1452 - Cannot add or update a child row: a foreign key constraint fails
[ "", "mysql", "sql", "foreign-keys", "" ]
I have two tables: - table 1 with id, firstname and lastname - table 2 with t1\_id, firstname and lastname I'd like a SQL query (if possible, not a PL/SQL) to update table2 with table1's id when I have a unique match on firstname and lastname the word "unique" here is my problem : ``` update table2 t2 set t1_id = (...
``` merge into table2 d using ( select firstname, lastname, max(id) id from table1 t1 group by firstname, lastname having count(0) = 1 ) s on (d.firstname=s.firstname and d.lastname=s.lastname) when matched then update set t1_id = s.id; ```
If you want to set the id to NULL in case you find duplicate entries or no entries at all in table1 then simply: ``` update table2 t2 set t1_id = ( select case when min(id) = max(id) then min(id) else null end from table1 t1 where t1.firstname=t2.lastname and t1.lastname=t2.lastname ) ```
How to update table2 with table1's id only on a unique match
[ "", "sql", "oracle", "" ]
I have SQL syntax like this : ``` SELECT FORM_NO, SUM(QTY) as QTY FROM SEIAPPS_QTY WHERE FORM_NO = '1' AND STATUS_QTY='OK' ``` But facing problem with error like this : ``` ORA-00937: not a single-group group function ``` I saw error from FORM\_NO, how can I include that FORM\_NO ? Please advice. Thanks
In Oracle you need to use GROUP BY on the values you wish to retrieve (that are not in a group function): ``` SELECT FORM_NO, SUM(QTY) as QTY FROM SEIAPPS_QTY WHERE FORM_NO = '1' AND STATUS_QTY='OK' GROUP BY FORM_NO ```
You need a group by ``` SELECT FORM_NO, SUM(QTY) as QTY FROM SEIAPPS_QTY WHERE FORM_NO = '1' AND STATUS_QTY='OK' GROUP BY FORM_NO ``` -Or- Since you're selecting a single form you can drop the form number ``` SELECT SUM(QTY) as QTY FROM SEIAPPS_QTY WHERE FORM_NO = '1' AND STATUS_QTY='OK' ``` -Or- If you...
SQL Cant Include Column Table after SUM column table in SELECT SYNTAX
[ "", "sql", "oracle", "" ]
I need to perform a query that find values based on 1 field if the 2nd field is same Example table: ``` id, what, why 1, 2, 2 2, 3, 4 3, 3, 2 ``` So I want the results to return what 2 and 3 because they both have why of 2. But the why (2) is unknown so I only what to know if the combination of what (2 and 3) have ...
Use a self-join. ``` SELECT t1.what FROM Table t1 JOIN Table t2 ON t1.why = t2.why and t1.what != t2.what ```
``` SELECT what FROM YourTable A WHERE EXISTS(SELECT 1 FROM YourTable WHERE what <> A.what AND why = A.why) ``` [**Here is a demo**](http://sqlfiddle.com/#!2/62da8/1) of this.
Find rows with same value of a column
[ "", "mysql", "sql", "" ]
Hi every one i want to use case statement in join using this query and got error ``` Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID FROM F_SALESINVOICEITEM SII INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID INNER JOIN #TempTableSearch ts ON CASE WHEN ts.ACCOUNTTYPE = '1'...
IT should be, ``` ON ts.ACCOUNTID = CASE WHEN ts.ACCOUNTTYPE = '1' THEN SI.TENANCYID WHEN ts.ACCOUNTTYPE = '2' THEN SI.EMPLOYEEID WHEN ts.ACCOUNTTYPE = '3' THEN SI.SUPPLIERID WHEN ts.ACCOUNTTYPE = '4' THEN SI.SALESCUSTOMERID ...
Instead of using CASE, I'd much rather do this: ``` Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID FROM F_SALESINVOICEITEM SII INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID INNER JOIN #TempTableSearch ts ON (ts.ACCOUNTTYPE='1' AND ts.ACCOUNTID=SI.TENANCYID) OR ...
Use Case Statement in Join
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I have a ***stored procedure*** which returns a list of contacts. Since there are many contacts, and for performance reasons, I wish to retrieve the contacts in a page-wise manner, whereby only 20 contacts are fetched in the each instance. A button on my form will allow me to go to the next page, and once the button i...
I found it (By using an ***orderedIndex*** ); ``` ALTER PROCEDURE [dbo].[GetAllContacts] (@searchVal varchar(500) , @CurrentPage int , @PageSize int) AS BEGIN DECLARE @RESULTS TABLE ( orderedIndex int IDENTITY(1...
You can use a [common table expression](http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) in conjunction with the [ROW\_NUMBER()](http://technet.microsoft.com/en-us/library/ms186734.aspx) function ``` ALTER PROCEDURE [dbo].[GetAllContacts] @searchVal VARCHAR(500), @page INT = NULL, @...
SQL - Retrieve data pagewise
[ "", "sql", "sql-server", "performance", "stored-procedures", "sql-server-2012", "" ]
I'm looking to write an ActiveRecord query and this is what I have below. Unfortunately you can't use OR like this. What's the best way to execute? `category_ids` is an array of integers. ``` .where(:"categories.id" => category_ids).or.where(:"category_relationships.category_id" => category_ids) ```
One way is to revert to raw sql... ``` YourModel.where("categories.id IN ? OR category_relationships.category_id IN ?", category_ids, category_ids) ```
Keep the SQL out of it and use ARel, like this: ``` .where(Category.arel_table[:id].in(category_ids). or(CategoryRelationship.arel_table[:category_id].in(category_ids)) ```
Rails ActiveRecord where or clause
[ "", "sql", "ruby-on-rails", "activerecord", "where-clause", "" ]
i have problem trying to delete record from my VS 2012 and i'm using sql server 2012, this is my task from my lecturer, and i cant solved it now this is what i have ``` Private Sub bt_hapus_Click(sender As Object, e As EventArgs) Handles bt_hapus.Click Try Dim sqlda As New SqlClient.SqlDataAdapter("Delete...
A delete command is executed using an SqlCommand and the [ExecuteNonQuery](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx) method. Your code should be ``` Try Dim cmd = New SqlClient.SqlCommand("Delete from tabelpasien where No_Rkm_Mds=@rkm", Me.SqlConnection1) c...
You have forgotten your single quote marks I.E." ' " from around your condition. Your statement Should be `Delete From tabelpasien where No_Rkm_Mds='" + Me.txt_rkm_mds.Text + "'"`
VB .NET SQL Delete error 'incorrect syntax near '='
[ "", "sql", "vb.net", "visual-studio-2012", "sql-server-2012", "vb.net-2010", "" ]
I have a table with following columns: 1. User\_Id 2. Work\_Date ``` create table Test_Seq(user_id number, work_date date); ``` It has following data: ``` insert into Test_Seq values (1, '01-SEP-2013'); insert into Test_Seq values (1, '02-SEP-2013'); insert into Test_Seq values (1, '06-SEP-2013'); insert into Test_...
Here's one approach. * In this approach, all the working days, holidays and weekends are put together in the same table. * Then the starting of each sequence is identified with dates ordered in descending order. * Each sequence is given a number. * Max and Min of first sequence is found out, which is the required resu...
you need a PL/SQL function. Either one that gives you the pipelined output or one that tells you if days are following each other. Here is a solution for the second way: This is the function needed. It returns 0 for false and 1 for true, due to the lack of a boolean data type in Oracle SQL: ``` create or replace func...
how to get start date and end date of sequence days in table?
[ "", "sql", "oracle", "" ]
I've got a PHP application that uses PDO with prepared statements, both in PostgreSQL and MySQL, and I'm wondering if there's a performance hit when preparing the exact same statements each time before executing it. In pseudo-code, an example would be something like: ``` for ($x=0; $x<100; $x++) { $obj = PDO::pre...
Yes, it somewhat defeats the purpose of using prepared statements. Preparing allows the DB to pre-parse the query and get things ready for execution. When you do execute the statement, the DB simply slips in the values you're providing and performs the last couple steps. When you prepare inside a loop like that, all o...
Yes, there's a performance hit. The prepare step has to parse the SQL string and analyze it to decide which tables it needs to access and how it's going to do that (which indexes to use, etc.). So if you prepare() once before the loop begins, and then just execute() inside the loop, this is a cost savings. This is an ...
Performance Problems When Preparing Statement Multiple Times
[ "", "mysql", "sql", "performance", "postgresql", "prepared-statement", "" ]
The objective here is to be able to query a database providing it with a **Journey**, based on the **Journey** the database will return all of the **Stop Codes** that run through this journey. So for example I need to be able to say, "Select all of the stop codes that run through journey 34". This should then only ret...
You have a **many to many** relationship between Stop Codes and Journeys. To eradicate this, you need to decompose the relationship. In order to do this, you need an intermediary table, let's call it JourneyStopCode, which will look like: ``` JourneyStopCode: JourneyStopCodeID (primarykey) JourneyID StopCodeID ``` T...
Journeys to stop codes is a many to many relation ship, you want a join table most likely. ``` Table 1 : SID | Stop Code | Long | lat 0 | ASDFSAFA | 1 | 2 1 | sdDSGSDGS | 4 | 0 .... Table 2 : Journey | Description 0 | Blah blah blah Table 3 : Journey | SID ...
Normalizing a database column
[ "", "mysql", "sql", "database-design", "database-normalization", "" ]
I'm trying to create a table in postgresql to hold user Work Items. Each Work Item will have a unique ID across the system, but then will also have a friendly sequential ID for that specific user. So far I have been just using: ``` CREATE TABLE WorkItems ( Id SERIAL NOT NULL PRIMARY KEY, ... ); ``` but I don't k...
You said that you *also* have a globally unique key. You can use that to solve your concurrency issues. If you allow the user work item number to be null, you can first create the work item, then do something like this to assign it a "friendly" number. (T-SQL dialect, @workItemID is the globally unique ID): ``` Update...
The most common way to have an auto-generated ID inside a table is the one using a sequence, if the sequence used on a `int`/`bigint` column then I see no reason why this won't be user-friendly. A demo follows on `Postgresql 13.6` assuming `postgres` is the user under which table and sequence will belong: * Define a ...
How to create sequential ID's per user in Postgresql
[ "", "mysql", "sql", "sql-server", "postgresql", "" ]
In SQL Server you can do this: ``` DECLARE @ID int SET @ID=1 SELECT * FROM Person WHERE ID=@ID ``` What is the equivalent Oracle code? I have spent some time Googling this, but I have not found an anwser.
The following link/page from the Oracle® Database PL/SQL User's Guide provides an overview of variable declaration: <http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/constantvar_declaration.htm> The sample below was taken from another page in the user’s guide. ``` DECLARE bonus NUMBER(8,2); emp_id NUMBER(6...
You create a bind variable ``` VARIABLE ID number ``` Assigning the variable must be done in a PL/SQL block (execute is a short cut to do that) ``` execute :id := 1 ``` You can then use it in a sql statement ``` SELECT * FROM Person WHERE ID=:ID ; ```
Translate TSQL to PLSQL
[ "", "sql", "sql-server", "oracle", "" ]
I have the following query (executed through PHP). How can I make it showing ZEROs if the result is NULL and is not shown. ``` select count(schicht) as front_lcfruh, kw, datum from dienstplan left join codes on dienstplan.schicht = codes.lcfruh left join personal on personal.perso_id = dienstplan.per...
I'm not entirely sure I understand the question, but I think you want this: ``` select count(codes.lcfruh) as front_lcfruh, dienstplan.kw, dienstplan.datum from dienstplan left join codes on dienstplan.schicht = codes.lcfruh and codes.lcfruh <> '' left join personal on personal.perso_id = dienstplan....
If you have no matching rows, then MySQL will return an **empty set** (here I have defined the fields at random, just to run the query): ``` mysql> CREATE TABLE dienstplan (kw varchar(10), datum integer, schicht integer, perso_id integer); Query OK, 0 rows affected (0.00 sec) mysql> CREATE TABLE codes (lcfruh varchar...
showing Zero if sql count is NULL
[ "", "mysql", "sql", "count", "" ]
This is a common SQL query for me: ``` update table1 set col1 = (select col1 from table2 where table1.ID = table2.ID) where exists (select 1 from table2 where table1.ID = table2.ID) ``` Is there any way to avoid having two nearly identical subqueries? This query is an obvious simplification but performance suffers an...
Unfortunately Informix don't support the FROM clause at UPDATE statement. The way to workaround and you will get better results (performance) is change the UPDATE to MERGE statement. This will work only if your database is version 11.50 or above ``` MERGE INTO table1 as t1 USING table2 as t2 ON t1.ID = t2.ID WHEN ...
Update with inner join can be used to avoid subqueries something like this: ``` update t1 set col1 = t2.col1 from table1 t1 inner join table2 t2 on t1.ID = t2.ID ```
Using subquery in an update always requires subquery in a where clause?
[ "", "sql", "informix", "" ]
I have the following SQL Query: ``` SELECT Score FROM ( SELECT SUM(Score) AS Score FROM ResponseData WHERE ScoreGUID='baf5dd3e-949c-4255-ad48-fd8f2485399f' GROUP BY Section ) AS Totals GROUP BY Score ``` And it produces this: ``` Score 0 1 2 2 4 5 5 ``` But, what I really want is the number of each of the scores, l...
Try this code: ``` SELECT Score,count(score) as cnt FROM ResponseData WHERE ScoreGUID='baf5dd3e-949c-4255-ad48-fd8f2485399f' GROUP BY Score ```
Something like: ``` SELECT Score, COUNT(Score) FROM ResponseData WHERE ScoreGUID='baf5dd3e-949c-4255-ad48-fd8f2485399f' GROUP BY Score ``` should work. But I don't understand the meaning of your: ``` group by Section ```
SQL Query to show count of same results
[ "", "sql", "" ]
I have a bunch of rows in my db that signify orders, i.e. ``` id | date --------------------- 1 | 2013-09-01 2 | 2013-09-01 3 | 2013-09-02 4 | 2013-09-04 5 | 2013-09-04 ``` What I'd like is to display the count of rows per day, including missing days, so the output would be: ``` 2013-09-01 | 2 2013-09-02 | 1 20...
If you want to get data for last 7 days, you can generate your pseudo-table via `UNION`, like: ``` SELECT COUNT(t.id), fixed_days.fixed_date FROM t RIGHT JOIN (SELECT CURDATE() as fixed_date UNION ALL SELECT CURDATE() - INTERVAL 1 day UNION ALL SELECT CURDATE() - INTERVAL 2 day UNION ALL SELEC...
Try Something like this! ``` SELECT c1, GROUP_CONCAT(c2 ORDER BY c2) AS 'C2 values' FROM table GROUP BY c1; ``` To retrieve a list of c1 values for which there exist specific values in another column c2, you need an `IN` clause specifying the c2 values and a `HAVING` clause specifying the required number of ...
Count/group rows based on date including missing
[ "", "mysql", "sql", "" ]
I have a table with three columns ``` Product Version Price 1 1 25 1 2 15 1 3 25 2 1 8 2 2 8 2 3 4 3 1 25 3 2 ...
If Teradata supports the `ROW_NUMBER` analytic function: ``` SELECT Product, Version, Price FROM ( SELECT atable.*, /* or specify column names explicitly as necessary */ ROW_NUMBER() OVER (PARTITION BY Product ORDER BY Price DESC, Version DESC) AS rn FROM atable ) s WHERE rn =...
Using Teradata SQL this can be further simplified: ``` SELECT * FROM atable QUALIFY ROW_NUMBER() OVER (PARTITION BY Product ORDER BY Price DESC, Version DESC) = 1; ``` The QUALIFY is a Teradata extension to Standard SQL, it's similar to a HAVING for GROUP BY, it filters the result of a window function...
SQL Max over multiple versions
[ "", "sql", "max", "greatest-n-per-group", "teradata", "" ]
I'm using db2, not sure what version. I'm getting an overflow error when trying to sum a table. I thought that I would be able to cast the sum to a BIGINT which seems to work for a sum total but I'm looking to get a percentage and when I cast to a BIGINT my data is inaccurate. How do I get an accurate percentage for Pe...
I was able to get the correct results converting to double. ``` SUM(CAST(FAT.ORDERS_B AS DOUBLE))/sum(CAST(FAT.Amount AS DOUBLE)) AS Percent_DeliveredB, ```
It is giving you a correct result, as any value less than 1, when cast to an integer (or BIGINT for that matter) will be truncated to 0, obviously. If you are expecting a fractional number, use DECIMAL or FLOAT data types: ``` cast(SUM(FAT.ORDERS_B) as decimal(10,2)) / cast(sum(FAT.Amount) as decimal(10,2)) AS Percen...
Arithmetic overflow or other arithmetic exception occurred solution?
[ "", "sql", "db2", "aggregate-functions", "" ]
I'm not sure the title is clear, but this is the situation. I have a table that looks like this: ``` ID inputID value 4 1 10 4 2 20 4 3 100 6 1 15 6 2 20 6 3 44 ``` I have user input that gives me the values for inputID 1 and inputI...
What about something like this? ``` SELECT t1.ID FROM table t1 INNER JOIN table t2 ON t1.ID = t2.ID WHERE t1.inputID = 1 AND t1.value = @input1 AND t2.inputID = 2 AND t2.value = @input2 ```
``` select ID from T as T1 where inputID=1 and value=10 and EXISTS(select id from T where ID=T1.ID and inputID=2 and value=20) ```
SQL query to get ID from multiple inputs
[ "", "sql", "" ]
I have a table that has employee's daily totals with start date, I need to look back 3 months to see how many days an employee has worked. Here is my sql query: ``` SELECT EMPNO, CONVERT(VARCHAR(10), STARTDATE,101), ROW_NUMBER() OVER (ORDER BY PERSONNUM) AS 'ROWCOUNT' FROM EMPLOYEE WHERE START...
You can use this CTE with `ROW_NUMBER` and `COUNT(*)OVER`: ``` WITH CTE AS ( SELECT EMPNO, STARTDATE, RN = ROW_NUMBER() OVER (PARTITION BY EMPNO ORDER BY STARTDATE DESC), [ROWCOUNT] = COUNT(*) OVER (PARTITION BY EMPNO) FROM dbo.EMPLOYEE WHERE STARTDATE BETWEEN DATEADD(month, -3, GETD...
Can't you use a count? ``` SELECT EMPNO, COUNT(EMPNO) AS [ROWCOUNT] FROM EMPLOYEE WHERE STARTDATE BETWEEN DATEADD(month, -3, GETDATE()) and GETDATE() GROUP BY EMPNO ORDER BY EMPNO ```
SQL 2008 - I need to count number of rows per employee in given time frame
[ "", "sql", "sql-server", "" ]
In Symfony2 and Doctrine I would like to execute a query that returns a count and a group by. Here's what I've tried. This is the SQL I want to run: ``` SELECT `terrain_id` , COUNT( * ) FROM `Partie` WHERE 1 =1 GROUP BY `terrain_id` ``` **With my entity:** ``` class Partie { /** * @var integ...
You'll probably want to go with a [Native Query](http://docs.doctrine-project.org/en/latest/reference/native-sql.html) ``` $sql = "SELECT terrain_id as terrain, count(*) AS count " ."FROM Partie " ."GROUP BY terrain_id;"; $rsm = new ResultSetMapping; $rsm->addScalarResult('ter...
This error occurs on this line : `select('count(p), p.terrain')` where you are trying to use `p` alias that doesn't exist anymore. The `select` method override the default alias of the `createQueryBuilder()`. To avoid this, use `addSelect` instead or specify clearly the `from` method. Try this : ``` public function ge...
symfony2 - Doctrine - How to do a multiple select with a count and group by
[ "", "sql", "symfony", "doctrine-orm", "" ]
Consider three tables - ``` users id | type -----------|------------ 1 | a 2 | b 3 | c types id | type -----------|------------ a | X a | Y b | X c | X c | Y c | Z trainin...
Try ``` SELECT DISTINCT u.id FROM users u JOIN types t ON u.type = t.type LEFT JOIN training_status s ON u.id = s.id AND t.training = s.training WHERE s.status IS NOT NULL GROUP BY u.id HAVING COUNT(t.type) = SUM(CASE WHEN s.status = 'S' THEN 1 ELSE 0 END) ``` or ``` SELECT DISTINCT u.id FROM users u ...
Try this ``` SELECT * FROM users WHERE id NOT IN ( SELECT u.id FROM users u JOIN types t ON u.type = t.type LEFT JOIN training_status s ON u.id = s.id AND t.training = s.training WHERE s.status IS NULL OR s.status = 'F') ```
MYSQL:SQL query to return a row only if all the rows satisfy a condition
[ "", "mysql", "sql", "" ]
I read the following question that has relevance, but the replies didn't satify me: [MySQL: #126 - Incorrect key file for table](https://stackoverflow.com/q/2011050/570796) --- ## The problem When running a query I get this error > ERROR 126 (HY000): Incorrect key file for table` ## The question When I'm trying t...
It appears that your query is returning a large intermediate result set requiring the creation of a temporary table and that the configured location for mysql temporary disk tables (/tmp) is not large enough for the resulting temporary table. You could try increasing the tmpfs partition size by remounting it: ``` mou...
If your `/tmp` mount on a linux filesystem is mounted as overflow, often sized at 1MB, ie ``` $ df -h Filesystem Size Used Avail Use% Mounted on udev 7.9G 12K 7.9G 1% /dev tmpfs 1.6G 348K 1.6G 1% /run /dev/xvda1 493G 6.9G 466G 2% / none 4.0K 0 4.0K 0% /sys...
MySQL, Error 126: Incorrect key file for table
[ "", "mysql", "sql", "mysql-error-126", "" ]
i want to count after `group by`, not the total line just want to count by the categories after `group by` my result is like ``` course lecturer comp1111 Jim comp1100 Jim comp1100 Jim infs2321 Jess infs2321 Jess econ1222 Helen ``` my result after count should be ``` lecturer count Ji...
I don't see why you want a group by after you have grouped. You get your desired result by doing just one group. Please have a look at this [sqlfiddle](http://sqlfiddle.com/#!2/420d6/2/0) to see it working live. ``` CREATE TABLE Table1 (`course` varchar(8), `lecturer` varchar(5)) ; INSERT INTO Table1 (`course...
Try this. It might work ``` SELECT LECTURER, COUNT(*) FROM (SELECT LECTURER, COURSE FROM TABLE WHERE GROUP BY LECTURER, COURSE ) GROUP BY LECTURER; ```
IN SQL count after group by
[ "", "sql", "database", "count", "group-by", "" ]
I'm new to if-then SQL statements. I only know the basics (select, update, insert with joins etc.), so it will be helpful if you could help me with the syntax in this scenario. I have a table that holds customer's activities, let's say I'm a dentist, and I store a specific activity, and when using my software to check...
I think this should work. You can change the CASE based on your requirement. ``` select ACTIVITY.ID, ACTIVITY.DATES, ACTIVITY.INSURANCE_ID ACTIVITY.AMOUNT, ACTIVITY.INSURANCE_AMOUNT, CASE WHEN TO_DATE >= sysdate THEN ACTIVITY.AMOUNT * ((100 - ACTIVITY.INSURANC...
You can add a CASE expression to return the `ACTIVITY.INSURANCE_AMOUNT` value conditionally: ``` SELECT ACTIVITY.ID, ACTIVITY.DATES, ACTIVITY.INSURANCE_ID ACTIVITY.AMOUNT, ACTIVITY.INSURANCE_AMOUNT, ACTIVITY.AMOUNT * (1 - CASE WHEN EXISTS ( ...
What am I doing wrong in this SQL Query?
[ "", "sql", "oracle", "" ]
In my database there are lots of sequences, triggers and tables. I'm confused each time which table is associated to which trigger(and sequence). How to see these list in single query?
In oracle, you cannot find which sequence is used on which table, it is not associated on table level. For that you need to find the code, and search for the sequence where it is been used, may be it is used on before insert trigger or in the PL/SQL code. For trigger, you can see the data dictionary views ``` select ...
In sql server, you can use sys.triggers and sys.tables like, ``` select ta.name AS 'TableName', tg.name 'TriggerName' from sys.triggers tg INNER JOIN sys.tables ta ON tg.parent_id = ta.object_id ```
how to see list of tables and list of trigger(and sequences)?
[ "", "sql", "oracle", "triggers", "sequence", "" ]
I have start and end weeks for a given customer and I need to make panel data for the weeks they are subscribed. I have manipulated the data into an easy form to convert, but when I transpose I do not get the weeks in between start and end filled in. Hopefully an example will shed some light on my request. Weeks start ...
I see two ways to do it. I would go for an array approach, since it will probably be the fastest (single data step) and is not that complex: ``` data RESULT (drop=start_week end_week); set YOUR_DATA; array week_array{62} week0-week61; do week=0 to 61; if week between start_week and end_week then we...
Use an array to create the variables. The one gotcha is SAS arrays are 1 indexed. ``` data input; input ID Start_week End_week; datalines; 1 6 61 2 0 46 3 45 61 ; data output; array week[62] week0-week61; set input; do i=1 to 62; if i > start_week and i<= (end_wee...
tracking customer retension on weekly basis
[ "", "sql", "sas", "proc-sql", "" ]
I would like to write a sql query that returns all values greater than or equal to x and also the first value that is not greater than x. For example if we have a table containing values 1, 2, 3, 4, 5 and x is 3, I need to return 2, 3, 4, 5. The fact that my example includes evenly spaced integers does not help becau...
union is your best bet. paste together the set of all values greater than x, and the largest value less than x. Something like the following should work: ``` SELECT n FROM table WHERE n > $x ORDER BY n DESC UNION SELECT n from table WHERE n < $x ORDER By n DESC LIMIT 0,1; ```
``` SELECT <columns> -- you want in the result FROM tableX WHERE columnX >= ( SELECT MAX(columnX) FROM tableX WHERE columnX < @x -- @x is the parameter, 3 in your example ) ; ```
SQL Lower Bound?
[ "", "mysql", "sql", "" ]
I want to be able to do a SQL Query that gets all numbers that end in .005 ``` Select * from amount where (numbers end in X.XX5) ``` I don't care what the numbers are for X
I am assuming you don't care what the first and second digit after the decimal is.Try this: ``` select * from MyTable where MyField like '%.__5' ``` The % specifies a substitution for 0 or more characters, and the underscores are a substitute for a single character. If there are digits after the 5, use ``` select ...
``` SELECT * FROM amount WHERE numbers LIKE '%.005'; ```
SQL Query for .005
[ "", "sql", "" ]
I have a big problem that I've been trying to tackle. Reading older similar issues hasn't been fruitful. My table has columns [id], [parentid], [data1], [data2] etc. There are some cases where only one record has same [parentid] and others have 2-10. I would like to group by [parentid] and print out all data of the r...
Can values in your ID column be reused? If no, then juergen's answer will work. If they can be reused, you will need to use the same table twice in your query, once to get the max id for each parent id, and once to get the row for each max id/parent id. Like so: ``` select t1.* from aTable t1, (select parentid, max(id...
``` select * from your_table where id in ( select max(id) from your_table group by parentid ) ```
Selecting * from max id when grouping by parentid (MySQL)
[ "", "mysql", "sql", "crystal-reports", "qlikview", "" ]
Hello i need help here... my query shows the folllowing result: ``` Id name color Version 1 leather black 1 1 leather brown 2 2 suede brown 1 3 cloth green 1 3 cloth blue 2 ``` i want to display the fol...
A simple one (if you know at design time the maximum number of colors you could possibly have) ``` drop table my_test; create table my_test ( id number, name varchar2(32), color varchar2(32), version number); insert into my_test values(1,'leather','black',1); insert into my_test val...
You're a little all over the place with your database type...is it mysql or oracle? I'm guessing oracle by your select statement anyway. I'm using 'join' based syntax, I find it easier to read than what you have here. Take a select statement with version 1 and left join it to a select statement with version 2. If there...
display result - data from 1 column divided into 2 columns depending on criteria
[ "", "mysql", "sql", "oracle", "toad", "" ]
I have 3 tables in an SQL Server 2008 database. The first table contains users names, the second contains privileges and the last links the first two tables: **USERS** (`ID` integer, `NAME` varchar(20)); **PRIVS** (`ID` integer, `NAME` varchar(50)); **USERS\_PRIVS** (`USERID` integer, `PRIVID` integer); For example...
``` SELECT Name, [Add Invoice],[Edit Invoice],[Delete Invoice] FROM (SELECT U.Name AS Name, P.Name AS PrivName FROM USERS_PRIVS UP INNER JOIN Users U ON UP.UserID = U.id INNER JOIN Privs P ON UP.PrivID = P.id) SB PIVOT( count(SB.PrivName) FOR SB.PrivName in ([Add Invoice],[edit Invoice],[Delete Invoice])) AS ...
Here's a Demo on [SqlFiddle](http://sqlfiddle.com/#!3/650f1/22/0). ``` with cl as ( select u.NAME , case when p.ID = 1 then 'Y' else 'N' end 'Add Invoice', case when p.ID = 2 then 'Y' else 'N' end 'Edit Invoice', case when p.ID = 3 then 'Y' else 'N' end 'Delete Invoice' from USERS u inner join USERS_PRIVS up on u.ID ...
Return Table from SQL Query
[ "", "sql", "sql-server-2008-r2", "" ]
I'm a new to `ASP.Net`, and this is my first ASP project. Hope you dont mind if my problem is so simple with some people. I'm programming a `Student's Forum`. In `Comment.aspx`, I use Repeater Control to get all comment (for each topic) and display them order by Time desc. ``` <asp: Repeater.... ....// </asp: Repeat...
You can put the repeater under the UpdatePanel and rather than refreshing after every few seconds . I will make a very light ajax method either using PageMethod or jquery (if allowed) to check if the count is changed , If only the count is change we can trigger the updatePanel refresh. <http://encosia.com/easily-refres...
You can follow this link. By this artical you will learn also about AJAX [Refresh Grid After some interval](http://csharpdotnetfreak.blogspot.com/2012/08/auto-refresh-update-gridview-in-aspnet-ajax-timer.html) and [Gmail style update](http://www.codeproject.com/Articles/103630/How-to-Make-GridView-Auto-Partial-Updat...
Auto update a table with AJAX
[ "", "asp.net", "sql", "ajax", "webforms", "" ]
I know this may be an easy question, but I've been stumped on this for the past hour and am not sure what terms to lookup that accurately describe what I am trying to do. I have a MySQL database with two tables. Countries and Regions. The Regions table has two columns, id and name. An example of a row would be 1, nort...
``` SELECT A.name, A.regionID, b.Name FROM countries A Join regions B on B.id = A.RegionId ORDER BY A.name ASC ```
Try this ``` SELECT A.name, A.regionID FROM countries A, regions B WHERE a.RegionID = b.id AND b.id = 1 ORDER BY A.name ASC ```
How to get name from another table when using a key in SELECT?
[ "", "mysql", "sql", "select", "key", "" ]
I have a table (that contains data) in Oracle 11g and I need to use Oracle SQLPlus to do the following: Target: change the type of column `TEST1` in table `UDA1` from `number` to `varchar2`. Proposed method: 1. backup table 2. set column to null 3. change data type 4. restore values The following didn't work. ``` ...
``` create table temp_uda1 (test1 integer); insert into temp_uda1 values (1); alter table temp_uda1 add (test1_new varchar2(3)); update temp_uda1 set test1_new = to_char(test1); alter table temp_uda1 drop column test1 cascade constraints; alter table temp_uda1 rename column test1_new to test1; ``` If there was ...
Add new column as varchar2, copy data to this column, delete old column, rename new column as actual column name: ``` ALTER TABLE UDA1 ADD (TEST1_temp VARCHAR2(16)); update UDA1 set TEST1_temp = TEST1; ALTER TABLE UDA1 DROP COLUMN TEST1; ALTER TABLE UDA1 RENAME COLUMN TEST1_temp TO TEST1; ```
Oracle SQL to change column type from number to varchar2 while it contains data
[ "", "sql", "oracle", "oracle11g", "" ]
Building report for slow movers in a a database. I want to know items that have not been purchases in 180 days and show the most recent purchase date. The dates ares store in datetime format mm/dd/yyyy HH:MM:SS.000 this is my latest attempt I am trying to self learn sql to help at work so any help and explanation is ap...
Can you try: ``` SELECT Inventory.LocalSKU, InventorySuppliers.SupplierSKU, MAX([Order Details].DetailDate) FROM Inventory INNER JOIN InventorySuppliers ON Inventory.LocalSKU = InventorySuppliers.LocalSKU INNER JOIN [Order Details] ON InventorySuppliers.LocalSKU = [Order Det...
Something like this (not syntax checked): ``` SELECT Inventory.LocalSKU, InventorySuppliers.SupplierSKU, MAX([Order Details].DetailDate) FROM Inventory INNER JOIN InventorySuppliers ON Inventory.LocalSKU = InventorySuppliers.LocalSKU INNER JOIN [Order Details] ON InventorySuppl...
Need to return last purchase date for items that have not been purchased for more than 180 days
[ "", "sql", "sql-server", "date", "datetime", "" ]
I have a table Question and there is two kinds os questions, the T/F questions and the multiple choise questions. Is it possible to make a dynamic table contains the general colums of the Question and the specific colums of the T/F questions and the multiple choise questions? Can anyone help me how to create the model...
Split your questions and their choices into separate tables. Have a third table that defines the mapping between the questions and their options. Having your tables normalized would help avoid repeating option groups like True and False. Here's a rough UML sketch of the table schema: ![Database Tables Diagram](https:...
This solution handles both T/F questions and multiple choice questions: ![enter image description here](https://i.stack.imgur.com/MVvEn.png)
How to have a table with two kinds of variable colums
[ "", "mysql", "sql", "" ]
In Ms.Access 2010, I have a similar query table like one below where its displaying duplicate records. Problem is that even though I have unique ID's, one of the field has different data than other row since I have combined two seperate tables in this query. I just want to display one row per ID and eliminate other row...
Use the SQL from your current query as a subquery and then `GROUP BY` `ID` and `NAME`. You can retrieve the minimum `FAVCOLOR` since you want only one and don't care which. ``` SELECT sub.ID, sub.NAME, Min(sub.FAVCOLOR) FROM ( SELECT ID, [NAME], FAVCOLOR FROM TABLE1 UNION ALL SELECT...
Try selecting union without the ALL parameter and see if you get the desired result. Your new query would look like "SELECT ID, NAME, FAVCOLOR FROM TABLE1; UNION SELECT ID, NAME, FAVCOLOR FROM TABLE2;"
Pick One Row per Unique ID from duplicate records
[ "", "sql", "ms-access", "ms-access-2010", "" ]
I need to find out row ID that the values come from while doing GROUP BY. first create and populate a "play object" ``` -- vertical coalesce with row-source of value :) instead of column-source of value as in horizontal coalesce :) CREATE TABLE #TBL(ID INT, GR INT, A INT, B INT) INSERT INTO #TBL SELECT 1,1,1,NULL UNI...
I am not sure if it will out perform joins/outer applies (I think it will), but this will work: ``` WITH CTE AS ( SELECT GR, A, B, ID, MinA = MIN(A) OVER(PARTITION BY GR), MinB = MIN(B) OVER(PARTITION BY GR) FROM #TBL ) SELECT GR, A = ...
This should do: ``` SELECT DISTINCT T1.GR, T2.A, T3.B, T2.ID A_ID, T3.ID B_ID FROM #TBL T1 OUTER APPLY (SELECT TOP 1 * FROM #TBL WHERE GR = T1.GR AND A IS NOT NULL ORDER BY A, ID) T2 OUTER APPLY (SELECT TOP 1 * F...
which row min value came from (vertical coalesce)
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Hy guys. I have a query: ``` select * from stat.cause_code_descriptions INNER JOIN stat.stat_dial on stat.cause_code_descriptions.CODE = stat.stat_dial.cause where called like '%3623.1348' and begdt > sysdate-500 and rownum <=100 order by begdt desc ``` This query returns something like that ``` ...
You need a window function, ROW\_NUMBER: ``` select * from ( select ccd.*, sd.*, row_number() over (partition by login order by begdtu desc) rn from stat.cause_code_descriptions ccd INNER JOIN stat.stat_dial sd on ccd.CODE = sd.cause where called like '%3623.1348' ) dt where rn = 1 order by beg...
``` SELECT * FROM ( select *,ROW_NUMBER() OVER (PARTITION BY login ORDER BY begdt DESC) RN from stat.cause_code_descriptions INNER JOIN stat.stat_dial on stat.cause_code_descriptions.CODE = stat.stat_dial.cause where called like '%3623.1348' and begdt > sysdate-500 and rownum <=100 ) WHERE RN=1; ```
Find last record in DB for each repeated field(Oracle query)
[ "", "sql", "oracle", "unique", "" ]
I have three tables, a table for users, one for orders and the last one that contains the order items. I've created a SQL query that gets all the orders and joins the user into the results, now I want to join the order items into the query. One order can have multiple order items. Each order item has a price. I need t...
``` SELECT huxwz_user_orders.*, huxwz_users.name, huxwz_users.email, huxwz_users.id, SUM(huxwz_user_orderitems.price) FROM huxwz_user_orders LEFT OUTER JOIN huxwz_users ON ( huxwz_user_orders.userid = huxwz_users.id ) LEFT OUTER JOIN huxwz_user_orderitems ON ( huxwz_user_orders.id = huxwz_user_orderitems.orderi...
Are you using oracle? If so, this might be what you want: ``` SUM(huxwz_user_orderitems.price) OVER (PARTITION BY huxwz_user_orderitems.orderid) ``` If not, I guess you'll have to make a select of all your order items, a select with all totals per order (group by having) and join those 2 result sets. ``` SELECT a.*...
Sum items in a join statement MySQL
[ "", "mysql", "sql", "join", "" ]
I just want to ask how can I achieve getting the records in a database by week in a month? using sql What I really mean is when I input 1 it will get the records in 1st week of a month I've done a lot of research today but it seems I can't find a good solution Heres the code: ``` DECLARE @MONTH int DECLARE @YEAR int ...
`DATEPART(WEEK,)` gives you number of a week in an YEAR so you just need to calculate number of week in the month calculating difference between current date week number and the week number of the first day of the month: ``` WHERE MONTH(RH.DateReleased) = @MONTH AND YEAR(RH.DateReleased) = @YEAR AND DATEPART(WEE...
I consider '2013-08-26' - '2013-09-01' the first week in september ``` DECLARE @MONTH int = 9 DECLARE @YEAR int = 2013 DECLARE @WEEK int = 1 DECLARE @from date= dateadd(day, datediff(day, -(@WEEK - 1)*7, (dateadd(month, (@year-1900) * 12 + @month - 1 , 0)))/7*7 , 0) SELECT RH.RepairOrderNumber FROM dbo.Repa...
How to get database values by week
[ "", "sql", "sql-server-2008", "" ]
How do you return all possibilities, whether there is content or it is NULL? If I want to return everything that isn't NULL: ``` SELECT * FROM table WHERE column LIKE '%' ``` And if I want to return all NULLs: ``` SELECT * FROM table WHERE column IS NULL ``` How do I combine them both? I need to be able to because...
It's fairly straightforward. To only get NULLS: ``` SELECT * FROM table WHERE column IS NULL ``` To only get NOT NULLS: ``` SELECT * FROM table WHERE column IS NOT NULL -- could be this if your example is not representative -- WHERE column IS NULL OR column LIKE '%whatever%' ``` And for everything (no filter), ju...
``` WHERE column LIKE '%' OR column IS NULL ```
WHERE statement that selects everything (content and NULL)
[ "", "sql", "sql-server", "" ]
Good day, i have a table with user activity information in. the table basically is as follow: ``` Eventdate, UserId, Activity 2013-09-09 SusanM Support Call 2013-09-09 BrandonP Meeting 2013-09-09 MumbaM Administration 2013-09-16 SusanM Support Call 2013-09-16 B...
You can try this: ``` SELECT t1.Eventdate, t1.UserId, t1.Activity FROM YourTable t1 WHERE t1.Eventdate = '2013-09-16' UNION SELECT t1.Eventdate, t1.UserId, 'No update yet' as Activity FROM YourTable t1 WHERE t1.userid not in (SELECT UserId FROM YourTable WHERE Eventdate = '2013-09-16') AND t1.Eventdate = ...
I think you can try something like this but instead of 'no update yet', you'll get NULL; ``` SELECT t1.Eventdate, t1.UserId, t2.Activity From Table t1 Left Outer Join Table t2 on t1.UserId = t2.UserId Where Eventdate = '2013/09/16' ```
How to try and display users that do no have entries for latest week in database
[ "", "sql", "sql-server-2012", "" ]
I need some help with MySQL. Lets say i have this query Q1: **Q1:** ``` select cn.idConteudo, TIMESTAMPDIFF(SECOND, nl.dataInicio , nl.dataFim) from navegacaolog nl, conteudoNo cn where nl.idConteudoNo = cn.idConteudoNo AND TIMESTAMPDIFF(SECOND, nl.dataInicio , nl.dataFim) > 120 ``` the results are...
You have not specified a join condition, so what you're getting is the FULL CROSS JOIN which produces a row for every possible combination of rows in the base tables. <http://en.wikipedia.org/wiki/Join_(SQL)> I find that using the ANSI syntax for joins avoids this confusion. Don't just use the commas in the FROM clau...
Results have not changed, just that each result has been repeated number of times equal to rows in new table. And reason is that you have added new table without any join in where clause so you have a cross join.
SQL Query: why does adding another table change the results?
[ "", "mysql", "sql", "" ]
I'm pretty new to SQL... I have a table with the following columns : ``` Employee,Title,Age,Children ``` Output of a basic SELECT would be : ``` Steve |Foreman|40|Billy Steve |Foreman|40|Amy Steve |Foreman|40|Michelle Daniel|Smith |35|Eric Daniel|Smith |35|Jake Erin |Otis |29|Eileen ``` Hopefully, I've shown t...
Either go for ... ``` SELECT * FROM employees WHERE Children NOT LIKE 'E%'; ``` if you want all *records* where the child's name doesn't start with `E` or for ... ``` SELECT * FROM employees e1 WHERE NOT EXISTS (SELECT 1 FROM employees e2 WHERE e1.Employee = e2.Emplo...
You could try: ``` select * from YourTable T where NOT EXISTS (select 1 from YourTable where Employee=T.Employee and Children like 'E%') ``` This, of course, will have a problem if your have two employees with the same name. You could expand the `WHERE` clause to cover all the attributes that make an employee the sam...
In SQL, omit entire record if column (of multiple values) matches condition
[ "", "sql", "advantage-database-server", "" ]
I was wondering is there a way to retrieve, for example, 2nd and 5th row from SQL table that contains 100 rows? I saw some solutions with `WHERE` clause but they all assume that the column on which `WHERE` clause is applied is linear, starting at 1. Is there other way to query a SQL Server table for a specific rows i...
Try this, ``` SELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY ColumnName ASC) AS rownumber FROM TableName ) as temptablename WHERE rownumber IN (2,5) ```
With SQL Server: ``` ; WITH Base AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM YourTable ) SELECT * FROM Base WHERE RN IN (2, 5) ``` The `id` that you'll have to replace with your primary key or your ordering, `YourTable` that is your table. It's a CTE (Common Table Expression) so it isn't a tempor...
How to retrieve specific rows from SQL Server table?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm converting a mysql system to use oracle, but I'm having problems with this query: ``` SELECT * FROM recent_activity WHERE TIME_TO_SEC(TIMEDIFF(NOW(), lastactivity )) < 5 ``` I know that `NOW()` uses `systimestamp` and `lastactivity` is a timestamp. I'm trying to check activities in the last 5 seconds. Do yo...
``` select * from recent_activity where systimestamp-lastactivity < interval '5' second; ```
Ok, now I think I got this working: ``` SELECT * FROM recent_activity WHERE EXTRACT (DAY FROM (systimestamp-lastactivity))*24*60*60+EXTRACT (HOUR FROM (systimestamp-lastactivity))*60*60+EXTRACT (MINUTE FROM (systimestamp-lastactivity))*60+ EXTRACT (SECOND FROM (systimestamp-lastactivity)) < 5 ```
An Oracle Select with time
[ "", "mysql", "sql", "oracle", "" ]
I'm wanting to be able to input any given report server url and display a list of reports available on that server. I found this question, and it's useful if I compile the project with a reference to a specific sql server ([How do I get a list of the reports available on a reporting services instance](https://stackove...
You can go to Web Service URL (note: *not* Report Manager URL). So if your main managing URL is `http://server/Reports` and Web Service URL is `http://server/ReportServer` - open the second one. It will give you raw listing of available items. Note that this will include reports, datasources, folders etc.
You could query the `ReportServer` database of your reporting server. ``` SELECT * FROM dbo.Catalog WHERE Type = 2 ``` Should give you a list of all of the reports.
How do I get a list of the reports available on any given reporting server?
[ "", "sql", "reporting-services", "" ]
I have the method that do update to data base table but when I invoke it I have an exception "Incorrect syntax near '('." Here is the method ``` internal Boolean update(int customerID,int followingID, string fullName, string idNumber, string address, string tel, string mobile1, string mobile2, string email, string c...
`UPDATE` syntax is wrong.. Try ``` string sqlStatment = "UPDATE customers SET followingID= @followingID, fullName=@fullName, idNumber=@idNumber,address=@address,tel=@tel,mobile1=@mobile1,mobile2=@mobile2,email=@email,customerComment=@customerComment,timeStamp=@timeStamp WHERE customerID=@customerID" ```
Your Syntax error is incorrect.Please refer the link for **[Update Query Syntax](http://www.w3schools.com/sql/sql_update.asp)** ``` update customers set followingID= @followingID, fullName=@fullName, idNumber=@idNumber, address=@address, tel=@tel, mobile1=@mobile1, mobile2=@mobile2, email=@email, customerComment=@c...
What is the error in this SQL update stament
[ "", "sql", "sql-server", "c#-4.0", "qsqlquery", "" ]
I have a star schema here and I am querying the fact table and would like to join one very small dimension table. I can't really explain the following: ``` EXPLAIN ANALYZE SELECT COUNT(impression_id), imp.os_id FROM bi.impressions imp GROUP BY imp.os_id; ...
Rewritten with (recommended) explicit ANSI JOIN syntax: ``` SELECT COUNT(impression_id), imp.os_id, os.os_desc FROM bi.impressions imp JOIN bi.os_desc os ON os.os_id = imp.os_id GROUP BY imp.os_id, os.os_desc; ``` First of all, your second query *might* be wrong, if more or less than exactly one match are found...
``` HashAggregate (cost=868719.08..868719.24 rows=16 width=10) HashAggregate (cost=1448560.83..1448564.99 rows=416 width=22) ``` Hmm, width from 10 to 22 is a doubling. Perhaps you should join after grouping instead of before?
Why does the following join increase the query time significantly?
[ "", "sql", "postgresql", "join", "aggregate-functions", "postgresql-performance", "" ]
I'm saving im my table a colum current\_date in this format: 'yyyy-MM-dd HH:mm' How to search in database by date? I want, for examble the records from 2013-09-25 discarting the hour. If I do this "Select current\_date from mydatabase where current\_date = '2013-09-25'" It does not work. I have to make this "Select c...
Apparently your dates are stored as Strings. You can use LIKE to discard the hour : ``` select current_date from mydatabase where current_date like '2013-09-25%' ```
``` SELECT * FROM mydatabase WHERE ( current_date > '2011-08-07') AND (current_date < '2011-08-08') ``` Replace the first date with the day you want information about and then update the second date with the following day.
How to search in sqlite by date?
[ "", "android", "sql", "sqlite", "datetime", "android-date", "" ]
I've been reading around StackOverflow and various forums about this problem but I cannot seem to figure it out. When trying to run the "CREATE TABLE Class" and "CREATE TABLE Enroll" commands below I get "ERROR 1005: Can't create table university.class (errno: 150)". I am using InnoDB as my storage engine. The first tw...
Remove NOT NULL in defination of facId
This is occur due to a foreign keye error. To get more details on foreign key error, run SHOW ENGINE INNODB STATUS\G and look at the "LATEST FOREIGN KEY ERROR" section. I think it will tell that the foreign key is invalid because there is no unique index or primary key index on Faculty.facid.
MYSQL Foreign Key errno: 150 cannot create tables
[ "", "mysql", "sql", "foreign-keys", "foreign-key-relationship", "" ]
I want to know how can i use MAX MIN command with ORMLITE. For example lets say we have this table > Table Name = Example > Column 1 = id > Column 2 = name In ORMLITE how can i get max id ? I looked [here](http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_5.html#Advanced/ "here") but i didnt't understand...
``` QueryBuilder<Account, Integer> qb = accountDao.queryBuilder(); qb.selectRaw("MIN(orderCount)", "MAX(orderCount)"); // the results will contain 2 string values for the min and max results = accountDao.queryRaw(qb.prepareStatementString()); String[] values = results.getFirstResult(); ``` I found this from [docum...
This is how I query for max ID in my code: ``` QueryBuilder<Example, String> builder = dao.queryBuilder(); builder.orderBy("id", false); // true or false for ascending so change to true to get min id Example example = dao.queryForFirst(builder.prepare()); String id = null; if (example == null) id = "-1"; else ...
SQL MAX-MIN in ORMLITE - ANDROID
[ "", "android", "sql", "max", "ormlite", "" ]
Please help me, below is my sql query. When I execute it, the result is nothing. ``` SELECT tblclientinfo.acctnum, tblclientinfo.fname, tblclientinfo.fname, tblreservation.unitnum, tblbillingsched.billnum, tblbillingsched.duedate, tblbillingsched.monthlyamort, tb...
I think you're looking for... ``` SELECT tblclientinfo.acctnum, tblclientinfo.fname, tblclientinfo.fname, tblreservation.unitnum, tblbillingsched.billnum, tblbillingsched.duedate, tblbillingsched.monthlyamort, tblbillingsched.totalbalance FROM tblclientinfo ...
(off topic and probably not the answer but I thought worth noting) The safer form of this: ``` tblbillingsched.duedate BETWEEN '1/1/2014' AND '1/30/2014' ``` is this: ``` tblbillingsched.duedate >= '20140101' AND tblbillingsched.duedate <'20140130' ``` Stating a date like this `'20140130'` is unmistakable.
SQL Server Joining 3 Tables
[ "", "sql", "sql-server", "" ]
I'm looking to write a postgresql query to do the following : ``` if(field1 > 0, field2 / field1 , 0) ``` I've tried this query, but it's not working ``` if (field1 > 0) then return field2 / field1 as field3 else return 0 as field3 ``` thank youu
As stated in PostgreSQL docs [here](http://www.postgresql.org/docs/9.1/static/functions-conditional.html): > The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages. Code snippet specifically answering your question: ``` SELECT field1, field2, CASE ...
``` case when field1>0 then field2/field1 else 0 end as field3 ```
IF-THEN-ELSE statements in postgresql
[ "", "sql", "postgresql", "" ]
I have several programs written in `R` that now I need to translate in T-SQL to deliver them to the client. I am new to T-SQL and I'm facing some difficulties in translating all my `R` functions. An example is the numerical derivative function, which for two input columns (values and time) would return another column ...
I think you may consider changing your mind a bit. SQL language is very good when working with sets of data, especially modern RDBMS implementations (like SQL Server 2012), but you have to think in sets, not in rows or columns. While I stilldon't know your exact tasks, let's see - SQL Server 2012 have very nice set of ...
I don't think this is possible in pure T-SQL without using cursors. But with cursors, stuff will usually be very slow. Cursors are processing the table row-by/row, and some people call this "slow-by-slow". But you can create your own aggregate function (see [Technet](http://technet.microsoft.com/en-us/library/ms182741...
Create a function with whole columns as input and output
[ "", "sql", "sql-server", "r", "clr", "" ]
So I have a folder full of images, and I would like to insert each filepath into a row in one of the tables into my database. Each of them is named from 001.png up to 999.png. I'm not sure how to do it. I've tried to use a LOOP but my SQL knowledge is basic at best. It's a single insert, so I don't mind if it takes a...
Can you use excel? (to generate the query only) I often use excel to generate one off sets of statements like this.. probably get shot for it around here ;) If column A had 0-999 in it the formula in B1 would be something like: ``` ="insert into table (column) values ('/images/"&A1&".png')" ``` Then just drag down ...
Not sure about mySQL but this would work in MSSQL: ``` create table #temp (fname varchar(10)) declare @filename as int set @filename = 0 WHILE @filename < 1000 BEGIN insert into #temp values (right('000' + cast(@filename as varchar(3)),3)+'.png') set @filename = @filename + 1 END select * from #temp ```
Insert multiple filepaths with sql from folder
[ "", "sql", "filepath", "" ]
I am trying to retrieve records from an ORACLE table that have yesterday's date in one of its column. I have a job running everyday retrieving ONLY yesterday's records. NOTE\*\* the column insert\_date is of type `date` These are the two SQL statements I have so far: ``` SELECT distinct column1 FROM table1 WHERE ...
Use the between but subtract a second from the end date. ``` insert_date between trunc(CURRENT_DATE-1) and trunc(CURRENT_DATE) - 1/86400 ```
Try this: ``` SELECT distinct column1 FROM table1 WHERE flag = 'N' AND insert_date = trunc(sysdate-1,'DD') and ipaddress is not null and ipaddress<>'0.0.0.0'; ``` Your first query works fine but you may not need to use `between` when you want to filter the data for a single day.
Search records from previous day
[ "", "sql", "database", "oracle", "date", "" ]
I am trying to add a simple index with the following SQL in Postgres, but the command keeps timing out: ``` CREATE INDEX playlist_tracklinks_playlist_enid ON playlist_tracklinks (playlist_enid); ``` The table definition is as follows: ``` => \d playlist_tracklinks Table "public.playlist_tracklinks" Col...
It was Heroku killing connections (the server ran out of temporary space). Contacting Heroku support was the solution eventually...
Arithmetic with `numerics` is very slow. This includes the comparisons needed to build and use the indexes. I suggest that you change the `enid` types to `char(20)` or just `varchar` if you do not do any arithmetic (other than comparisons) on them, and perhaps `bigint` if you do. Bigint isn't quite enough for the large...
PostgreSQL: How to create index on very large table without timeouts?
[ "", "sql", "postgresql", "postgresql-9.2", "" ]
Let us say that I have a database table with the following two records: ``` CACHE_ID BUSINESS_DATE CREATED_DATE 1183 13-09-06 13-09-19 16:38:59.336000000 1169 13-09-06 13-09-24 17:19:05.762000000 1152 13-09-06 13-09-17 14:18:59.336000000 1173 13-09-05 13-09-19 15:48:59.136...
Not positive on oracle syntax, but use the `ROW_NUMBER()` function: ``` SELECT BUSINESS_DATE, CACHE_ID FROM (SELECT t.*, ROW_NUMBER() OVER(PARTITION BY BUSINESS_DATE ORDER BY CREATED_DATE DESC) RN FROM YourTable t )sub WHERE RN = 1 ``` The `ROW_NUMBER()` function assigns a number to each row. ...
You want to group on business date, and get the CACHE\_ID with the most current created date? Use something like this: ``` select yt.CACHE_ID, yt.BUSINESS_DATE, yt.CREATED_DATE from YourTable yt where yt.CREATED_DATE = (select max(yt1.CREATED_DATE) from YourTable yt1 ...
Select Record with Maximum Creation Date
[ "", "sql", "oracle", "oracle11g", "" ]
I keep getting the following error when I click on the Security tab in ASP.NET WebSite Administration Tool. > A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server...
You need to configure a membership provider in your websites web.config file. Please see the below example and modify the configuration to suit your requirements. ``` <configuration> <connectionStrings> <add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrat...
This is extension of @codkemonkeh answer if you are using SQL Server and not localDB. My Website Administration tool was running fine until I enabled roles, at which points I started getting this error. So without roles, my application worked fine but with roles enabled, I was getting this error. Found out that Roles...
ASP.NET WebSite Administration Tool can't access SQL database
[ "", "asp.net", "sql", "sql-server", "" ]
I have a select statement in which the WHERE clause's IN operator. The query works properly as long as some values are passed to question mark (passed from java program). But when there are no values passed, I get a syntax error. ``` select this_.categoryAddressMapId as category1_1_0_, this_.categoryId as cate...
Modify your java program. Your choices are to not run the query if there are no addressIds, or ensure that it passes at least one value. If addressId is an integer field, pass -1 or something like that. Personally, I like the first option but it depends on your requirements.
how about doing sometiong like ``` where (? is null) OR this_.addressId in ( ? ) ``` you may need to add some special treatment to the first part of the OR if your columns does accept NULLS
Dynamic Values in 'IN' operator
[ "", "mysql", "sql", "where-in", "" ]
I'm a newbie so I apologize if I'm not asking this question in the best way possible. Let's say I have two tables: One called `CatColours` and one called `Cats` `CatColours` ``` id colour spots -- ----- ----- 1 brown Yes 2 black No 3 white No 4 orange Yes ``` `Cats` ``` id cat_name ...
I think you are just looking for a simple join: ``` SELECT CatColours.id, Cats.cat_name, CatColours.colour FROM CatColours INNER JOIN Cats ON CatColours.id = Cats.id ``` And [here's a SQL Fiddle to demonstrate](http://www.sqlfiddle.com/#!6/3a5bf/1). For more information on joins, see also: * <http://en.wikipedia.or...
If you just want to get the data form existing tables you can use any of the queries already posted. Pls note that your tables are not very well organized. How would you represent a cat named Jimmy that is brown and doesn’t have spots? Also, note that your CatColors table contains redundant data because cat can have ...
Show data that are linked to each other in separate tables
[ "", "sql", "sql-server", "" ]
at the moment I am using the statement: ``` delete from tbl_name where trunc(tbl_name.Timestamp) = to_date('06.09.2013','DD/MM/YYYY'); ``` But this takes very very long. Is there a way to speed things up? Thank you
First, this is certainly a big table. Otherwise I see no point in a statement like yours taking very long. Then there are two possibilities: 1) The delete statement affects many, many records. Then it's only natural for the statement to take long. The whole table will have to be scanned (full table scan). You could ...
Use a between value in right side instead of using trunc on left side. ``` delete from tbl_name where tbl_name.Timestamp between to_date('06.09.2013 00:00:00','DD/MM/YYYY hh24:mi:ss') and to_date('06.09.2013 23:59:59','DD/MM/YYYY hh24:mi:ss'); ```
Delete where Date = DD.MM.YYYY on table with 20m records
[ "", "sql", "oracle", "oracle11g", "" ]
I want to take a column with values that repeat multiple times and get that value only once and store it for later use, but at the same time I would like to get another value in the same row as that distinct column. ``` A B C 32263 123456 44 32263 123456 45 32263 123456 46 32264 246802 44 32263 246...
You can use `INSERT INTO... SELECT` statement on this, ``` INSERT INTO tableName (A, B, C) SELECT A, B, MAX(C) + 1 FROM tableName GROUP BY A, B ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!6/c2051/2)
Try this: ``` SELECT * INTO new_table FROM (SELECT DISTINCT * FROM table_name) x ```
SELECT DISTINCT values and INSERT INTO table
[ "", "sql", "select", "sql-server-2012", "distinct", "sql-insert", "" ]
I have an order table that looks like the below ``` order_id ordered checkin collected ====================================== 1 2 1 4 2 4 2 4 3 4 2 4 4 1 4 1 ``` This ...
**UPDATED:** You can calculate row counts per staff id for each column individually and then join with staff table using outer join. ``` SELECT s.id, s.name, COALESCE(o.ordered, 0) ordered, COALESCE(c.checkin, 0) checkin, COALESCE(l.collected, 0) collected FROM staff s LEFT JOIN ( SELE...
You can use `COUNT(*)` to count all orders in your table. Also Use `COUNT(checkin)` `COUNT(collected)` to count the other fields. If you are trying to get the counts for one user, you can user `WHERE` to do it. ``` SELECT COUNT(order_id) AS order_count, COUNT(checking) AS chcekin_count, COUNT(collected) AS co...
Multiple mysql counts from order table
[ "", "mysql", "sql", "" ]
please see my attached below: my actual data will be store in table 1, can I create a view that display data like table 2? ![enter image description here](https://i.stack.imgur.com/GchAn.png)
Yes it is possible and it is called a [UNPIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) For your case: ``` SELECT period, value, category FROM (SELECT VendorID, charcge,nocharge FROM Table) p UNPIVOT (value FOR category IN (charge,nocharge) )AS unpvt; ```
Please see [PIVOT/UNPIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) for what you need
is it possible create a sql view from "horizontal" to "vertical"
[ "", "sql", "sql-server", "" ]
I'm trying to select all the results from a table A and all results from table B I used this Request: ``` $request_public_imgs = $BDD-> query("SELECT * FROM images_public "); UNION("SELECT * FROM images_users WHERE img_kind='PublicImg' ") ; ``` But I receive this error > Fatal error: Call to undefined fu...
Write your SQL command as a single piece : ``` $request_public_imgs = $BDD-> query("SELECT id, field1, .. FROM images_public UNION SELECT id, field1, .. FROM images_users WHERE img_kind='PublicImg' ") ; ``` You should select precise field and not using \* for performance matter. Adrien
`UNION` is a `MySQL` function, hence you need to put it inside the `query()`: ``` $request_public_imgs = $BDD-> query(" SELECT * FROM images_public UNION SELECT * FROM images_users WHERE img_kind='PublicImg' "); ``` More generally, all the queries will work like: ``` $request_public_imgs = $BDD-> query("YOUR_MY...
Select all from TWO tables
[ "", "mysql", "sql", "join", "" ]
I have a question. How can I write this SQL **First Table** 1. Name: ORDER\_TABLE 2. Column: Order\_number, Contract\_number,vendor\_number **Second Table** 1. Name: CONTRACT\_TABLE 2. Column: Contract\_number, vendor\_number I have a one contract\_number ='1234' which contain in CONTRACT\_TABLE but I want check d...
Assuming you want to detect all the Contract\_number in CONTRACT\_TABLE which does not exits in ORDER\_TABLE (not clear from your description) here is one exemple ofsql: ``` select Contract_number from CONTRACT_TABLE minus select distinct Contract_number from ORDER_TABLE ```
``` SELECT Contract_Number FROM Contract_Table WHERE NOT EXISTS (SELECT NULL FROM Order_Table WHERE Contract_Table.Order_Number = Order_Table.Order_Number) ```
Order Number which dosnt exists in other table
[ "", "sql", "oracle", "" ]
Suppose I have a table `t` filled like this: ``` x y z - - - A 1 A A 4 A A 6 B A 7 A B 1 A B 2 A ``` Basically, columns x and z are random letters and y random numbers. I want to aggregate the rows as follows: ``` x z min(y) max(y) - - ------ ------ A A 1 4 A B 6 6 A A 7 7 B A 1 2 ``` In...
Here a solution, but I don't have the time to explain it step by step: ``` select x, z, min(y), max(y) from ( select b.* , sum(switch) over (order by rn) as grp_new from( select a.* , case when grp = (lag(grp) over (order by rn)) then 0 else 1 end as switch from ...
You didn't mention Oracle version if your version supports [WITH](http://www.oracle-base.com/articles/misc/with-clause.php) and [ROW\_NUMBER() OVER](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm) ``` WITH C as ( select t.*, ROW_NUMBER() OVER (order by x,y,z ) as rn from t ), C2 as ( s...
How do I aggregate over ordered subsets of rows in SQL?
[ "", "sql", "oracle", "" ]
I need to insert a string value that looks like money from one table to another table where the column type is decimal(18,2). I have tried code that looks like: `CAST(REPLACE(REPLACE(d.Cost,',',''),'$','') AS DECIMAL(18,2)) AS 'Cost'` but get the error converting data type varchar to numeric.
It's not a good idea to store formatted values in your database, but this problem is easy to workaround. The reason you can't cast it into *Decimal* is because currently it's a *Varchar*. So first cast it in *Money* and then you can cast it into something else. This works in Sql Server: ``` select cast(cast('$400,00...
Try: ``` CAST(CAST(REPLACE(REPLACE(d.Cost,',',''),'$','') AS Float) AS DECIMAL(18,2)) AS 'Cost' ```
How do I Cast a string value formatted like "$400,000.88" to a decimal
[ "", "sql", "sql-server", "" ]
Consider the following table (snapshot): ![enter image description here](https://i.stack.imgur.com/2dav3.jpg) I would like to write a query to select rows from the table for which * At least 4 out of 7 column values (VAL, EQ, EFF, ..., SY) are not NULL.. Any idea how to do that?
Nothing fancy here, just count the number of non-null per row: ``` SELECT * FROM Table1 WHERE IIF(VAL IS NULL, 0, 1) + IIF(EQ IS NULL, 0, 1) + IIF(EFF IS NULL, 0, 1) + IIF(SIZE IS NULL, 0, 1) + IIF(FSCR IS NULL, 0, 1) + IIF(MSCR IS NULL, 0, 1) + IIF(SY IS NULL, 0, 1) >= 4 ``` Just noticed you tagged...
How about this? Turning your columns into "rows" and use SQL to count not nulls: ``` select * from Table1 as t where ( select count(*) from (values (t.VAL), (t.EQ), (t.EFF), (t.SIZE), (t.FSCR), (t.MSCR), (t.SY) ) as a(val) where a.val is not null ) >= 4 ``` I like this solution beca...
Conditional select statement
[ "", "sql", "sql-server", "sql-server-2005", "select", "" ]
I'm using polymorphic association to argument my `Post` model (which has common post attributes-title, body, date, etc... ) Here's my models, ``` class Post < ActiveRecord::Base belongs_to :post_module, polymorphic: true end class Album < ActiveRecord::Base has_one :post, as: :post_module belongs_to :artist en...
I ended up with `Post.joins('LEFT OUTER JOIN albums ON albums.id = posts.post_module_id').where('posts.post_module_type = "Album" AND albums.artist_id = "?"', @artist.id)`
If I understood correctly, you want to retrieve all the posts for a given artist id. So: ``` @posts = Post.joins(:post_module => :album).where(:post_module => { :album => { :artist_id => artist_id }}) ```
how to query with polymorphic has_one association's attribute?
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
I would like to export a table from SQL Server 2008 R2 to a file. The problem is that I don't have bcp (nor can I install it or anything else) and am not able to run xpcmdshell. Anyone have any ideas on how this could be done without those permissions/tools? (I would like to have this happen on some automated basis pre...
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV. You can also use a command like this too: ``` INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\Test.xls;','SELECT pr...
I'm usually using Copy/Paste from SSMS `Results Pane` to `Excel` ![enter image description here](https://i.stack.imgur.com/ovpQA.png) --- **OR** you can right click on database in the `Object Explorer` and select `Database->Tasks->Export Data`. An `SQL Server Import and Export Wizard` dialog opens and you will be a...
Exporting a table from SQL Server 2008 R2 to a file WITHOUT external tools
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I have these queries : ``` SELECT COUNT(*) FROM t_table WHERE color = 'YELLOW'; SELECT COUNT(*) FROM t_table WHERE color = 'BLUE'; SELECT COUNT(*) FROM t_table WHERE color = 'RED'; ``` Is there any way to get these results in one query?
``` SELECT color, COUNT(*) FROM t_table GROUP BY color ```
If you want the result to be in one row you can use: ``` SELECT SUM(IF(color = 'YELLOW', 1, 0)) AS YELLOW, SUM(IF(color = 'BLUE', 1, 0)) AS BLUE, SUM(IF(color = 'RED', 1, 0)) AS RED FROM t_table ``` [Working example](http://sqlfiddle.com/#!2/9ef77/3)
Multiple COUNT() for multiple conditions in one query (MySQL)
[ "", "mysql", "sql", "count", "" ]
I have two table with some identical field. (please don't blame the design). Below only for the example schema > Table A > id > name > phone > keys > > Table B > id > name > keys > address So, i want to query id, name from either table A or B which meet condition 'keys' on single query, with return ...
Use `UNION` instead of `CROSS JOIN`: ``` SELECT a.id, a.name FROM TABELA as a WHERE a.keys = '1' UNION SELECT b.id, b.name FROM TABLEB as b WHERE b.keys = '1' ```
use union or union all. Union returns only distinct rows, union all returns all rows see examples in manual [manual on unions](http://dev.mysql.com/doc/refman/5.0/en/union.html) ``` SELECT a.id, a.name FROM TABELA as a WHERE a.keys = '1' union SELECT b.id, b.name FROM TABELb as b WHERE b.keys = '1' ```
SQL Query, query to having single field name from different table
[ "", "mysql", "sql", "sql-server", "select", "join", "" ]
I'm having a hard time figuring out a greater than in a SQL statement. Here's my code: ``` select one, two, three from orders where case when @orderid > 0 then orders.orderid = @orderid end ``` --- @orderid is parameter passed to the stored procedure. The idea is that if a valid (> 0) orderid is passed, then use th...
Guffa has the right answer, but the way you'd do this using the CASE trick (which does occasionally come in handy) is this: ``` --If order ID is greater than 0, use it for selection --otherwise return all of the orders. select one, two, three from orders where orders.orderid = CASE WHEN @orderid > 0 then @orderid ...
NYCDotnet answer, like the rest of the answers here works, but they may not be [SARGable](http://en.wikipedia.org/wiki/Sargable) To make this non-SARGable query.. ``` select one, two three from orders where case when @orderid > 0 then orders.orderid else 0 end = @orderid ``` ..SARGable, do th...
Greater than in SQL CASE statement
[ "", "sql", "sql-server", "" ]
I'm having difficulty with what I figure should be an easy problem. I want to select all the columns in a table for which one particular column has duplicate values. I've been trying to use aggregate functions, but that's constraining me as I want to just match on one column and display all values. Using aggregates se...
If I understood you correctly, this should do: ``` SELECT * FROM YourTable A WHERE EXISTS(SELECT 1 FROM YourTable WHERE Col1 = A.Col1 GROUP BY Col1 HAVING COUNT(*) > 1) ```
You can join on a derived table where you aggregate and determine "col" values which are duplicated: ``` SELECT a.* FROM Table1 a INNER JOIN ( SELECT col FROM Table1 GROUP BY col HAVING COUNT(1) > 1 ) b ON a.col = b.col ```
How to select all columns for rows where I check if just 1 or 2 columns contain duplicate values
[ "", "sql", "sql-server", "" ]
I am trying to return the names with the max number of entries in a table and return a list of (name, count) tuples for those with the max for count. My current solution uses: ``` select name, count(*) from action_log group by name order by count desc limit 1; ``` The problem is that using `limit 1` does not account ...
[SQL Fiddle](http://sqlfiddle.com/#!12/09cca/1) ``` with s as ( select name, count(*) as total from action_log group by name ), m as ( select max(total) as max_total from s ) select name, total from s where total = (select max_total from m) ```
You could do this with sub queries - except there are some rules surrounding the group by. How about simplifying it with a view: ``` create view cname as select name, count(name) c from action_log group by name ``` and then `SELECT` like this: ``` select distinct a.name from action_log a join cname c o...
How to get all max count with a field
[ "", "sql", "postgresql", "" ]
Why does this SQL-statement return `0`? ``` SELECT CASE WHEN NULL IN (9,1,NULL) THEN 1 ELSE 0 END ```
I don't know what RDBMS you are using since some of them has configuration on how `NULL` will be treated. ``` NULL IN (9, 1, NULL) ``` can be written as ``` (NULL = 9) OR (NULL = 1) OR (NULL = NULL) ``` and not of them were `TRUE` nor `FALSE`. They are all `NULL`. Since there are only two paths in the `CASE` statem...
SQL is based on [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic), where there are three truth values: `TRUE`, `FALSE`, and `UNKNOWN`. The special `NULL` value is a placeholder for "missing data" and if you compare something, anything, with missing data the result is unknown. For example, is `<miss...
NULL IN (1,2,NULL) returns false
[ "", "sql", "" ]
I have a table `StudentMarks` with columns `Name, Maths, Science, English`. Data is like ``` Name, Maths, Science, English Tilak, 90, 40, 60 Raj, 30, 20, 10 ``` I want to get it arranged like the following: ``` Name, Subject, Marks Tilak, Maths, 90 Tilak, Science, 40 Tilak, English, 60 ...
Your query is very close. You should be able to use the following which includes the `subject` in the final select list: ``` select u.name, u.subject, u.marks from student s unpivot ( marks for subject in (Maths, Science, English) ) u; ``` See [SQL Fiddle with demo](http://sqlfiddle.com/#!18/3771e/1)
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps: 1. create multiple copies for each row using cross join (also creating subject column in this case) 2. create column "marks" and fill in relevant values using case expression ( ex: if...
Unpivot with column name
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "unpivot", "" ]
Say I have a table called `votes`, and a column in that table called `vote_type` which can either be 0 or 1. How can I fetch the `COUNT` of `vote_type` where `vote_type` is `1`? Right now, I can select the count of `vote_type` overall, but not the count of `vote_type` where it is 1 or 0, via this query: ``` SELECT CO...
``` SELECT COUNT(*) TotalVotes, SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) TotalVoteOne, SUM(CASE WHEN vote_type = 0 THEN 1 ELSE 0 END) TotalVoteZero, SUM(CASE WHEN vote_type = 1 THEN 1 ELSE 0 END) - SUM(CASE WHEN vote_type = 0 THEN 1 ELSE 0 END) TotalVoteValue FROM votes -- WHE...
I don't know what exactly are you trying to do, but if you want to count all the votes with Vote\_Type=1 try ``` SELECT COUNT(votes.vote_id) AS vote_count FROM votes WHERE votes.vote_type=1 ``` or if you need to sum the votes ``` SELECT SUM(votes.vote_type) AS vote_sum FROM votes WHERE votes.vote_type=1 ```
How to count by the value of a column in SQL?
[ "", "mysql", "sql", "" ]
I am attempting to get the user information of the user who left this review. With the following code: ``` SELECT username, image, user_id FROM table_users AS us JOIN table_reviews AS re ON re.user_id = us.user_id WHERE us.user_id = 1 AND re.review_id= 1 ``` I get the error: > Column 'user\_id' in field list is amb...
It means that both tables in the query have the column `user_id`. You need to specify which one you want to get in the SELECT statement like `SELECT username, image, re.user_id`
column user\_id is in both `table_reviews`, `table_users` tables. You need to specify columns with table alias name also. ``` SELECT username, image, us.user_id FROM table_users AS us JOIN table_reviews AS re ON re.user_id = us.user_id WHERE us.user_id = 1 AND re.review_id= 1 ```
Column 'user_id' in field list is ambiguous
[ "", "mysql", "sql", "" ]
How can I compare the result of a COUNT inside a trigger in SQLite? So far, this is the code I've come up with: ``` CREATE TRIGGER mytrigger BEFORE INSERT ON mytable BEGIN SELECT CASE WHEN SELECT COUNT (*) FROM mytable >= 3 THEN RAISE(FAIL, "Activated - mytrigger.") END; END; ``` It fail...
You need to add parenthesis around the whole SELECT statement `SELECT COUNT (*) FROM mytable` ``` CREATE TRIGGER mytrigger BEFORE INSERT ON mytable BEGIN SELECT CASE WHEN (SELECT COUNT (*) FROM mytable) >= 3 THEN RAISE(FAIL, "Activated - mytrigger.") END; END; ```
Try this code to delete last 50 row from table2 when count is greater than 100 ``` CREATE **TRIGGER IF NOT EXISTS** delete_trigger BEFORE INSERT ON table1 WHEN (SELECT COUNT(*) FROM table1) > 100 BEGIN delete From table1 where id not in (select id from table1 order by id desc limit 50; END; ```
Test for COUNT()>X inside SQLite trigger
[ "", "sql", "sqlite", "triggers", "" ]
I have a table named `Course` in a Postgres database: [![sample data for table Course](https://i.stack.imgur.com/XbcgA.png)](https://i.stack.imgur.com/XbcgA.png) How can I select rows which have course name with latest date? I mean if I have two same course names for one ID, I should only show the latest one as the b...
In PostgreSQL, to get *unique rows for a defined set of columns*, the preferable technique is generally [`DISTINCT ON`](https://www.postgresql.org/docs/current/sql-select.html#SQL-DISTINCT): ``` SELECT DISTINCT ON ("ID") * FROM "Course" ORDER BY "ID", "Course Date" DESC NULLS LAST, "Course Name"; ``` Assuming you ...
``` SELECT "ID", "Course Name", MAX("Course Date") FROM "Course" GROUP BY "ID", "Course Name" ```
Select rows based on last date
[ "", "sql", "database", "postgresql", "greatest-n-per-group", "" ]
I have SQL table that has a large number of columns. For some reason, some columns have empty cells instead of NULL cells. I would like to make all empty cells in all the columns to be NULL. I know that the way to go for a single column is: ``` UPDATE your_table SET column = NULL WHERE column = '' ``` However, I am...
Run the following query: ``` SELECT 'UPDATE yourtable SET ' + name + ' = NULL WHERE ' + name + ' = '''';' FROM syscolumns WHERE id = object_id('yourtable') AND isnullable = 1; ``` The output of this query will be a chunk of SQL script like this: ``` UPDATE yourtable SET column1 = NULL WHERE column1 = ''; UPDATE yo...
You could do a query on `syscolumns` to get a list of columns, and use the results to construct your query. ``` select quotename(name) + ' = nullif (' + quotename(name)+ ','''')' from syscolumns where id = object_id('yourtable') ``` Additionally, if you write your query as ``` update yourtable set yourcolumn=nu...
Replace empty cells with NULL values in large number of columns
[ "", "sql", "sql-server", "sql-server-2005", "null", "" ]
I have the following query: ``` select 'junior' as type, value from mytable union select 'intermediate' as type, value from mytable union select 'senior' as type, value from mytable ``` Which returns the following data: ``` type value Intermediate 10 Junior 5 Senior 1 ``` I j...
You need to add a third column, called e.g. sortorder. Then, assign the proper integer value to it, ``` select 'junior' as type, value, 1 as sortorder from mytable union select 'intermediate' as type, value, 2 as sortorder from mytable union select 'senior' as type, value, 3 as sortorder from mytable order by 3 ```
You can either sort by adding a sort key column or add a simple case statement based on the values. ``` -- Sort with Case statement with sourceData as ( select 'junior' type, 5 value union all select 'intermediate' type, 10 value union all select 'senior' type, 1 value ) select * from sourceData order by ...
sql order by hardcoded values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Been searching for a few weeks for a solution to this but have come up blank. I have table of data similar to this: ``` client_ref supplier_key client_amount 1111 GBP 10 1111 GBP -10 1111 EUR 50 2222 CHF -22.5 2222 CHF -20 3333 ...
One possible approach is to use the SUM() windowing function: ``` SELECT * FROM ( SELECT tbis.client_ref ,tbis.supplier_key,tbis.client_amount, SUM(tbis.client_amount) OVER ( PARTITION BY tbis.client_ref, tbis.supplier_key) AS total_client_amount FROM [XXXX].[dbo].[transaction] tbis WHERE tbis.client_amoun...
Try this instead: ``` SELECT t1.* FROM transactions AS t1 INNER JOIN ( SELECT tbis.client_ref , tbis.supplier_key, sum(tbis.client_amount) AS total FROM transactions tbis WHERE tbis.client_amount !=0 GROUP BY tbis.client_ref, tbis.supplier_key HAVING sum(tbis.client_amount) =0 ) AS t2 ON t1....
How to display rows that when added together equal zero
[ "", "sql", "" ]
I've seen several questions/answers on how to recursively query a self-referencing table, but I am struggling to apply the answers I've found to aggregate up to each parent, grandparent, etc. regardless of where the item sits in the hierarchy. ``` MyTable ----------- Id Amount ParentId ``` Data: ``` Id Amount ...
``` with cte as ( select t.Id, t.Amount, t.Id as [Parent Id] from Table1 as t union all select c.Id, t.Amount, t.Id as [Parent Id] from cte as c inner join Table1 as t on t.[Parent Id] = c.[Parent Id] ) select Id, sum(Amount) as Amount from cte group by Id ``` **`sql fiddle demo`**
Something like that? ``` WITH temp (ID, ParentID, TotalAmount) AS ( SELECT ID, ParentID, Amount FROM MyTable WHERE NOT EXISTS (SELECT * FROM MyTable cc WHERE cc.ParentID = MyTable.ID) UNION ALL SELECT MyTable.ID, MyTable.ParentID, TotalAmount + MyTable.Amount FROM MyTable INNER JOIN t...
Aggregate Self-Referencing Table
[ "", "sql", "sql-server", "sql-server-2008", "recursion", "" ]
I have a table (simplified below) ``` |company|name |age| | 1 | a | 3 | | 1 | a | 3 | | 1 | a | 2 | | 2 | b | 8 | | 3 | c | 1 | | 3 | c | 1 | ``` For various reason the age column should be the same for each company. I have another process that is updating this table and somet...
You should not be including `age` in the group by clause. ``` SELECT company FROM tableName GROUP BY company, name HAVING COUNT(DISTINCT age) <> 1 ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/4cefc/1)
Since you mentioned "how to get **the rows** where the age is different" and not just the comapnies: Add a unique row id (a primary key) if there isn't already one. Let's call it `id`. Then, do ``` select id from table where company in (select company from table group by company having count(distinct...
SQL group by with a count
[ "", "sql", "group-by", "" ]
I am having trouble writing a script which can delete all the rows which match on the first three columns and where the Quantities sum to zero? I think the query needs to find all Products that match and then within that group, all the Names which match and then within that subset, all the currencies which match and th...
One way to simplify the SQL is to just concatente the 3 columns into one and apply some grouping: ``` delete from product where product + name + currency in ( select product + name + currency from product group by product + name + currency having sum(quantity) = 0) ```
Try this: ``` DELETE FROM [Product] WHERE Id IN ( SELECT Id FROM ( SELECT Id, SUM(Quantity) OVER(PARTITION BY a.Product, a.Name, a.Currency) AS Sm FROM [Product] a ) a WHERE Sm = 0 ) ```
Sql Delete Statement Trouble
[ "", "sql", "sql-server", "" ]
I want to know how to use loops to fill in missing dates with value zero based on the start/end dates by groups in sql so that i have consecutive time series in each group. I have two questions. 1. how to loop for each group? 2. How to use start/end dates for each group to dynamically fill in missing dates? My input ...
You can do it like this without loops ``` SELECT p.date, COALESCE(a.value, 0) value, p.grp_no FROM ( SELECT grp_no, date FROM ( SELECT grp_no, MIN(date) min_date, MAX(date) max_date FROM tableA GROUP BY grp_no ) q CROSS JOIN tableb b WHERE b.date BETWEEN q.min_date AND q.max_date ) p LEF...
The following query does a `union` with `tableA` and `tableB`. It then uses group by to merge the rows from `tableA` and `tableB` so that all of the dates from `tableB` are in the result. If a date is not in `tableA`, then the row has 0 for `value` and `grp_no`. Otherwise, the row has the actual values for `value` and ...
How to fill missing dates by groups in a table in sql
[ "", "sql", "date", "loops", "" ]