Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I could not get the exact query to get the over all total of the total table. i want to get the total of each date in call\_time table. here's my query: ``` SELECT call_type, channel, call_time, count (CASE WHEN upper(status) = upper('no answer') THEN 1 ELSE NULL END) AS cnt_no_answer, count (CASE WHEN u...
Try this: ``` SELECT CALL_TYPE, CHANNEL, TRUNC(CALL_TIME) ,COUNT (CASE WHEN UPPER(STATUS) = UPPER('no answer') THEN 1 END) AS CNT_NO_ANSWER ,COUNT (CASE WHEN UPPER(STATUS) = UPPER('answered') THEN 1 END) AS CNT_ANSWER ,COUNT (STATUS) AS CNT_TOTAL FROM APP_ACCOUNT.CC_CALL WHERE CHANNEL = 'DAHDI/i1/' A...
Use something like the following: ``` SELECT CALL_TYPE, CHANNEL, TRUNC(CALL_TIME) , COUNT (CASE UPPER(STATUS) WHEN UPPER('no answer') THEN 1 ELSE NULL END) AS CNT_NO_ANSWER , COUNT (CASE UPPER(STATUS) WHEN UPPER('ans...
How can I get the total?
[ "", "sql", "oracle", "count", "sum", "oracle-sqldeveloper", "" ]
In Oracle database I have one table with primary key GAME\_ID. I have to insert a copy of a row where game\_name = 'Texas holdem' but it tells me: > An UPDATE or INSERT statement attempted to insert a duplicate key. This is query I am using: ``` INSERT INTO GAME (SELECT * FROM GAME WHERE NAME = 'Texas Holdem'); ```
Assuming your `game_id` is generated by a sequence, you can get a new as part of the select statement: ``` INSERT INTO GAME (game_id, name, col_3) SELECT seq_game_id.nextval, name, col_3 FROM GAME WHERE NAME = 'Texas Holdem'; ```
Let me just offer a slightly more abstract point of perspective... * In a relational database, table is a physical representation of the mathematical concept of relation. * Relation is a **set** (of tuples, i.e. table rows/records). * A set either contains given element or it doesn't, it cannot contain the same elemen...
Oracle Database. Insert a copy of a row to the same table (Duplicate key error message)
[ "", "sql", "oracle", "" ]
I am trying to perform the following query: ``` SELECT * FROM table_name_here WHERE Date LIKE %Jan % 2014% ``` Now, the table name is different and hidden here, but it just won't go through. It says there is an error in my syntax around `%Jan % 2014%` I can get this to work, so I know the connection works: `SELECT *...
You have two syntax errors, firstly the word `Date` is a keyword, so needs to be wrapped and you need quotes around your string, like so: ``` SELECT * FROM table_name_here WHERE `Date` LIKE "%Jan % 2014%" ```
Assuming that `date` is begin stored as a date/datetime column, don't use `like` on it. The `like` implicitly converts it to a string, using some local format. Instead, be explicit: ``` where month(`date`) = 1 and year(`date`) = 2014 ``` or ``` where date_format(`date`, '%Y-%m') = '2014-01' ``` As for your origina...
What is the proper syntax for LIKE?
[ "", "mysql", "sql", "" ]
I'm trying to execute a query to return orders where they only have 1 cross reference number. Something like this (field names and tables changed to protect the innocent ;-P) : ``` SELECT ordernum FROM orders WHERE (COUNT(orderref) = 1) ORDER BY ordernum; ``` The problem is, having an aggregate function is not possi...
The count(\*) has to be in the HAVING clause since it is calculated. Also, you are missing a GROUP BY clause. ``` -- Updated statement SELECT ordernum, COUNT(orderref) as Total FROM orders GROUP BY ordernum HAVING COUNT(orderref) = 1 ORDER BY ordernum ``` Someone emailed me stating that MS Access does not support ...
I'm not sure if it is working in Access but try something like this ``` SELECT ordernum FROM orders group by orderref having count(*) = 1 ORDER BY ordernum; ```
SQL Access COUNT in WHERE clause
[ "", "sql", "ms-access", "" ]
I have an SQL query that returns a column like this: ``` foo ----------- 1200 1200 1201 1200 1200 1202 1202 1202 ``` It has already been ordered in a specific way, and I would like to perform another query on this result set to ID the repeated data like this: ``` foo ID ---- ---- 1200 1 1200 1 1201 2 1200...
This is my solution using a cursor and a temporary table to hold the results. ``` DECLARE @foo INT DECLARE @previousfoo INT = -1 DECLARE @id INT = 0 DECLARE @getid CURSOR DECLARE @resultstable TABLE ( primaryId INT IDENTITY(1, 1) NOT NULL PRIMARY KEY, foo INT, id int null ) SET @getid = CURSOR FOR ...
Not sure this will be the fastest results... ``` select main.num, main.id from (select x.num,row_number() over (order by (select 0)) as id from (select distinct num from num) x) main join (select num, row_number() over(order by (select 0)) as ordering from num) x2 on x2.num=main.num order by x2.ordering ``` Assu...
Identifying repeated fields in SQL query
[ "", "sql", "sql-server-2012", "" ]
This sql code throws an > aggregate functions are not allowed in WHERE ``` SELECT o.ID , count(p.CAT) FROM Orders o INNER JOIN Products p ON o.P_ID = p.P_ID WHERE count(p.CAT) > 3 GROUP BY o.ID; ``` How can I avoid this error?
Replace `WHERE` clause with `HAVING`, like this: ``` SELECT o.ID , count(p.CAT) FROM Orders o INNER JOIN Products p ON o.P_ID = p.P_ID GROUP BY o.ID HAVING count(p.CAT) > 3; ``` `HAVING` is similar to `WHERE`, that is both are used to filter the resulting records but `HAVING` is used to filter on aggregated data (w...
Use `HAVING` clause instead of `WHERE` Try this: ``` SELECT o.ID, COUNT(p.CAT) cnt FROM Orders o INNER JOIN Products p ON o.P_ID = p.P_ID GROUP BY o.ID HAVING cnt > 3 ```
How to avoid error "aggregate functions are not allowed in WHERE"
[ "", "mysql", "sql", "aggregate-functions", "" ]
Given the data below from the two tables cases and acct\_transaction, how can I include just the acct\_transaction.create\_date of the largest acct\_transaction amount whilst also calculating the sum of all amounts and the value of the largest amount? Platform is t-sql. ``` id amount create_date ---|----------|...
Thanks, that got me on the right track to this which is working: ``` ,CAST((SELECT TOP 1 t2.create_date from acct_transaction t2 WHERE t2.case_sk = act.case_sk AND (t2.trans_type = 'F') order by t2.amount, t2.create_date DESC) AS date) AS 'max_date' ``` It won't let me upvote because I have l...
``` ;WITH x AS ( SELECT c.id, t.amount, t.create_date, s = SUM(t.amount) OVER(), m = MAX(t.amount) OVER(), rn = ROW_NUMBER() OVER(ORDER BY t.amount DESC) FROM dbo.cases AS c INNER JOIN dbo.acct_transaction AS t ON c.id = t.id ) SELECT x.id, x.amount, x.create_date, [sum] = y.s, max_amoun...
Choose column based on max() of another column
[ "", "sql", "sql-server", "sql-server-2008-r2", "max", "" ]
I have two tables - `artist and album` columns in `artist - id, name, artist_genre` columns in `album - id, name, artist_name, album_genre, release_date` I would like to find all artists in the album table that is not in the genre listed in artist table (to be more specific - if artist X has genre ‘pop’ and ‘rock’ r...
``` select artist_name, name, album_genre from album left join artist on artist.name = album.artist_name and album_genre = artist_genre where artist.id is null ```
Try this : ``` select artist_name, name, album_genre from album alb where album_genre not in (select distinct artist_genre from artist where name = alb.artist_name) ``` **[SQL Fiddle Demo](http://sqlfiddle.com/#!2/4edd3/1)**
Sql - data reference does not exist when comparing two tables
[ "", "mysql", "sql", "" ]
I'm creating a new trigger and want to have both null value and NULL string in :new.SCO\_NUMBER validation. I'm getting error when i'm using both (as shown below) but when i use ':new.SCO\_NUMBER IS NULL', it works fine. How to use or in this validation. ``` CREATE OR REPLACE TRIGGER TRIG_SCONUMBER_INSERT AFTER INSE...
In case of T-SQL, replace `new.SCO_NUMBER IS (NULL OR 'NULL')` with `new.SCO_NUMBER IS NULL OR new.SCO_NUMBER = 'NULL'`. This should work for you.
Try this ``` IF inserting AND ( :new.SCO_NUMBER IS NULL OR :new.SCO_NUMBER = 'NULL') THEN ```
Inserting null and string 'Null in trigger condition
[ "", "mysql", "sql", "oracle-sqldeveloper", "" ]
Here's my data: ``` with first_three as ( select 'AAAA' as code from dual union all select 'BBBA' as code from dual union all select 'BBBB' as code from dual union all select 'BBBC' as code from dual union all select 'CCCC' as code from dual union all select 'CCCD' as code from dual ...
``` WITH code_frequency AS ( SELECT code, COUNT(1) OVER ( PARTITION BY SUBSTR( code, 1, 3 ) ) AS frequency FROM table_name ) SELECT code FROM code_frequency WHERE frequency > 1 ```
``` WITH first_three AS ( ... ) SELECT * FROM first_three f1 WHERE EXISTS ( SELECT 1 FROM first_three f2 WHERE f1.code != f2.code AND substr(f1.code, 1, 3) = substr(f2.code, 1, 3) ) ```
How to get query to return rows where first three characters of one row match another row?
[ "", "sql", "oracle", "oracle11g", "" ]
I want to find all foreign keys in my database that reference to a primary key of a certain table. For example, I have a column `A` in table `T` which is the primary key. Now I want to find in which tables column `A` is referenced in a foreign key constraint? One simple way I've considered is to check the database di...
Look at [How to find foreign key dependencies in SQL Server?](https://stackoverflow.com/questions/925738/how-to-find-foreign-key-dependencies-in-sql-server) You can sort on PK\_Table and PK\_Column to get what you want
On the last line, change [Primary Key Table] to your table name, change [Primary Key Column] to your column name, and execute this script on your database to get the foreign keys for the primary key. ``` SELECT FK.TABLE_NAME as Key_Table,CU.COLUMN_NAME as Foreignkey_Column, PK.TABLE_NAME as Primarykey_Table, ...
Find all foreign keys constraints in database referencing a certain primary key
[ "", "sql", "sql-server", "foreign-keys", "primary-key", "foreign-key-relationship", "" ]
I just want to drop all table that start with "T%". The db is Netezza. Does anyone know the sql to do this? Regards,
With the catalog views and `execute immediate` it is fairly simple to write this in nzplsql. Be careful though, `call drop_like('%')` will destroy a database pretty fast. ``` create or replace procedure drop_like(varchar(128)) returns boolean language nzplsql as begin_proc declare obj record; expr alia...
You can create a script and then execute it. something like this... ``` DECLARE @SQL nvarchar(max) SELECT @SQL = STUFF((SELECT CHAR(10)+ 'DROP TABLE ' + quotename(TABLE_SCHEMA) + '.' + quotename(TABLE_NAME) + CHAR(10) + 'GO ' FROM INFORMATION_SCHEMA.TABLES WHERE Table_Name LIKE 'T%' ...
Drop multiple tables in Netezza
[ "", "sql", "netezza", "" ]
``` Mentor table +--------------+ | id | name | +-----+--------+ | 1 | name1 | | 2 | name2 | | 3 | name3 | +-----+--------+ MentorLanguage table +------------------+ | id | language | +-----+------------+ | 1 | english | | 1 | french | | 1 | german | | 2 | chinese | | 2 | eng...
You could try using the "IN" operator instead of = in your where clause. This allows you to to do a "contains" instead of comparing with a single value. ``` select * from Mentor m where m.id IN ( select ml.id from MentorLanguage ml, StudentLanguage sl where ml.language like sl.language group by ml.id ) ```
There are a ton of ways to do this. I guess it just depends on your preference and/or need in the result set. I've included two ways I would meet this request. Pretty simple. Let me know if you need additional returned results. ``` CREATE TABLE #Mentor ([id] INT Identity, [name] NVARCHAR(20)) GO INSERT INTO #Mentor(n...
select rows based on WHERE clause which return multiple rows
[ "", "sql", "sql-server", "subquery", "" ]
Is it possible to get results similar to the Oracle `DESCRIBE` command for a query? E.g. I have a join among several tables with a restriction of the columns that are returned, and I want to write that to a file. I later want to restore that value from a file into its own base table in another DBMS. I could describe a...
If you plan to re-use the query, it may make sense to create a view for it. You can comment on a database view in the same way that you can for a table: ``` create view TEST_VIEW as select 'TEST' COL1 from dual; comment on table TEST_VIEW IS 'TEST ONLY'; ``` To find comments on a view, execute this: ``` select * f...
If you have a query that represents a set of data that you want to extract from one database and load into a different database, it would seem eminently sensible to create a view in the source database for that query. Once you have that view, you can `describe` the view or otherwise extract the information you are look...
Describing the schema of a query result in Oracle?
[ "", "sql", "oracle", "ddl", "describe", "" ]
I have the following query in mysql: ``` SELECT title, added_on FROM title ``` The results looks like this: ``` Somos Tão Jovens 2013-10-10 16:54:10 Moulin Rouge - Amor em Vermelho 2013-10-10 16:55:03 Rocky Horror Picture Show (Legendado) 2013-10-10 16:58:30 The X-Files: I...
Could you try this? ``` select count(*), DATE_FORMAT(timestamp, "%Y-%m-01") from title group by DATE_FORMAT(timestamp, "%Y-%m-01") ``` Please, note that `MONTH()` can't differentiate '2013-01-01' and '2014-01-01' as follows. ``` mysql> SELECT MONTH('2013-01-01'), MONTH('2014-01-01'); +---------------------+---------...
``` SELECT Count(*), Date(timestamp) FROM title GROUP BY Month(timestamp) ``` Edit: And obviously if it matters to display the 1st day of the month in the results, you do the `DATE_FORMAT(timestamp, "%Y-%m-01")` thing mentioned in some other answers :)
GROUP BY month on DATETIME field
[ "", "mysql", "sql", "" ]
I am trying to get the lowest amount below an average in SQL I have amount 2000, 2500, 3000. The average is 2500. I want to build an SQL query to calculate the AVG and to extract the lowest amount from it. SELECT AVG(Amount) FROM CONTRACT.... I can't figure out how to do the rest Thanks
Assuming that you are concerned only about the amount field and that the data is not very huge you could try this out - SELECT MIN(AMOUNT) FROM CONTRACT WHERE AMOUNT <= (SELECT AVG(AMOUNT) FROM CONTRACT) But, wouldn't the lowest amount below average would simply be the lowest amount of all? Something like this - SEL...
I think what you're looking for is simply: ``` SELECT MIN(Amount) FROM Contract ``` But your question implies somehow applying AVG to a subset of your data, which I don't really understand.
lowest amount below the average amoutn in SQL
[ "", "sql", "" ]
I'm running SQL server management studio and my table/dataset contains approximately 700K rows. The table is a list of accounts each month. So at the begining of each month, a snapshot is taken of all the accounts (and who owns them), etc. etc. etc. and that is used to update the data-set. The 2 fields in question are ...
You want to first isolate the distinct `AccountID` and `Rep` combinations, then you want to use `GROUP BY` and `HAVING` to find `AccountID` values that have multiple `Rep` values: ``` SELECT AccountID FROM (SELECT DISTINCT AccountID, Rep FROM YourTable WHERE Rep NOT IN ('Support Specialist','Friendly Accou...
Try this: ``` SELECT t.AccountID FROM [table] t WHERE NOT EXISTS(SELECT * FROM [reps table] r WHERE r.Rep = t.Rep AND r.[is not human]) GROUP BY t.AccountID HAVING COUNT(DISTINCT t.Rep) > 1; ```
SQL - Where Field has Changed Over Time
[ "", "sql", "time", "duplicates", "where-clause", "" ]
I am using this function to get the diff of two dates a person with the date joined of =03/03/1993 and a date left date of 06/02/2012 should be bringing back 8yrs 11mths but in mine its bringing back 9 years 2 months also i need it adapted If year in Date Joined is after the Year in Date Left you need to minus one Year...
This is how I get your desired answer: ``` DECLARE @D DATETIME SET @D = CONVERT(datetime,'06/02/2002', 103) - CONVERT(datetime,'03/03/1993', 103) SELECT @D SELECT DATEPART(yyyy,@D) - 1900 SELECT DATEPART(mm,@D) - 1 SELECT DATEPART(day,@D) - 1 ```
This is happening because the caller is somewhere converting the strings "03/03/1993" and "06/02/2012" to dates without being explicit about the date semantics and the months and days are getting swapped. So "03/03/1993" is (coincidentally) unambiguous as "1993-MAR-03", but if "06/02/2012" is the same as "2012-FEB-06"...
Function to find length of date range
[ "", "sql", "sql-server", "user-defined-functions", "" ]
I have a table team (name,id,points). i want to find the rank of team based on points. ``` SELECT *FROM team ORDER BY points DESC ``` above query sorts result in descending order of points of team. now i want to find the rank of particular team. means the row number of this result set.
easy way: Count all the teams with more (or equal) points than your desired\_team ``` SELECT Count(*) FROM team WHERE points >= (SELECT points FROM team WHERE name = "team_name"); ``` (you need to include your team so the "list" start with 1.) in that case if your team ha...
Try this. It should give you exactly what you need. ``` SELECT @i:=@i+1 AS rownumber, t.* FROM team AS t, (SELECT @i:=0) AS test ORDER BY points DESC ```
mysql query to find row number of particular record from result set
[ "", "mysql", "sql", "" ]
Suppose,I have a table named items: ``` sender_id receiver_id goods_id price 2 1 a1 1000 3 1 b2 2000 2 1 c1 5000 4 1 d1 700 2 1 b1 500 ``` Here I want to select the sender\_id,goods\_id in descendin...
please try this ``` select sender_id,goods_id from items t1 where not exists (select 1 from items t2 where t2.sender_id = t1.sender_id and t2.receiver_id = t1.receiver_id and t2.price > t1.price) and receiver_id = 1 order by price desc ```
Get the highest price of each group, you could do like below: ``` SELECT T1.* FROM ( SELECT MAX(price) AS max_price, sender_id FROM items GROUP BY sender_id ) AS T2 INNER JOIN items T1 ON T1.sender_id = T2.sender_id AND T1.price = T2.max_price WHERE T1.receiver_id=1 ORDER BY T1.price ```
Selecting distinct value from a column in MySql
[ "", "mysql", "sql", "select", "group-by", "groupwise-maximum", "" ]
I'm using the following T-SQL to obtain role members from my SQL Server 2008 R2 database: ``` select rp.name as database_role, mp.name as database_user from sys.database_role_members drm join sys.database_principals rp on (drm.role_principal_id = rp.principal_id) join sys.database_principals mp on (drm.member_prin...
I've worked out what's going on. When I queried out the role members I was comparing the output with what SSMS listed as role members in the role's properties dialog - this included users as well as roles, but the users weren't being listed by the query as listed in my question. I turns out that when listing role memb...
Here is another way ``` SELECT dp.name as RoleName, us.name as UserName FROM sys.sysusers us right JOIN sys.database_role_members rm ON us.uid = rm.member_principal_id JOIN sys.database_principals dp ON rm.role_principal_id = dp.principal_id ```
How to list role members in SQL Server 2008 R2
[ "", "sql", "sql-server-2008-r2", "" ]
I'm trying to make changes to an existing table and am getting this error when i try to save : > Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving ch...
The following actions might require a table to be re-created: 1. Adding a new column to the middle of the table 2. Dropping a column 3. Changing column nullability 4. Changing the order of the columns 5. Changing the data type of a column To change this option, on the Tools menu, click Options, expand Designers, and ...
you need to change settings to save the changes 1. Open SQL Server Management Studio (SSMS). 2. On the Tools menu, click Options. 3. In the navigation pane of the Options window, click Designers. 4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK. ![enter ima...
SQL server: can't save/change table design
[ "", "sql", "sql-server", "" ]
Trying to figure how how to replace the following, with equivalent left outer join: ``` select distinct(a.some_value) from table_a a, table_b b where a.id = b.a_id and b.some_id = 123 and b.create_date < '2014-01-01' and b.create_date >= '2013-12-01' MINUS select distinct(a.some_value) from table_a a, table_b b wh...
``` SELECT * FROM ( select distinct(a.some_value) from table_a a, table_b b where a.id = b.a_id and b.some_id = 123 and b.create_date < '2014-01-01' and b.create_date >= '2013-12-01' ) x LEFT JOIN ( select distinct(a.some_value) from table_a a, table_b b where a.id = b.a_id and b.some_id = 123...
Here's what my brain puts out after a beer: ``` select distinct a.some_value from table_a a join table_b b on a.id = b.a_id where b.some_id = 123 and b.create_date < '2014-01-01' and b.create_date >= '2013-12-01' and not exists ( select a2.some_value from ...
How to replace a complex SQL MINUS query with LEFT OUTER JOIN equivalent
[ "", "sql", "outer-join", "" ]
I want to return the numbers 1,2,3,4 from mysql in *different* rows. If I run `select 1,2,3,4` then I will get *a single row* with these four numbers. How can I get four different rows each with a single number ? Please don't answer me to create a table containing these numbers ! Also the use case is for a jasper r...
You could use [`UNION ALL`](http://dev.mysql.com/doc/refman/5.1/en/union.html) to concat the rows: ``` SELECT 1 AS ColumnName UNION ALL SELECT 2 AS ColumnName UNION ALL SELECT 3 AS ColumnName UNION ALL SELECT 4 AS ColumnName ``` `Demo`
Try using UNION ``` select 1 as col_name UNION select 2 UNION select 3 UNION select 4 ``` If some of your values occur more than once (say you have two 1s and you want them both in your returned rows), then you may want to use `UNION ALL` instead of `UNION`.
Mysql return enumeration of numbers in different rows
[ "", "mysql", "sql", "" ]
I've created a SQL query in teradata which at product price changes, but want to show the most updated - using the timestamp. The issue however is that the data does have instances where the product\_number, price, timestamp is repeated exactly, giving multiples values. I'm looking to eliminate those duplicates. ``` ...
Simply use a ROW\_NUMBER + QUALIFY ``` select * from product_price qualify row_number() over (partition by product_number order by update_timestamp desc) = 1; ```
You should be able to simply move your `DISTINCT` operator to the outside query, or do a GROUP BY that covers all columns (doing it on just `maxtimestamp` will result in an error). ``` select DISTINCT a.product_number, a.maxtimestamp, b.product_price from ( SELECT product_number ,MAX(update_timestamp) as maxtimes...
SQL timestamp, eliminate duplicate rows
[ "", "sql", "teradata", "" ]
I wanted to understand the UDF WeekOfYear and how it starts the first week. I had to artifically hit a table and run the query . I wanted to not hit the table and compute the values. Secondly can I look at the UDF source code? ``` SELECT weekofyear ('12-31-2013') from a; ```
You do not need table to test UDF since Hive 0.13.0. See this Jira: [HIVE-178 SELECT without FROM should assume a one-row table with no columns](https://issues.apache.org/jira/browse/HIVE-178) **Test:** ``` hive> SELECT weekofyear('2013-12-31'); ``` **Result:** ``` 1 ``` The source code (master branch) is here: [...
If you are Java developer, you can write Junit Test cases and test the UDFs.. you can search the source code of all hive built in functions in **grepcode**. <http://grepcode.com/file/repo1.maven.org/maven2/org.apache.hive/hive-exec/1.0.0/org/apache/hadoop/hive/ql/udf/UDFWeekOfYear.java>
how can we test HIVE functions without referencing a table
[ "", "sql", "hive", "hiveql", "hive-udf", "" ]
I would like to know if a user has a privilege on an object or not. I'm working on SQL Developer. When I query manually the table **DBA\_TAB\_PRIVS**, I get all the information needed. However, I need this information to be used in some triggers and functions. So, I'm writing PL/SQL function that will return 1 if a...
I'll wager that you have privileges on `dba_tab_privs` via a role, not via a direct grant. If you want to use a definer's rights stored function, the owner of the function has to have privileges on all the objects granted directly, not via a role. If you disable roles in your interactive session, can you still query `...
You can use `table_privileges`: ``` select * from table_privileges; ``` This does not require any specific rights from your user.
How to know if a user has a privilege on Object?
[ "", "sql", "oracle", "plsql", "privileges", "" ]
Is there a way to retrieve all the sequences defined in an existing oracle-sql db schema? Ideally I would like to use something like this: ``` SELECT * FROM all_sequences WHERE owner = 'me'; ``` which apparently doesn't work.
Try this: ``` SELECT object_name FROM all_objects WHERE object_type = 'SEQUENCE' AND owner = '<schema name>' ```
Yes: ``` select * from user_sequences; ``` Your SQL was almost correct too: ``` select * from all_sequences where sequence_owner = user; ```
How to check if a sequence exists in my schema?
[ "", "sql", "oracle11g", "sequences", "" ]
Assume I have an table of orders with the following columns: `Model` `Quantity` `Price` `ScheduleB` `OrderID` There can be multiple `Model` with the same `ScheduleB` classification. I need a SQL statement that will only return a record where the total price (`Quantity` \* `Price`) of all `Model` of similarly ...
Yes, it can be done: ``` Select Model ,Quantity ,Price ,ScheduleB ,OrderID From Table1 WHERE ScheduleB IN (SELECT ScheduleB FROM Table1 GROUP BY ScheduleB HAVING SUM(Quantity * Price) > 2500) ```
The following SQL statement did the trick: `Select ScheduleB from (select (Select Sum(Quantity) From orderitems where OrderID = ? AND ProductID = products.ProductID Group BY ProductID) as Quantity, orderitems.ItemPrice, categories.ScheduleB from orderitems INNER JOIN products ON products.ProductID = orderitems.Product...
SQL Statement - Based on Total Sum of a Column Type
[ "", "mysql", "sql", "" ]
I have been trying out postgres 9.3 running on an Azure VM on Windows Server 2012. I was originally running it on a 7GB server... I am now running it on a 14GB Azure VM. I went up a size when trying to solve the problem described below. I am quite new to posgresql by the way, so I am only getting to know the configura...
Those seq scans make it look like you didn't run `analyze` on the table after importing your data. <http://www.postgresql.org/docs/current/static/sql-analyze.html> During normal operation, scheduling to run `vacuum analyze` isn't useful, because the autovacuum periodically kicks in. But it is important when doing mas...
Unless your encoding or collation is C or POSIX, an ordinary btree index cannot efficiently satisfy an anchored like query. You may have to declare a btree index with the varchar\_pattern\_ops op class to benefit.
Postgresql: How do I ensure that indexes are in memory
[ "", "sql", "postgresql", "configuration", "indexing", "" ]
I'm new to `SQL` and I want to create a `One-To-Many` relationship between two tables. I have these two tables created with the following queries: ``` CREATE TABLE Customers ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName VARCHAR(255) NOT NULL, LastName VARCHAR(255) NOT NULL, Email VARCHAR(255) NOT...
I gave up and started using the web client of MySQL...
You need to set the storage engine...change your query to... ``` CREATE TABLE Orders ( OrderId INT NOT NULL AUTO_INCREMENT, Date DATE NOT NULL, Quantity INT NOT NULL, TotalDue FLOAT NOT NULL, CustomerId INT NOT NULL, PRIMARY KEY(OrderId), FOREIGN KEY(CustomerId) REFERENCES Customers(Custome...
SQL One-To-Many relationship
[ "", "mysql", "sql", "relational-database", "one-to-many", "" ]
I'm trying to add a computed column to a SQL Server 2008 Express table. The formula is: ``` case when callrecord_contacttype=1 then 'Routed voice' else when callrecord_contacttype=2 then 'Direct incoming voice' else when callrecord_contacttype=3 then 'Direct outgoing voice' else when callrecord_contacttype=4 then ...
Try : ``` case callrecord_contacttype when 1 then 'Routed voice' when 2 then 'Direct incoming voice' when 3 then 'Direct outgoing voice' when 4 then 'Direct internal voice' when 5 then 'Routed callback' when 6 then 'Routed email' when 7 then 'Direct outgoing email' when 8 then 'R...
Have only 1 `ELSE` in your query: ``` case when callrecord_contacttype=1 then 'Routed voice' when callrecord_contacttype=2 then 'Direct incoming voice' when callrecord_contacttype=3 then 'Direct outgoing voice' when callrecord_contacttype=4 then 'Direct internal voice' when callrecord_contacttype=5 then 'Routed ca...
computed column - Incorrect syntax near the keyword 'when'
[ "", "sql", "sql-server", "sql-server-2008", "case", "calculated-columns", "" ]
``` ID Place Name Type Count -------------------------------------------------------------------------------- 7718 | UK1 | Lemuis | ERIS TELECOM | 0 7713 | UK1 | Astika LLC | VERIDIAN | 34 7712 | UK1 | Angel Telecom AG |...
``` SELECT * FROM FullResults WHERE ID = (SELECT ID FROM FullResults WHERE Type= @variable); ``` I guess it will be something like this?
Something like this should do the trick, returns all data for all ID's that have a matching type. ``` SELECT * FROM Table WHERE ID IN (SELECT ID from Table where Type = 'ERIS TELECOM') ```
SQL query to get specific rows based on one value
[ "", "mysql", "sql", "sql-server", "stored-procedures", "" ]
I want to return two defaults column values even if the table has no records. I'm using the following query (thanks to [How to SELECT DEFAULT value of a field](https://stackoverflow.com/a/8266834/466153)): ``` SELECT DEFAULT(membership_credits) AS membership_credits, DEFAULT(product_credits) AS product_credits ...
It all depends on if your columns allow `NULL` or not. If `NULL` allow, a query like the following will be useful, so the table does not have records: ``` SELECT DEFAULT(`membership_credits`) `membership_credits`, DEFAULT(`product_credits`) `product_credits` FROM (SELECT 1) `dummy` LEFT JOIN `users` ON TRUE LIM...
if you use following query to create table ``` CREATE TABLE `users` ( `user_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `user_login` VARCHAR(40) NOT NULL, `user_name` VARCHAR(100) NOT NULL, `user_email` VARCHAR(254) NOT NULL, `user_telephone` VARCHAR(100) NOT NULL, `user_password` VARCHAR(...
SELECT DEFAULT returns NULL
[ "", "mysql", "sql", "phpmyadmin", "" ]
I am relatively new to SQL so apologies for any stupid questions, but I can't even get close on this. I have a data set of customer orders which consists of **Cust\_ID** and **Date**. I want to return a query that has all the customer orders adding two fields, "Date of first order" and "order count" ``` Cust_ID Da...
``` SELECT foo.Cust_ID , foo.`Date` , MIN(p.`Date`) AS FirstOrder , COUNT(*) AS orderCount FROM foo JOIN foo AS p ON p.Cust_id = foo.Cust_id AND p.`Date` <= foo.`Date` GROUP BY foo.Cust_ID, foo.`Date` ORDER BY foo.`Date`; ```
If I understood you correctly: Source data you have: ``` Cust_ID Date 5001 04/10/13 5001 11/10/13 5002 11/10/13 5001 17/10/13 5001 24/10/13 5002 24/10/13 ``` Result dataset you expect: ``` Cust_ID Date FirstOrder OrderNumber 5001 04/10/13 ...
SQL aggregating running count of records
[ "", "mysql", "sql", "" ]
I've got a database which contains lots of data. I would like to select all data, but Group by one column. So for example: ``` column a | column b example | apple example | pear example | orange example | strawberry ``` In the example column A is a column which has duplicate values and needs to be grouped. Colum...
I think you can get what you want using `group_concat()`: ``` select a, group_concat(b) from t group by a; ``` This will create a list of "b"s for each a. In your example: ``` example apple,pear,orange,strawberry ``` You can change the separator using the `SEPARATOR` keyword. EDIT: You can use `group_concat()`...
All SQL systems deal in tables: rectangles of data with rows and columns. Your question asks for a result set which isn't really a rectangle of data, in the sense that it contains "header" rows and "detail" rows. ``` Example: (header row) - apple (detail row) ``` It's common practice to create such header / ...
MySQL Group by one column, but select all data
[ "", "mysql", "sql", "" ]
I'm using the following query to return the ages (in years) of all stored user date of births. It would be useful if I could essentially tally the ages so I could generate a report. The query is chunky and therefore makes it very difficult for me to understand how I'd do this, especially since aggregate functions canno...
Just use a CTE or subquery to create the ages first, and then a simple group by query to tally them up: ``` ; With Ages as ( Select DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - CASE WHEN DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP) > CURRENT_TIMESTAMP ...
Can you try this, ``` Select X.age, sum (X.num) numUsers From ( Select DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - CASE WHEN DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END age, 1 num from [database].[dbo].[users] ) X grou...
Return number of people of a certain age deduced from stored DOBs
[ "", "sql", "sql-server", "database", "" ]
I currently have a table of Users, and at what time they connected to a device (e.g. a Wifi Router). ``` +-------------+-----------+---------+------------+---------------------+ | location_id | device_id | user_id | dwell_time | date | +-------------+-----------+---------+------------+------------------...
``` select * from users inner join (select user_id,max(date) as maxdate from users group by user_id)T1 on T1.user_id = users.user_id AND T1.maxdate = users.date ``` or if you don't want to have a subquery, you can user @variables like this query below ``` SELECT location_id,device_id,use...
Assuming the combination of `user_id` and `date` is unique in the table, you could ``` SELECT tablename.* FROM tablename INNER JOIN ( SELECT user_id, MAX(`date`) AS maxdate FROM tablename GROUP BY user_id ) AS selector ON tablename.user_id=selector.user_id AND tablename.`date`=selector.maxdate ```
SQL Statement Construction: Selecting Unique Records
[ "", "mysql", "sql", "select", "group-by", "unique", "" ]
I have a schema that has two relations. One is loan which has the attributes loan-number, branch-name and amount. The other is borrower which has customer-name and loan-number as its attributes. These two relations are linked via loan-number. How would I write a query in relational algebra to find the names of custome...
Do some research on relational algebra 8 main operators: restriction, projection, cartesian product, join, union, intersection, set difference and division. To answer your question: ``` loan(loan_number, branch_name, amount) borrower(customer_name, loan_number) ``` Perform a natural join of the both relations, apply...
Disclaimer: I am not too familiar with relational algebra. SQL can be quickly seen as using an implicit inner join and then an filter on loan.amount: ``` SELECT customer-name FROM Borrower, Loan WHERE Customer.loan-number = Loan.loan-number AND Loan.amount > 10000 ``` And then translate this into an relational alge...
SQL Relational Algebra Query
[ "", "sql", "relational-algebra", "" ]
I am trying to return people from a search string that can consist of any variation of a name, such as: 'john', 'john smith', 'smith, john', 'john jason smith', or any other common variation. I can cleanup the string and format as a regular expression if need be. I am aiming for something similar to this: ``` SELECT ...
If you want to only return rows that meet all of your supplied criteria then you need to add those filter criteria. There are a couple of ways to do it but you could do something as simple as this: * Split up your term into the searchable tokens * Make your search case insensitive by forcing everything to upper case *...
Try this dude. I tested this against SQL server and it works. Make the necessary change for it to work against Oracle. I've only tested this with 1 field name. Just edit the code so it suits your needs. It's basically @Carth 's solution implemented only using SQL. ``` DECLARE @stringsearch varchar(255)='stringvalue' ...
Searching names with SQL
[ "", "sql", "oracle", "" ]
I want to insert data into my table, but insert only data that doesn't already exist in my database. Here is my code: ``` ALTER PROCEDURE [dbo].[EmailsRecebidosInsert] (@_DE nvarchar(50), @_ASSUNTO nvarchar(50), @_DATA nvarchar(30) ) AS BEGIN INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE,...
instead of below Code ``` BEGIN INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE, @_ASSUNTO, @_DATA) WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos WHERE De = @_DE AND Assunto = @_ASSUNTO AND Data = @_DATA); END ``` replace with ``` BEG...
For those looking for the *fastest way*, I recently [came across these benchmarks](http://cc.davelozinski.com/sql/fastest-way-to-insert-new-records-where-one-doesnt-already-exist) where apparently using "INSERT SELECT... EXCEPT SELECT..." turned out to be the fastest for 50 million records or more. Here's some sample ...
SQL Server Insert if not exists
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "sql-insert", "" ]
In SQL Server 2008, this query works: ``` SELECT SUM(CAST(isredeemed AS TINYINT)) AS totalredeemed, FROM rewards GROUP BY merchantid ``` It gives you the number of redeemed rewards by merchant. The `TINYINT` cast is need to avoid the error `Operand data type bit is invalid for sum operator.` Now I'd like to do ...
This question lacks detail to give an exact answer but you need to use a derived table or subquery for the calculation. something like this ``` SELECT r1.merchantid, r2.claimedthisweek FROM rewards r1 JOIN ( SELECT merchantid, SUM(CAST(isredeemed AS INT)) claimedthisweek FROM rewards GROUP BY merchantid ...
I think you want this would work but it would count some twice: ``` SELECT SUM(case when MIN(dateredeemed) > '2014-01-10 05:00:00' then 1 else 0 end ) FROM rewards GROUP BY merchantid ```
Using boolean logic inside SUM function
[ "", "sql", "sql-server", "sql-server-2008", "" ]
We will get id from user in this form: ``` "A-123456-14" ``` and want to search in database with simple id in this form : ``` 123456 ``` I have tried ``` select * from orders where id = '%' + searchId + '%'; ``` here id = 123456 in database and searchId = 'A-123456-14' which get from user. but its not working a...
you can use: ``` SELECT * FROM orders WHERE WHERE 'A-123456-14' REGEXP '[:punct:]' + id + '[:punct:]'; ``` in above you can replace 'A-123456-14' with user input searchId i have tried its work fine
``` SELECT * FROM orders WHERE id = SUBSTRING_INDEX( SUBSTRING_INDEX(searchId, '-', 2), '-',- 1) ``` EDIT: If you want to make everything dynamic then you can try this (You should post delimiter as a parameter also, if it is dynamic). ``` SELECT * FROM orders WHERE id = ...
search database id field with string manipulated id
[ "", "mysql", "sql", "search", "select", "sql-like", "" ]
``` SELECT bm.WinningNumber,bd.BetOnNumber,"WinLossAmount" = CASE WHEN 2 in (2,1) THEN ('WIN') END FROM BettingMaster bm inner join BettingDetail bd on bm.GameID = bd.GameID where bd.GameID = 1 ``` This works as a Charm and I get 'WIN' in WinLossAmount. Now I actually hav...
IN operator in SQL searches values in the row set. But in the second example you try to find INT value in the STRING so you can't use `IN` this way. In the most SQL systems you can try to use following condition. Where `+` is a concatenate operator in MSSQL (in Oracle `||`, in MySQL `CONCAT()`) ``` WHEN ','+bd.BetOnN...
I believe the problem is that in the first statement, SQL is comparing 2 to 1 and then 2 to 2, all integers. Obviously, finding the match and working. In the second case, you're comparing 2 to a string of "1,2" and 2 does not equal "1,2". You'll need to split the varchar into a series of integers before you compare it...
trouble with IN clause in sql
[ "", "sql", "sql-server-2012", "" ]
Let's say I have a Table that looks like this: ``` id fk value ------------ 1 1 'lorem' 2 1 'ipsum' 3 1 'dolor' 4 2 'sit' 5 2 'amet' 6 3 'consetetur' 7 3 'sadipscing' ``` Each **fk** can appear multiple times, and for each **fk** I want to select the last row (or more precise the row with the respective...
``` SELECT * FROM table WHERE id IN (SELECT MAX(id) FROM table GROUP BY fk) ```
Try this: ``` SELECT a.id, a.fk, a.value FROM tableA a INNER JOIN (SELECT MAX(a.id) id, a.fk FROM tableA a GROUP BY a.fk ) AS b ON a.fk = b.fk AND a.id = b.id; ``` **OR** ``` SELECT a.id, a.fk, a.value FROM (SELECT a.id, a.fk, a.value FROM tableA a ORDER BY a.fk, a.id DESC) AS a GROUP BY a.fk; ```
SELECT only one entry of multiple occurrences
[ "", "mysql", "sql", "select", "group-by", "greatest-n-per-group", "" ]
i trying to do a sql query which i combine de compare operators with substring. in my column date i have the following value inside : **09-01-2014 12:02:55** what i try to now is to select all rows which is **>= 09-01-2014** and for example **<=22-01-2014** how can i do it? i have trying for example with this code:...
You can use the `BETWEEN` operator ``` SELECT * FROM table WHERE Name = 'Something' AND SUBSTRING(date, 1, 10) BETWEEN '09-01-2014' AND '22-01-2014' ``` EDIT: I'm still leaving this here, but it is not an error proof solution (as pointed out by oerkelens down in the comments)
The `BETWEEN` operator will work, like this: ``` SELECT * From table Where Name= 'Something' AND `date` BETWEEN '2014-01-09' AND '2014-01-23' ``` Working Demo: <http://sqlfiddle.com/#!2/b4d7e>
SQL - Select all rows which is >= and <=
[ "", "mysql", "sql", "datetime", "select", "" ]
Say I have a package with a spec defined in **mySpec.pks** ``` CREATE OR REPLACE PACKAGE TEST_PKG AS PROCEDURE TEST_1 ( asdf int ); PROCEDURE TEST_2 ( asdf int, asdf2 char ); END; ``` Is it possible to split the implementation of each procedure into multiple body "CREATE OR REPLACE PACKAGE BODY" statements? ...
No, it is not. A package body is a single entity, there must be a single `CREATE` statement. Just like the entire implementation of an object has to be in a single file, the entire implementation of a package must be in a single file. The desire to split the implementation across multiple files would tend to imply to ...
You can't quite do what you suggest, but it is possible to split the package body *file* into smaller sections, as long as you're using SQL\*Plus to load the package. I'm not suggesting this is a good idea, and I'd generally agree with Justin about refactoring your design if you're doing this for size reasons. But just...
Define elements of a package spec in multiple scripts?
[ "", "sql", "database", "oracle", "plsql", "" ]
I need a little help with a MySQL query. I have two tables one table is a list of product and one table is a list of warehouses quantity product: ``` product_id product_name 1 name1 2 name2 3 name3 ``` warehouse\_product ``` id warehouse_id product_id product_quantity 1 ...
Try this: ``` SELECT p.product_id, p.product_name, SUM(wp.quantity) as quantity FROM product as p LEFT JOIN warehouse_product as wp ON p.product_id = wp.product_id AND product_active = 1 GROUP BY p.product_id, p.product_name ``` After JOINing the two tables you need to use `GROUP BY` so that `SUM` of quantity can...
``` SELECT P.productid, P.ProductName, Sum(W.product_quantity) As quantity FROM Product AS P LEFT JOIN warehouse_product AS W ON P.productid = W.productid GROUP BY P.ProductId , P.ProductName ``` `SQLFiddle`
Join two table. One column using SUM
[ "", "mysql", "sql", "" ]
For the sake of brevity, let's assume we have a `numbers` table with 2 columns: `id` & `number`: ``` CREATE TABLE numbers( id INT NOT NULL AUTO_INCREMENT, NUMBER INT NOT NULL, PRIMARY KEY ( id ) ); ``` I want the `number` column to auto-increment, but restart from 1 after hitting 100, satisfying the followin...
Try to use modulo `%` operator ``` INSERT INTO `numbers` (`number`) VALUES ( IFNULL( (SELECT `number` FROM `numbers` as n ORDER BY `id` DESC LIMIT 1), 0 ) % 100 + 1 ) ```
You could use a temp variable. ``` INSERT INTO `numbers`(`number`) VALUES ( IF((@a := IFNULL((SELECT number FROM `numbers` AS n ORDER BY id DESC LIMIT 1), 0)) > 99, 1, @a + 1) ); ```
Any way to remove the duplicate SELECT statement?
[ "", "mysql", "sql", "select", "insert", "select-insert", "" ]
I want to know what is the meaning or purpose of inserting a value like- ``` insert into table_name (column_name) values(''); ``` And what is the difference b/w above statement and not inserting a value for the column(means adding `null`)
Selects records where ID is an empty string ``` select * from tablename where id='' ``` Selects records where ID is NULL ``` select * from tablename where id is null ``` A NULL indicates absence of data where as an '' (empty string) is actually a string of length 0. For you better understanding: ``` SELECT LEN(NU...
in case if you set `NOT NULL` as a property of the column - this doesn't give you an error as a result of insert.
difference between select * from tablename where id='' and select * from tablename where id is null
[ "", "mysql", "sql", "" ]
Ok, I am using Mysql DB. I have 2 simple tables. ``` Table1 ID-Text 12-txt1 13-txt2 42-txt3 ..... Table2 ID-Type-Text 13- 1 - MuTxt1 42- 1 - MuTxt2 12- 2 - Xnnn ``` Now I want to join these 2 tables to get all data for `Type=1` in table 2 SQL1: ``` Select * from Table1 t1 Join (select * from Table2 where Type=1)...
Sometimes the MySQL query optimizer does a pretty decent job and sometimes it sucks. Having said that, there are exception to my answer where the optimizer optimizes something else better. Sub-Queries are generally expensive as MySQL will need to execute and store results seperately. Normally if you could use a sub-qu...
As per my view 2nd query is more better than first query in terms of code readability and performance. You can include filter condition in Join clause also like ``` Select * from Table1 t1 Join Table2 t2 on t1.ID=t2.ID and t2.Type=1 ``` You can compare execution time for all queries in SQL fiddle here : [Query 1](...
Which Query is faster if we put the "Where" inside the Join Table or put it at the end?
[ "", "mysql", "sql", "" ]
Okay, so I've got two tables. One table (`table 1`) contains a column `Books_Owned_ID` which stores a series of numbers in the form of `1,3,7`. I have another table (`table 2`) which stores the Book names in one column and the book ID in another column. What I want to do is create an SQL code which will take the numbe...
The core of this centers around data normalisation... Each fact is stored only once (and so is "authoritative"). You should also get into the habit of only storing a single fact in any field. So, imagine the following table layouts... ``` Books Id, Name, Description Users Id, Username, EmailAddress, Password...
You need to do an inner join. [This is a great example/reference for these](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html) ``` SELECT Book_Name FROM Table2 INNER JOIN Table1 ON Table1.Books_Owned_ID = Table2.Book_ID ``` **EDIT** [SQL Fiddle](http://sqlfiddle.com/#!3/6abca/2) I will ...
SQL Cross-Table Referencing
[ "", "sql", "sql-server", "" ]
I'm really confused here. Running the following query: ``` SELECT * FROM `articles` WHERE `form` = 'Depotplåster' AND `size` = 5 ``` returns rows that also start with "5", despite me neither using `LIKE` nor a `%` wildcard operator. How come? The `size` field is of type `VARCHAR`. ![enter image description here](ht...
That is because you're using comparison between numeric and varchar data. MySQL will implicitly convert your column to `double`, resulting in `5`. See this simple test data: ``` mysql> select * from test; +-----------------+ | name | +-----------------+ | 5 | | 5 and some crap | +-------------...
``` SELECT * FROM `articles` WHERE `form` = 'Depotplåster' AND `size` = '5' -- this will compare the string 'size' with the string '5' SELECT * FROM `articles` WHERE `form` = 'Depotplåster' AND `size` = 5 -- this will convert string 'size' to integer and then compare with the integer 5 ``` The conversion of string t...
Query returns "LIKE" results despite not having wildcards?
[ "", "mysql", "sql", "equality", "" ]
I wish to find all records of the current day. I have a field Date of type DATE. I am getting error on sql server ``` 'DATE' is not a recognized built-in function name. ``` on this line ``` (DATE(EnterDate) = CURDATE() ) ```
As the error states, there is no `DATE` *function* in SQL Server 2008 or 2012 (you tagged both so I'm not sure which you're targeting). You *can*, however, cast to a `date` type in SQL Server 2008 and above: ``` WHERE EnterDate = CONVERT(date,GETDATE()) ``` Note that there's no `CURDATE` function either, so I've tran...
Use the following condition in your where cluase ``` WHERE CAST(DateColumn AS DATE) = CAST(GETDATE() AS DATE) ^------------ Your Column Name with `Date` or 'DateTime' data type ``` `CURDATE()` is a mysql function, In Sql-Server we have `GETDATE()` function to get current date and time.
'DATE' is not a recognized built-in function name
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "ssms", "" ]
Conceptual stage question: I have several Tables (**Person**, **Institution**, **Factory**) each has many kinds of **Addresses** (**Mailing**, **Physical**) Is there a way to create a **single** Address table that contains **all the addresses** of all the Entities? I'd rather not have a **PersonAddress** and **Facto...
My proposal relies on the principle that one entity (person, Institution, Factory, etc) can have multiple adresses, which is usually the case (home, business, etc), and that one adress can be shared by entities of different nature: ``` CREATE TABLE ADDRESS ( ID INT IDENTITY PRIMARY KEY NOT NULL, .... (your ad...
You need to use abstraction and inheritance. An `individual` and `institution` (I'd call it organization) are really just concrete representations of an abstract `legal party`. A `mailing` or `physical address` is the concretion of an abstract `address`, which could also be an email address, telephone number, or web ...
One Address Table for Many entities?
[ "", "sql", "sql-server", "database-design", "" ]
Surprisingly there isn't any straight forward example to demonstrate the use of delimiter in Stored Procedure? I have a string variable as input (with delimiter) and would like to make it as condition in Stored Procedure. Something like below: ``` CREATE PROCEDURE testing ( @stringVar NVARCHAR(255) = NULL ) .....
it is a bit of tricky situation and there is no "Simple way" of doing it. but I can give you the simplest way of doing it. You will need to do two things to make this work, > 1) Create a Split function which takes a parameter of deliminited > string and split these values. > 2) Make your stored procedure in a > wa...
From SQL Server 2008 on, you can use **table valued parameters**. I cannot explain it better than here: <http://www.sommarskog.se/arrays-in-sql.html>
SQL Server Simple example for the use of Delimiter in Stored Procedure
[ "", "sql", "sql-server", "stored-procedures", "delimiter", "" ]
How can I get the create table command which is used to create a table in oracle 11g so that I can copy the command and run it in another database? Please help.
``` select dbms_metadata.get_ddl('TABLE', 'YOUR_TABLE_NAME_GOES_HERE') from dual; ```
Try to spool the output of the below query, ``` SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u; ``` Like, ``` set pagesize 0 set long 90000 set feedback off set echo off spool schema.sql SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u WHERE TABLE_NAME = '<yo...
Getting the create table command used in oracle 11g
[ "", "sql", "oracle", "oracle11g", "" ]
Edit: For anyone facing this problem, don't miss the tips about only using parameters instead of inserting the values directly into the SQL queries. --- i'm facing a big problem with my vb.net project, i'm stuck with this for a week i've a combobox item that i need to compare with an access number which is my databa...
number criteria should be without quote ``` Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number, " _ & "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _ & "WHERE Number =" & CInt(mycombobox.SelectedItem), c...
In your WHERE clause have you tried to remove the quotes ? They are not required if you are looking for a number.
Can't compare vb.net item with access number
[ "", "sql", ".net", "database", "vb.net", "ms-access", "" ]
``` create procedure db.Test @input1 varchar(max), @input2 {Either 'yes' or 'no'} ``` I want the input2 from users to be restricted to either 'yes' or 'no'. Can anyone provide me with the syntax. I found the synax for default value ``` @input2 varchar(max) default 'yes' ``` But couldnt find anything for restricted ...
You need to make a check with and `if` statement. There isn't a "restriction" validator for what you need. ``` create procedure db.Test @input1 varchar(max), @input2 varchar(3) as begin if @input2 not in ('yes', 'no') begin --raiserror or similar return end (...) end go ```
You can create your own custom error messages for RAISERROR. ``` exec sp_addmessage @msgnum=50010,@severity=1,@msgtext='Invalid input parameters' ``` After this , errorid 50010 will point to message Invalid input parameters. ``` create procedure db.Test @input1 varchar(max), @input2 varchar(3) as begin if @input...
Restricted user input values in Stored Procedures SQL
[ "", "sql", "sql-server", "stored-procedures", "" ]
I want to find how many modules a lecturer taught in a specific year and want to select name of the lecturer and the number of modules for that lecturer. Problem is that because I am selecting `Name`, and I have to group it by name to make it work. But what if there are two lecturers with same name? Then sql will make...
``` SELECT a.lecturerName, b.NumOfModules FROM Lecturer a,( SELECT l.lecturerID, COUNT(moduleID) AS NumOfModules FROM Lecturer l , Teaches t WHERE l.lecturerID = t.lecturerID AND year = 2011 GROUP BY l.lecturerID) b WHERE a.lecturerID = b.lecturerID ```
You should probably just group by `lecturerID` and *include it in the select column list.* Otherwise, you're going to end up with two rows containing the same name with no way to distinguish between them. You raise the problem of "wrong output" when grouping just by name but "undecipherable output" is just as big a pr...
Group by a field not in select
[ "", "sql", "group-by", "" ]
![enter image description here](https://i.stack.imgur.com/r4vyL.png)I am executing a query from which i want to get all server name installed on a system So I did it with this query ``` select srvname from sysservers ``` It gives me server names but it is not the correct server name it gives me srvname `WIN-1BKHG...
To check what the current values are set to ``` SELECT ServerProperty('machinename') as [machinename] ,ServerProperty('ServerName') as [ServerName] ,@@ServerName as [@@ServerName]; ``` To correct the issue run the following: ``` EXEC sp_dropserver 'old_server_name'; GO EXEC sp_addserver 'new_server_name', '...
This can happen when the server name is changed after SQL Server was installed. You could try sp\_dropserver and sp\_addserver to change it back: <http://www.brentozar.com/blitz/servername-not-set/> Im not sure i would though you dont know why it was changed in the first place it might break something.
Getting Wrong Server Name
[ "", "sql", "sql-server-2008-r2", "" ]
here is table `T` :- ``` id num ------- 1 50 2 20 3 90 4 40 5 10 6 60 7 30 8 100 9 70 10 80 ``` and the following is a **fictional** sql ``` select * from T where sum(num) = '150' ``` the expected result is :- (A) ``` id num ------- 1 50 8 100 ``` (B) ``` id num ------- 2 20 7 30 ...
You can use recursive query in MSSQL to solve this. `SQLFiddle demo` The first recursive query build a tree of items with cumulative sum <= 150. Second recursive query takes leafs with cumulative sum = 150 and output all such paths to its roots. Also in the final results ordered by `ItemsCount` so you will get prefer...
If you restrict your problem to "which ***two*** numbers add up to a value", the solution is as follows: ``` SELECT t1.id, t1.num, t2.id,t2.num FROM T t1 INNER JOIN T t2 ON t1.id < t2.id WHERE t1.num + t2.num = 150 ``` If you also want the result for three and more numbers you can achieve that by using the above qu...
sql server : select rows who's sum matches a value
[ "", "sql", "sql-server", "sql-server-2012", "subset-sum", "" ]
Its hard to explain what exactly i mean using words so ill write a query similar to what i have at the moment. ``` SELECT * FROM table t WHERE t.something = 'something' AND CASE WHEN t.name = 'john' THEN 'smith' ELSE t.lastname END = t.lastname ``` Basicly depending if a field is what i want it to be (name = joh...
You can do this without the `case`: ``` WHERE t.something = 'something' AND (t.lastname = 'smith' or t.name <> 'john') ```
You can place the entire test within the `CASE` statement: ``` AND CASE WHEN t.name = 'john' THEN t.lastname = 'smith' ELSE True ``` (I don't remember my Oracle so well. `True` may not be the correct term here.) Now the result of the `CASE` is a truth value rather than a value to be tested against `t.lastname`.
oracle query - additional where condition depending on a field
[ "", "sql", "oracle", "" ]
i need assign value word by numeric so i tried below code.but its showing error"Incorrect syntax near the keyword 'case'." ``` declare @ww int set @ww=1 case @ww WHEN '1' THEN print='one' ELSE NULL ``` where i made error...?
Please read <http://technet.microsoft.com/en-us/library/ms181765.aspx> In there it states "CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select\_list, IN, WHERE, ORDER BY, and HAVING...
**You can't use Case in stand alone, instead use it like this** ``` declare @ww int set @ww=1 SELECT CASE @ww WHEN '1' THEN 'one' ELSE NULL end ```
how to use case sql server 2008
[ "", "sql", "sql-server", "" ]
I have a query like this one: ``` SELECT type, count(case when STATUS = 'N/A' then 1 end) as NOTAPPLICABLE, count(case when STATUS = 'Failed' then 1 end) as FAILED, count(case when STATUS = 'No Run' then 1 end) as NO_RUN, count(case when STATUS = 'Not Completed' then 1 end) as NOT_COMPLETE, count(case when...
You can use expressions in `ORDER BY` ``` SELECT type, count(case when STATUS = 'N/A' then 1 end) as NOTAPPLICABLE, count(case when STATUS = 'Failed' then 1 end) as FAILED, count(case when STATUS = 'No Run' then 1 end) as NO_RUN, count(case when STATUS = 'Not Completed' then 1 end) as NOT_COMPLETE, count(c...
If Column aliases that are defined in the `SELECT` are then referenced in the `ORDER BY` they must be used on their own. Not in an expression. You can use a derived table. ``` SELECT * FROM ( /* Your Query here*/ ) T ORDER BY PASSED/TOTAL DESC ``` You may also need to cast `PASSED` to numeric to avoid integer divis...
Order by the result of a division of two counts
[ "", "sql", "" ]
I'm currently developing an API for a company that didn't do a very good job on maintaining a good test database with test data. The MySQL database structure is quite big and complicated and the live database should be around 160-200GB. And because I'm quite lazy and don't want to create test data for all the table fr...
Take a look at [Jailer](http://sourceforge.net/projects/jailer/) which describes itself as a "Database Subsetting and Browsing Tool". It is specifically designed to select a subset of data, following the database relationships/constraints to include all related rows from linked tables. To limit the amount of data you e...
I would suggest that it doesn't matter how thorough you are the risk of getting live customer details into a test database is too high. What happens if you accidentally email or charge a real customer for something your testing!? There are a number of products out there such as RedGate's [Data Generator](http://www.re...
How to turn a huge live database into a small testing database?
[ "", "mysql", "sql", "database", "testing", "database-migration", "" ]
``` SELECT INT_VALUE = NULL -- Result Data Type = INT ,STR_VALUE = NULL -- Result Data Type = INT ``` I want to make sure that STR\_VALUE is a varchar NULL and not int NULL. I need this to be done in SELECT statement and in derived column. How can I achieve that? Thank you UPDATE: Thanks guys for really quick feedb...
Just `CAST` it: ``` SELECT INT_VALUE = CAST(NULL AS int) ,STR_VALUE = CAST(NULL as VARCHAR(10)) ```
`NULL` defaults to an int. You can change it to any other type using `cast()`: ``` SELECT INT_VALUE = NULL, -- Result Data Type = INT STR_VALUE = cast(NULL as varchar(255)) -- Result Data Type = varchar(255) ```
T-SQL Derived Column in SELECT
[ "", "sql", "sql-server", "" ]
I have a query where I am using SUM to total up bill detail values. I would like to create a `CASE` statement that works off the results of that sum, rather than the values being summed. Below is a partial example of what my query currently looks like. ``` SELECT bill.billnumber_id, billdetail.billclass, ...
Is this what you want? ``` SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount, (case when SUM(billdetail.amount) > 10 then 'BigOne' else 'Little' end) GROUP BY bill.billnumber_id, billdetail.billclass ```
You need to use a sub-query: ``` SELECT CASE WHEN Amount = 0 THEN 'Nothing' ELSE 'somthing' END AmountComment FROM( SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount GROUP BY bill.billnumber_id, billdetail.billclass )x ```
CASE statement based on SUM results in query
[ "", "sql", "sql-server-2008", "reporting-services", "" ]
I'm trying to use a case statement to update a column based on the value of another column. My table called 'rma' in MySQL is as follows: ``` ID | rma_number | serial_number | ref_status_id 1 | 9898 | 123456 | 19 2 | 7869 | 098768 ...
Try this: ``` CREATE DEFINER=`admin`@`localhost` PROCEDURE `delete_update_rma`(IN selectedID INT, IN selectedRMAID INT) BEGIN UPDATE rma SET ref_status_id = CASE ref_status_id WHEN 19 THEN 0 WHEN 3 THEN 2 ELSE ref_status_id END WHERE id = selectedRMAID; DELETE FROM dropbox WHERE id = selectedID; E...
The case syntax is correct, however you cannot change a database field inside a case statement, you need to use an update statement for that. ``` UPDATE rma SET ref_status_id = 0 WHERE ref_status_id = 19 AND id = selectedrmaid; ``` You can only change local vars inside this kind of case statement. Your...
Case statement in stored procedure - Unknown System Variable
[ "", "mysql", "sql", "stored-procedures", "sql-update", "case-expression", "" ]
I have created a Scalar Functions, it was created successfully, but when I call the function using select statement, it says Invalid object name 'dbo.fun\_functional\_score'. my function: ``` ALTER function [dbo].[fun_functional_score] (@phy_id varchar(20)) returns varchar(50) as begin declare @level_initial in...
Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do ``` select dbo.fun_functional_score('01091400003') as [er] ```
You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list. ``` select dbo.fun_functional_score('01091400003') ```
how to call scalar function in sql server 2008
[ "", "sql", "sql-server", "" ]
I have the below code which is checking physical file counts to confirm that a previous process has generated the correct number of files (in different folders) ``` set NOCOUNT ON declare @DateOffset int set @DateOffset=0 -- Create a table variable to store user data DECLARE @myTable TABLE ( docID INT IDENTITY(...
You need to use `output` parameter with `sp_Executesql` like this ``` DECLARE @intCount int SET @statement = 'SELECT @numRecords = count(*) FROM BOCTEST.S653C36C.LIVEBOC_A.' + @docRef EXEC sp_Executesql @statement, N'@numRecords int output', @intCount OUTPUT PRINT @intCount ``` **Check here :** [Extract value ...
You could use `sp_executesql` with an `output` parameter. Remember to specify `output` twice: ``` set @statement= 'SELECT @rc = count(*) FROM BOCTEST.S653C36C.LIVEBOC_A.' + @docRef declare @rc int exec sp_executesql @statement, N'@rc int output', @rc output; ```
return a variable from a Dyanmic SQL query
[ "", "sql", "t-sql", "dynamic-sql", "remote-server", "" ]
So basically this would be the psuedo code, but I don't know how to do this in SQL, please help. ``` for each row in table1{ loop through each row in table 2 { if table1's row.column 1 = table2's row.column 2 for this row { set table1's row.col2 = table2's row.col2 } } } ``` Edit: ...
In SQL Server you can do something like: ``` UPDATE Table_1 SET Column_2 = t2.Column_2 FROM Table_1 AS t1 INNER JOIN Table_2 AS t2 ON t2.Column_1 = t1.Column_1 ``` or something like ``` UPDATE Table_1 SET Column_2 = ( SELECT t2.Column_2 FROM Table_2 AS t2 WHERE t2.Column_1 = Table_1.Column_1 ) ``` Of c...
The basics of it is: ``` UPDATE Table1 SET col2 = (select col2 FROM Table2 where Table2.column2 = Table1.column1) ``` But that may not do exactly what you need if there's not a 1-1 correspondence between rows in the two tables - and hence my current comment below your question: > What should happen if there are...
In SQL how do you update each row of the table by finding all rows that are equal for a column, then set another column equal to eachother
[ "", "mysql", "sql", "sql-server", "" ]
I need to write a SQL query which Displays the Name of the Courses which the students have an average greater than 55 in it TABLES : STUDENTS,GRADES,COURSES,DEPARTMENTS WHAT I DID : ``` SQL> SELECT COURSE_NAME 2 FROM COURSES 3 where 4 (select avg(grade) 5 from grades,courses 6 where 7 grades.co...
Your query returns every record or no records from `COURSES` based on whether the subquery returns more than 55 or less than 55, because the outer query is not related to the subquery in any way. You want to `JOIN` the tables, `GROUP BY` the course name, and use a `HAVING` clause to filter: ``` SELECT c.course_name F...
Try this query : ``` select COURSE_NAME, avg(grade) from grades,courses where grades.course_id=courses.course_id group by COURSE_NAME having avg(grade) > 55 ```
Bad results in SQL query
[ "", "sql", "" ]
I am trying to execute two select statements into a query that pumps data into a temp table. The first query will have 5 columns while the second query will have only one column. The first can be achieved by: ``` Select a.ID AS [a], b.ID AS [b], c.ID AS [c] INTO #testingTemp FROM .... ``` Now I have ...
Change it into a insert into statement. Otherwise you create the same temp table multiple times and that is not allowed. ``` Insert into #testingTemp (a,b,c) Select a.ID AS [a], b.ID AS [b], c.ID AS [c] FROM ```
The second query should just be a normal insert. ``` INSERT INTO #testingTemp (a, b, c) select etc. ``` dont forget to drop the temptable when you are done.
How to insert into an existing temp table in SQL Server
[ "", "sql", "sql-server", "temp-tables", "" ]
I have an oracle SQL query that selects the count of the company from different department. ``` select a.cust_nm, a.cust_acct_nb, a.cust_company_nb, to_char(b.case_receive_dt, 'YYYYMM'), count(*) from customer a...
Use a subquery in the `select` statement as follows: ``` select a.cust_nm, a.cust_acct_nb, a.cust_company_nb, to_char(b.case_receive_dt, 'YYYYMM'), count(*), (select count(*) from customer a1, case b1 where a1.cust_nb = b1.case_cust_nb ...
Can you try this? I cant test it since I have no data setup. ``` select a.cust_nm, a.cust_acct_nb, a.cust_company_nb, to_char(b.case_receive_dt, 'YYYYMM'), count(*) from customer a, case b where ...
Getting count of count from a Oracle SQL query
[ "", "sql", "oracle", "" ]
Recently I was working on MySql and Sql, where I found I can almost insert everything primitive type data but is it possible to store a jpeg/jpg/bmp/png (image)file in a database. If so then can you please write the code. Don't need to explain the whole thing just the key point. Thanks
Sorry for the late response. However, I found a way to convert the image to String and then store it in the mysql. This answer is just for those who are still looking for a easy solution: code: ``` Bitmap bm = BitmapFactory.decodeFile("/path/to/myImage.jpg"); ByteArrayOutputStream baos = new ByteArrayOutputSt...
**1** Perhaps convert the image to a `Byte Array` (if it's not `bmp`, then convert it), then store it in **MySql** as a Blob type, then when reading it, you can create a **Bitmap** through the code (I don't know what language you're using) with the **Byte Array** with what you read, or perhaps just get the code associa...
how to insert an image in mysql -android
[ "", "android", "mysql", "sql", "database", "image", "" ]
I have a query like this, ``` SELECT b.user_id,b.first_name, b.last_name, b.email_id, COUNT(DISTINCT a.file_id) AS sharedFiles FROM email_history a, users b WHERE a.email_receiver_id = b.user_id AND a.email_sender_id= 20 GROUP BY b.user_id,b.first_name, b.last_name, b.email_id UNION SELECT b.user_id,b.firs...
``` SELECT b.user_id,b.first_name, b.last_name, b.email_id, SUM(sharedFiles)as sharedFiles FROM( SELECT b.user_id,b.first_name, b.last_name, b.email_id, COUNT(DISTINCT a.file_id) AS sharedFiles FROM email_history a, users b WHERE a.email_receiver_id = b.user_id AND a.email_sender_id= 20 GROUP BY b.user_id,b.fir...
Using your query as a sub query allows for additional grouping and summartion. Look at the following query: ``` SELECT (b.user_id,b.first_name, b.last_name, b.email_id, SUM(b.sharedFiles) FROM ( SELECT b.user_id,b.first_name, b.last_name, b.email_id, COUNT(DISTINCT a.file_id) AS sharedFiles FROM email_histo...
how to combine these two results as one in mysql?
[ "", "mysql", "sql", "union", "" ]
I am trying to convert this SQL View to sort the month names in order. Any help would be appreciated: ``` SELECT DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets FROM dbo.TASKS WHERE (REQDATE >= '6/1/13') GROUP BY DATENAME(Month, REQDATE) ``` It currently displays the months out of order..
Try this. ``` SELECT MAX(DATENAME(Month, REQDATE)) AS Month, COUNT(WO_NUM) AS Tickets FROM dbo.TASKS WHERE (REQDATE >= '6/1/13') GROUP BY DATEPART(Month, REQDATE) ORDER BY DATEPART(Month, REQDATE) ASC ``` SQL Fiddle: <http://sqlfiddle.com/#!3/220be/4>
This will display the results with the months listed in calendar order. ``` SELECT DATENAME(Month, REQDATE) AS Month, COUNT(WO_NUM) AS Tickets FROM dbo.TASKS WHERE (REQDATE >= '6/1/13') GROUP BY DATENAME(Month, REQDATE), DATEPART(Month, REQDATE) ORDER BY DATEPART(Month, REQDATE) ASC ``` I added `DATEPAR...
SQL Query Month Name Sort
[ "", "sql", "sql-server", "" ]
I have table: ``` describe tests; +-----------+-----------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-----------+------+-----+-------------------+-----------------------------+ | id | int...
If you want the *last* five rows, then you need to order by the time column in *descending* order: ``` select avg(result) from (select result from tests where line_id = 4 order by test_time desc limit 5 ) t ```
the guy before submitted something link that for my it works ``` select avg( id ) from ( select id from rand limit 5) as id; ```
mysql average latest 5 rows
[ "", "mysql", "sql", "" ]
Sorry to bring this topic up again, I've come across several helpful existing posts that are very similar but stackoverflow won't let me post a comment/question on an existing thread because I'm so new (less than 50 points). Anyways, a lot of the running total posts are great for 1 group / running total only. As soon ...
You can do this using a correlated subquery: ``` select name, date, dollars, (select sum(dollars) from table t2 where t2.name = t.name and t2.date <= t.date ) as running from table t; ``` EDIT: If you have multiple rows on the same date, then you need to introduce another ...
You can use `OUTER APPLY`: ``` SELECT A.[NAME], A.[DATE], A.DOLLARS, SUM(B.[DOLLARS]) RUNNING FROM YourTable A OUTER APPLY (SELECT * FROM YourTable WHERE [NAME] = A.[NAME] AND [DATE] <= A.[DATE]) B GROUP BY A.[NAME], A.[DATE], A.DOLLARS ...
Running Total (pre 2012) for more than 1 group
[ "", "sql", "sql-server", "sql-server-2008", "" ]
What is the difference between implicit conversion and explicit conversion in SQL Server?
An explicit conversion occurs when you use the `CONVERT` or `CAST` keywords explicitly in your query. An implicit conversion arises when you have differing datatypes in an expression and SQL Server casts them automatically according to the rules of [datatype precedence](http://technet.microsoft.com/en-us/library/ms190...
**Implicit conversions** are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a `smallint` is compared to an `int`, the `smallint` is implicitly converted to int before the comparison proceeds. `GETDATE()` implicitly converts to date style 0. `SYSDATET...
Difference between Implicit Conversion and Explicit Conversion in SQL Server
[ "", "sql", "sql-server", "implicit-conversion", "" ]
I have a table that looks something like ``` ID Col1 Col2 Col3 Col4 1 3 5 3 3 ``` What I want to do is COUNT the number of `3`s in this particular row. I have tried the ``` select COUNT(*) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' -- but obviously I need WHERE Col1 = 3 OR Col2 = ...
Based on what OP asked, this can be done ``` select CASE WHEN Col1 = 3 then 1 ELSE 0 END + CASE WHEN Col2 = 3 then 1 ELSE 0 END + CASE WHEN Col3 = 3 then 1 ELSE 0 END + CASE WHEN Col4 = 3 then 1 ELSE 0 END From TableName ```
I don't really enjoy working with PIVOT so here a solution using APPLY. ``` SELECT T.id , Val , COUNT(*) FROM MyTable AS T CROSS APPLY ( VALUES (T.C1) , (T.C2) , (T.C3) , (T.C4) ) AS X(Val) GROUP BY T.Id, X.Val ORDER BY T.Id, X.val ```
COUNT the number of columns where a condition is true? SQL Server 2008 R2
[ "", "sql", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I need to get a comma separated list of ids as a field for a messy third party api :s This is a simplified version of what I am trying to achieve. ``` | id | name | |====|======| | 01 | greg | | 02 | paul | | 03 | greg | | 04 | greg | | 05 | paul | SELECT name, {some concentration function} AS ids FROM table GROUP BY...
A really old question, but as an update, you can use listagg() function | id | name | | --- | --- | | 01 | greg | | 02 | paul | | 03 | greg | | 04 | greg | | 05 | paul | SELECT name, listagg(id) AS ids FROM table GROUP BY name That will return the desire output: | name | ids | | --- | --- | | greg | 01, 03, 04 | | ...
You'll have to use [`OVER()`](https://my.vertica.com/docs/6.1.x/HTML/index.htm#13400.htm) with [`NVL()`](https://my.vertica.com/docs/6.1.x/HTML/index.htm#10435.htm) (you'll have to extend the concatenation for more than 10 instances per name): ``` CREATE TABLE t1 ( id int, name varchar(10) ); INSERT INTO t1 SELEC...
Concat GROUP BY in Vertica SQL
[ "", "sql", "vertica", "" ]
I have a line chart/graph that I need to include for all service outages we went through in the year. Currently, my SQL can pull data that includes any tickets creating in a ticketing system for these services. However, if no ticket was created for a service, the service will not show in the rows or the service will s...
How about this- Create a temp table having all service values as 100% for each month. After that, update the temp table with the real values based on your filter condition.
It would really help if you showed the query. However, somewhere along the way, you can solve your problem using `coalesce()`. Assuming the values are really numbers between 0 and 100: ``` select month, coalesce(service1, 100) as service1, coalesce(service2, 100) as service2, coalesce(service3, 100) as service3 ...
How to select Months for data without any data existing in SQL
[ "", "sql", "select", "common-table-expression", "" ]
I have spent quite some time dealing with the following: Imagine that you have **N** number of groups with multiple records each and every record has **unique** `starting` and `ending` points. In other words: ``` ID|GroupName|StartingPoint|EndingPoint|seq(row_number)|desired_seq __|_________|_____________|__________...
This is a `gaps-and-islands` problem with subgrouping. The trick is grouping by the difference between two ROW\_NUMBER() values, one partitioned and one unpartitioned. ``` WITH t AS ( SELECT GroupName, StartingPoint, EndingPoint, ROW_NUMBER() OVER(PARTITION BY GroupName ORDER BY StartingPoint) ...
Not sure, but maybe: ``` SELECT DISTINCT GroupName, MIN(StartingPoint) OVER (PARTITION BY GroupName ORDER BY Id), MAX(EndingPoint) OVER (PARTITION BY GroupName ORDER BY Id) FROM table1 ``` Because `partition` does not lead to the reduction of number of rows there will be originally duplicated entries, ...
Identifying the boundaries of N-groups
[ "", "sql", "sql-server", "sql-server-2008", "gaps-and-islands", "" ]
I have a query where I need to check a date between two dates using Oracle. Whenever I run the code I get an ORA-01843: not a valid month error. However whenever I remove either of the two parameters from the sql it works fine, but trying to use two date parameters throw an error. What am I missing? ``` String...
think you've got a problem with your parameter's order. If you don't bind parameters by name, they are bound by position (means the order in which you add parameters is taken). Just try to add : ``` cmd.BindByName = true; ```
You expect date formatted as `MM/DD/YYYY`, but it is not guaranteed that `ToShortDateString()` returns it in this format. A format specifiction is needed. But well, I do not even know what is the programming language you are using to provide further help...
2nd Date Parameter Throws ORA-01843: not a valid month error
[ "", "sql", "oracle", "datetime", "oraclecommand", "" ]
[**STRUCTURE TABLES AND ERROR WHEN EXECUTE QUERY ON SQLFIDDLE**](http://sqlfiddle.com/#!2/bd60dc/32) QUERY: ``` SELECT n.Type as Type, n.UserIdn as UserIdn, u.Username as Username, n.NewsIdn as NewsIdn, n.Header as Header, n.Text as Text, ...
Wrap it in a subquery ``` SELECT * FROM ( SELECT n.Type as Type, n.UserIdn as UserIdn, u.Username as Username, n.NewsIdn as NewsIdn, n.Header as Header, n.Text as Text, n.Tags as Tags, n.ImageLink as ImageLink, n.VideoLink as VideoLink, n.DateCreate as DateCreate, SUM(l.Typ...
You cant use aggregate fields like `sum()` in where clause, you shuld use `having`, the end of your query could be like: ``` GROUP BY n.id HAVING SumLikes > 20 ORDER by SumLikes DESC ``` ofcourse remove `SumLikes > 20` in your `where`. Check this out for more information: [MySQL Extensions to GROUP BY](http://dev.m...
how correctly execute query?
[ "", "mysql", "sql", "select", "group-by", "having", "" ]
Want to know which appropriate fields to use in review table. requirement for review table: ``` > review will be given by customer * review in points * review in description * review in videos (instead of text can upload review video in which it present review description) * comments on re...
as per my senior suggestion its need to be like this: **user\_reviews** ``` - id - restaurant_menu_item_id - restaurant_id - customer_id - review_title : title like wow / superb / or ... - review_points : from 1 - 10 - description : limit it to ... - review_video_id ...
`Review` Table Contains ``` 1. reviewId (INT, Primary key, Auto Increment) 2. restaurantId (INT, ForeignKey of restaurant table) 3. userId (INT, ForeignKey of user_master table) 4. menuItemId (INT, ForeignKey of menuItem table) 5. couponId (INT, ForeignKey of packs / coupons table) 6. title (VARCHAR) 7. commen...
want to design review table for restaurants
[ "", "mysql", "sql", "database", "database-design", "" ]
How to return all the characters from a string and count it in sql. if the string is "how are you" it should return char count ``` 2 h 1 o 2 w 1 a 1 r 1 e 1 y 1 u 1 ```
You can use this script. It will give you exactly what you need. This one counts just the letters in the string. ``` declare @c int declare @ch varchar(10) declare @str varchar(max) set @str = 'how are you' declare @letter int declare @i int set @i = 1 create table #tbl(ch varchar(10), cnt int) while (@i <= len(@...
This will return the result set you have requested. It does this by taking each letter and adding it to a new row within a temporary table and then querying the results to return the counts for each occurrence of the character. ``` DECLARE @individual CHAR(1); DECLARE @text NVARCHAR(200) SET @text = 'how are you'; I...
return separate character from a string
[ "", "sql", "sql-server-2008-r2", "" ]
I would need to reverse the word positions in a sentence or String. ``` For example : "Hello World! I Love StackOverflow", to be displayed as "StackOverflow Love I World! Hello". ``` Can it be done with a `SQL` ? The word length is no greater than `VARCHAR2(4000)` which is the maximum length support in a Oracle `VARC...
*Create a **Function**:* `REGEXP_SUBSTR('Your text here','[^ ]+', 1, ?)` will extract a word from the text using Space as a delimiter. Tt returns the original String itself on Exception! ``` CREATE OR REPLACE FUNCTION reverse_words (v_STRING IN VARCHAR2) RETURN VARCHAR2 IS L_TEMP_TEXT VARCHAR2(4000); L_FINAL_T...
XML-based version to avoid defining your own function; requires 11g for `listagg()`: ``` select listagg(word, ' ') within group (order by rn desc) as reversed from ( select word, rownum as rn from xmltable('for $i in ora:tokenize($STR, " ") return $i' passing 'Hello World! I Love StackOverflow' as str colu...
Reverse String Word by Word using SQL
[ "", "sql", "oracle", "plsql", "" ]
Is there any function similar to the MYSQL `BIT_COUNT` function in MSSQL? I want to create a very simple Hammingdistance function in MSSQL that i can use in my selects. Here is what i have for MYSQL: ``` CREATE FUNCTION `HAMMINGDISTANCE`(`hasha` BIGINT, `hashb` BIGINT) RETURNS int(11) DETERMINISTIC RETURN...
Why not just write your own bit\_count code in T-SQL? There's no need to use SQL CLR if all you need is to count the number of set bits in a bigint. Here is an example: ``` CREATE FUNCTION bit_count ( @pX bigint ) RETURNS int AS BEGIN DECLARE @lRet integer SET @lRet = 0 WHILE (@pX != 0) BEGIN SET ...
I just wrote a HAMMINGDISTANCE using the provided code by dcp and it seems to work. ``` CREATE FUNCTION [dbo].[HAMMINGDISTANCE](@hasha BIGINT, @hashb BIGINT) RETURNS int AS BEGIN DECLARE @pX BIGINT DECLARE @lRet integer SET @lRet = 0 SET @pX = @hasha ^ @hashb WHILE (@pX != 0) BEGIN SET @lRe...
MSSQL BIT_COUNT (Hammingdistance)
[ "", "mysql", "sql", "sql-server", "" ]
I have a Table Variable and when attempting to filter down the data I have a condition that must be met. User Story -- When HCPC\_CODE Contains LCS AND the Allowed\_AMT > 0 Then display these records What I am seeing it that I try parenthesis around the data, but It treats the Allowed\_AMT > 0 as if it is just another...
Your third query should work. Just change `LCS%` to `%LCS%`. This would handle `HCPC_CODE` that begins with `LCS`, ends with `LCS` or has `LCS` in the middle. Considering your `HCPC_CODE` could also be null, your query should look something like this - ``` select * from @billingEdit where (HCPC_CODE like '%LCS%' and A...
Unless I am missing something, it looks like just need to change the "NOT IN" to "LIKE" and add your wildcard to the beginning of LCS. Also, you don't need the parenthesis around the LSC. ``` select * from @billingEdit where (HCPC_CODE LIKE '%LCS%' AND ALLOWED_AMT > 0) OR HCPC_CODE NOT LIKE '%LCS%' ```
Sql Server is not combining the results , it is becoming mutually exclusive
[ "", "sql", "sql-server", "t-sql", "where-clause", "" ]
I have a requirement where we need to modify a column's default value in database table. The table is already an existing table in database and currently the default value of the column is NULL. Now if add a new default value to this column, If I am correct it updates all the existing NULLs of the column to new DEfault...
Your belief about what will happen is not correct. Setting a default value for a column will not affect the existing data in the table. I create a table with a column `col2` that has no default value ``` SQL> create table foo( 2 col1 number primary key, 3 col2 varchar2(10) 4 ); Table created. SQL> inse...
``` ALTER TABLE *table_name* MODIFY *column_name* DEFAULT *value*; ``` worked in Oracle e.g: ``` ALTER TABLE MY_TABLE MODIFY MY_COLUMN DEFAULT 1; ```
Alter table to modify default value of column
[ "", "sql", "oracle", "alter-table", "" ]
I had a sql query which brings me info about tablespaces and it's sizes. I'm using this query for an oracle database. **QUERY** ``` SELECT df.tablespace_name tablespace, (df.total_space_mb - fs.free_space_mb) kullanilan_alan, fs.free_...
you can always use a "constant" value in a select (and so in an insert... select) so this is perfectly valid : ``` insert into table2 (id, f1, f2, f3, f4, fdate, farbitrary) select id, field1, field2, field3, field4, SYSDATE, 'I put what I want here') from table1 ``` In this case, id, field1, field2, field3, field4 ...
You can get todays date by `SYSDATE` and append to select list for inserting in new table. ``` INSERT INTO newTable(colA,colB,colC,colD,DateColumn) SELECT df.tablespace_name TABLESPACE, (df.total_space_mb - fs.free_space_mb) KULLANILAN_ALAN, fs.free_space_mb BOS_ALAN, ...
Inserting columns to another table
[ "", "sql", "oracle", "" ]
I need to write a query to pull out the records as below. ``` membership_id, person_id, first_name last_name ``` who joined or called yesterday and the members who didn't join will have only person\_id But the below query is pulling out all the records from the table. ``` SELECT dbo.pn_membership.membership_id, ...
Try this version. Your write in your question "who joined or called yesterday" but your query does "who joined or called in the last 24 hours" which is kind of different. Also, as Sparky noted you had this lack of WHERE clause problem. My version does "who joined or called yesterday". ``` SELECT dbo.pn_member...
Try this: ``` SELECT dbo.pn_membership.membership_id, dbo.pn.person_id, dbo.pn.first_name, dbo.pn.surname, dbo.pn.create_datetime FROM dbo.pn LEFT OUTER JOIN dbo.pn_membership ON dbo.pn.person_id=dbo.pn_membership.person_id WHERE dbo.pn.create_datetime >=getdate()-1 ``` Your query says... ...
T-SQL programming
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
I have a table like this ``` | ID | DATE | DURATION | STATUS | DUPLICATION | |----|------------------- -------|----------|------------|-------------| | 1 | January, 08 2014 19:30:12 | 00:00:03 | Aborted | (null) | | 2 | January, 08 2014 19:30:12 | 00:00:06 | Dropped | (null) ...
One option is to use this: ``` UPDATE `calldata` SET `date` = DATE_SUB(`date`, INTERVAL 7 DAY) WHERE DATE(`date`) = '2014-01-08' ``` Fiddle: <http://sqlfiddle.com/#!2/28d71/1> For better performance use the following query because index (if any) can be used by MySQL as `DATE()` is not on the left side of comparison ...
Try this: ``` UPDATE calldata SET date = CONCAT('2014-01-01 ', TIME(date)) WHERE DATE(date) = '2014-01-08' ``` Check the [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!2/53279/1) **OUTPUT** ``` | ID | DATE | DURATION | STATUS | DUPLICATION | |----|------------------...
How can I update date of datetime field with mysql only?
[ "", "mysql", "sql", "date", "datetime", "sql-update", "" ]
How would I calculate the last weekday of the current month given a date using SQL? I was able to get the last day of current month, but not sure how to do the last weekday programmatically. I don't want to generate a calendar look-up table. Here's the last day of month code i'm currently using: ``` declare @date d...
I know it is not the most intuitive or effective or easy way of doing it. But here is my solution to find the last **Weekday** of the month... ``` declare @date datetime, @lastDate datetime, @lastWeekDay datetime set @date='05/4/2014';--'1/1/2014' set @lastDate = (SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date)...
Quite a neat solution: ``` declare @date1 as date = '20130401' declare @date as date= eomonth(@date1,0) set @date = (select case when datepart(dw,@date) = 1 then dateadd(day,-2,@date) --when day is a sunday subtract 2 day to friday when datepart(dw,@date) = 7 then dateadd(day,-1,@date) --when day is a saturday...
How to find last weekday of current month using SQL
[ "", "sql", "sql-server-2008", "" ]
I wonder how I could select every user who met the first and second lowest values of a result table? Table Test ``` NAME VALUE John 8 Marie 8 Luis 10 Carlos 10 Leo 13 Max 14 ``` So the result in this case would be ``` NAME VALUE John 8 Marie 8 Luis 10 Carlos 10 ``` Thanks a lot! BT...
Try this: ``` SELECT * FROM Test WHERE `value` IN ( SELECT * FROM ( SELECT DISTINCT `value` FROM Test ORDER BY `value` LIMIT 0,2 ) AS t ) ```
Try this: ``` SELECT t.* FROM Test t INNER JOIN (SELECT DISTINCT t.value FROM Test t ORDER BY t.value LIMIT 2 ) A ON t.value = A.value; ``` Check this [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!2/9aafb/1) **OUTPUT** ``` | NAME | VALUE | |--------|-------| | John | 8 | | Marie | 8 | | Lu...
mysql select all rows meeting the first and second lowest values?
[ "", "mysql", "sql", "select", "sql-order-by", "limit", "" ]
As I was learning SQL statements I encountered one example (regarding the demo [SCOTT](http://www.orafaq.com/wiki/SCOTT "SCOTT") database), I have no idea how to solve. > In which department(s) are all salgrades present? My most promising approach is to **group all salgrades and departments** in the joined tables **e...
I found an even easier solution now: ``` SELECT d.dname FROM emp e INNER JOIN dept d ON(e.deptno = d.deptno) INNER JOIN salgrade s ON(e.sal BETWEEN s.losal AND s.hisal) GROUP BY d.dname HAVING COUNT(DISTINCT s.grade) = (SELECT COUNT(*) FROM salgrade); ```
Minor change from your version, by removing the grouping inside, and this version, first generates, `salgrade` and `department` of all employees, and then doing a grouping outside, counting distinct salary grades. ``` SELECT Department_ID FROM ( SELECT s.grade AS Salgrade, d.dname AS Department_ID FROM emp e...
"Double Group By" in Oracle SQL?
[ "", "sql", "oracle", "oracle-apex", "" ]
I have a query that I would like to run but is not returning the expected results. So my tables are like this ``` users (has two columns) user_id,name users_archive (has the same two columns) user_id,name ``` I want to basically run a query that lists user\_id from the respective table where the username matches w...
You do not want a JOIN, you want a UNION. Look ``` SELECT users.user_id, 'users' FROM users WHERE users.name='MikeBOSS' UNION SELECT users_archive.user_id, 'archive' FROM users_archive WHERE users_archive.name='MikeBOSS'; ```
A join condition normally links two tables. Yours does not: ``` ON users_archive.name='MikeBOSS' ``` A join condition that does link the two tables might look something like: ``` ON users.name = users_archive.name ``` If you wonder about the number of rows this returns, check each table individually. Is there even ...
MySQL query from 2 tables confusion
[ "", "mysql", "sql", "join", "multiple-tables", "" ]