Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to write a query which calculates the difference between the value rows as a new column called difference when the datetime field is in ascending order. For example, 2016-03-02 should be 102340624 - 102269208 ``` select datetime, tagname, value from runtime.dbo.AnalogHistory where datetime between '201603...
You can use the lag function to get the previous rows value. ``` Select datetime, tagname, value, value- coalesce(lag(value) over(partition by tagname order by datetime),0) [difference] from runtime.dbo.AnalogHistory where datetime between '20160301 00:00' and '20160401 00:00' and TagName = 'EWS_A3_PQM.3P_REAL_U' and ...
For sql server versions 2005 or higher but before 2012 (where you don't have lag and lead functions) ``` ;with cte as ( select datetime, tagname, value from runtime.dbo.AnalogHistory where datetime between '20160301 00:00' and '20160401 00:00' and TagName = 'EWS_A3_PQM.3P_REAL_U' and wwResolution ...
Difference between two rows with date in ascending order
[ "", "sql", "sql-server", "t-sql", "" ]
I'm working on JOIN statements (implicit) and I've set up the code to join without much of a hitch, and when the code runs I get quite a few duplicates per person. I was wondering what kind of statement I should use to only show one of each person? **Select Statement** ``` SELECT CONCAT(customers.customer_first_name,...
You have a Descartes product, not a `join`. You could use the `distinct` keyword or you could do a `group by`, but it seems you really need a `join` instead. I am writing something like that for you, but since I do not know your `table` structure, I will be guessing the columns: ``` SELECT CONCAT(customers.customer_fi...
If you don't want to use the `JOIN` keyword you can add the key columns on whick the tables are related to the `WHERE` clause like this: ``` SELECT CONCAT(customers.customer_first_name, ' ', customers.customer_last_name) as 'Customer', orders.order_date as 'Order Date', customers.customer_zip as 'Zipcode' FROM...
MySQL: Implicit Join with conditions: What kind of statement would I need for duplicate removal?
[ "", "mysql", "sql", "join", "duplicates", "implicit", "" ]
How can I write a SQL query to do below function. I have a column values with underscore `"_"`. I want to split these values by underscore `"_"` to create two new columns named pID, nID and keep original ID column intact. ``` Input example Output example ID | | pID | nID | 1234_591856 ...
If you want to add two new columns to your table you could use ALTER TABLE: ``` alter table mytable add column pid varchar(100), add column nid varchar(100); ``` then you can update the value of the newly created columns: ``` update mytable set pid=substring_index(id, '_', 1), nid=substring_index(id, '_', -1) wh...
You can get by below query- ``` SELECT SUBSTRING_INDEX(mycol,'_',1), SUBSTRING_INDEX(mycol,'_',-1) FROM mytable; ```
How can I split a value into multiple columns in mySQL
[ "", "mysql", "sql", "" ]
Using Rails. I have the following code: ``` class TypeOfBlock < ActiveRecord::Base has_and_belongs_to_many :patients end class Patient < ActiveRecord::Base has_and_belongs_to_many :type_of_blocks, dependent: :destroy end ``` With these sets of tables: ``` ╔══════════════╗ β•‘type_of_blocksβ•‘ ╠══════╦═══════╣ β•‘ id ...
The only solution that comes to my mind is to use raw SQL and leverage the **[`group_concat` function](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat)**, as shown [here](https://stackoverflow.com/a/11640438/1544012). The SQL needed is this: ``` SELECT combination, count(*) as...
The answer provided by [BoraMa](https://stackoverflow.com/a/36318432/5070879) is correct. I just want to address: > ***As you can see, the query does not return zero counts,*** this has to be > solved in ruby code (perhaps initialize a hash with all combinations > with zeroes and then merge with the query counts). It...
Rails complex query to count unique records based on truth table
[ "", "mysql", "sql", "ruby-on-rails", "" ]
This is my table ``` date count of subscription per date ---- ---------------------------- 21-03-2016 10 22-03-2016 30 23-03-2016 40 ``` Please need your help, I need to get the result like below table, summation second row with first row, same thing for another rows: ``` date count of su...
``` SELECT t.date, ( SELECT SUM(numsubs) FROM mytable t2 WHERE t2.date <= t.date ) AS cnt FROM mytable t ```
You can do a cumulative sum using the ANSI standard analytic `SUM()` function: ``` select date, sum(numsubs) over (order by date) as cume_numsubs from t; ```
SQL query to calculate sum of row with previous row
[ "", "sql", "oracle", "" ]
I'm curious about something in a SQL Server database. My current query pulls data about my employer's items for sale. It finds information for just under 105,000 items, which is correct. However, it returns over 155,000 rows, because each item has other things related to it. Right now, I run that data through a loop in...
Since you only want the first 7 attributes and you want to keep all of the logic in the SQL query, you're probably looking at using row\_number. Subqueries will do the job directly with multiple joins, and the performance will probably be pretty good since you're only joining so many times. ``` select i.item_id, a...
Here is @WCWedin's answer modified to use a CTE. ``` WITH attrib_rn as ( select *, row_number() over(partition by item_id order by name, attribute_id) as row_number from attributes ) select i.item_id, attr1.name as attribute1_name, attr1.value as attribute1_value, ... attr7.name as attribute7_name, att...
Flatten multiple query results with same ID to single row?
[ "", "sql", "sql-server", "" ]
I am trying to find out an ideal way to automatically copy new records from one database to another. the databases have different structure! I achieved it by writing VBS scripts which copy the data from one to another and triggered the scripts from another application which passes arguments to the script. But I faced i...
You can use [CDC](https://msdn.microsoft.com/en-us/library/bb895315.aspx) to do this activity. Create a SSIS package using CDC and run that package periodically through SQL Server Agent Job. CDC will store all the changes of that table and will do all those changes to the destination table when you run the package. Ple...
The word periodically in your question suggests that you should go for Jobs. You can schedule jobs in SQL Server using Sql Server agent and assign a period. The job will run your script as per assigned frequency.
SQL: Automatically copy records from one database to another database
[ "", "sql", "database", "sql-server-2012", "" ]
I have a select statement I am trying to make for a report. I have it pulling data and everything I need but I noticed that since I have to use the group by it is dropping off rows that do not exist in a table. How can I stop this or make it work. ``` SELECT Sum(CASE WHEN direction = 'I' THEN 1 ELSE 0 END) InBound, ...
``` SELECT u.FullName, SUM(CASE WHEN Direction = 'I' THEN 1 ELSE 0 END) AS InBound, SUM(CASE WHEN Direction = 'O' THEN 1 ELSE 0 END) OutBound, SUM(CASE WHEN Direction = 'I' THEN p.Duration ELSE 0 END) InBoundTime, SUM(CASE WHEN Direction = 'O' THEN p.Duration ELSE 0 END) OutBoundTime, CASE WHEN EXIS...
If you have a `brokers` table then you can use it for your `left join` ``` SELECT b.broker_id, .... FROM brokers b LEFT JOIN .... ALL YOUR OTHER TABLES .... GROUP BY b.broker_id, .... ``` If your brokers has duplicate names then use ``` SELECT b.broker_id, .... FROM (SELECT DISTINCT broker_id FROM brokers) b L...
Case sql not working
[ "", "sql", "group-by", "case", "exists", "" ]
I have a table called "`Accounts`" with a `composite primary key` consisting of 2 columns: `Account_key` and `Account_Start_date` both with the datatype `int` and another non key column named `Accountnumber(bigint).` Account\_key should have one or many `Accountnumber(bigint)` and not the other way around meaning **1 ...
If this were an OLTP table the solution would be to properly normalize the data into two tables, but this is a DW table so it makes sense to have it all in one table. In this case, you should add a `FOR` / `AFTER` Trigger `ON INSERT, UPDATE` that does a query against the `inserted` pseudo-table. The query can be a sim...
If I understand you correctly, you want: 1. Any given AccountNumber can only be related to one AccountKey 2. Any given AccountKey can be related to multiple AccountNumbers If this is correct, you can achieve this with a `CHECK CONSTRAINT` that calls a UDF. EDIT: Psuedo-logic for the CHECK CONSTRAINT could be: ``` ...
Enforcing 1:1 and 1:Many cardinality in denormalized warehouse table with composite Primary Key
[ "", "sql", "sql-server", "database", "t-sql", "data-warehouse", "" ]
I'm trying to figure out away to split the first 100,000 records from a table that has 1 million+ records into 5 (five) 20,000 records chunks to go into a file? Maybe some SQL that will get the min and max rowid or primary id for each 5 chunks of 20,000 records, so I can put the min and max value into a variable and pa...
If you just want to assign values 1-5 to basically equal sized groups, then use `ntile()`: ``` select t.*, ntile(5) over (order by NULL) as num from (select t.* from t where rownum <= 100000 ) t; ``` If you want to insert into 5 different tables, then use `insert all`: ``` insert all when num = ...
A bit harsh down voting another fair question. Anyway, NTILE is new to me, so I wouldn't have discovered that were it not for your question. My way of doing this , the old school way, would have been to MOD the rownum to get the group number, e.g. ``` select t.*, mod(rn,5) as num from (select t.*, rownnum rn f...
SQL: How would you split a 100,000 records from a Oracle table into 5 chunks?
[ "", "sql", "database", "oracle", "max", "min", "" ]
I have query like this ``` SELECT a.STOCK_ITEM_NO, a.STOCK_BEG_QTY, b.DOUT_QTY_ISSUE FROM INV_STOCK AS a LEFT OUTER JOIN INV_DOUT AS b ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO WHERE a.STOCK_ITEM_NO = 'ABC01' AND b.CREATEDDATE > '01-MAR-2016' AND b.CREATEDDATE < '01-APR-2016' ``` There is `null` value ...
Put your date WHERE statement inside the LEFT JOIN. ``` SELECT a.STOCK_ITEM_NO,a.STOCK_BEG_QTY, b.DOUT_QTY_ISSUE FROM INV_STOCK a LEFT OUTER JOIN INV_DOUT b ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO AND b.CREATEDDATE BETWEEN '01-MAR-2016' AND '01-APR-2016' WHERE a.STOCK_ITEM_NO = 'ABC01' ```
``` SELECT a.STOCK_ITEM_NO ,a.STOCK_BEG_QTY ,ISNULL(b.DOUT_QTY_ISSUE,0) as DOUT_QTY_ISSUE FROM INV_STOCK AS a LEFT JOIN INV_DOUT AS b ON a.STOCK_ITEM_NO = b.DOUT_ITEM_NO AND b.CREATEDDATE > '01-MAR-2016' AND b.CREATEDDATE < '01-APR-2016' WHERE a.STOCK_ITEM_NO = 'ABC01' ``` Put the where c...
SQL Left Join with null result return 0
[ "", "sql", "sql-server", "" ]
I want to convert the decimal number 3562.45 to 356245, either as an `int` or a `varchar`. I am using `cast(3562.45 as int)`, but it only returns 3562. How do I do it?
Or you can replace the decimal point. ``` select cast(replace('3562.45', '.','') as integer) ``` This way, it doesn't matter how many decimal places you have.
How about the obvious: ``` CAST(3562.45*100 as INTEGER) ```
Convert decimal number to INT SQL
[ "", "sql", "sql-server", "casting", "decimal", "number-formatting", "" ]
I'm having an issue with SQL joins in a query that is designed to query the Post table having been joined to the comment, click and vote table and return stats about each posts activity. My query below is what I've been using. ``` SELECT p.PostID, p.Title, CASE WHEN COUNT(cm.CommentID) IS NULL T...
The result that is being returned is expected because the query is producing a Cartesian (or semi-Cartesian) product. The query is basically telling MySQL to perform "cross join" operations on the rows returned from `comment`, `click` and `vote`. Each row returned from `comment` (for a given postid) gets matched to ea...
You probably want something like this: ``` SELECT p.PostID, p.Title, (SELECT COUNT(*) FROM Comment cm WHERE cm.PostID = p.PostID) AS CommentCount, (SELECT COUNT(*) FROM Click cl WHERE p.PostID = cl.PostID) AS ClickCount , (SELECT SUM(vt.Value) FROM Vote vt WHERE p.PostID = vt.PostID) A...
SQL query returns same value in each column
[ "", "sql", "sql-server", "left-join", "" ]
I have three tables. One consists of customers, one consists of products they have purchased and the last one of the returns they have done: Table customer ``` CustID, Name 1, Tom 2, Lisa 3, Fred ``` Table product ``` CustID, Item 1, Toaster 1, Breadbox 2, Toaster 3, Toas...
How about ``` SELECT * FROM Customer LEFT JOIN Product ON Customer.CustID=Product.CustID WHERE Item = 'Toaster' AND Customer.CustID NOT IN ( Select CustID FROM Product Where Item = 'Breadbox' ) AND (SELECT COUNT(*) FROM Returns WHERE Customer.CustId = Returns.CustID) <= 1 ```
The filter condition goes in the `ON` clause for all but the first table (in a series of `LEFT JOIN`: ``` SELECT * FROM Customer c LEFT JOIN Product p ON c.CustID = p.CustID AND p.Item = 'Toaster' LEFT JOIN Returns r ON c.CustID = r.CustID WHERE c.CustID NOT IN (Select p.CustID FROM Product p Where...
Filter on second left join - SQL
[ "", "mysql", "sql", "" ]
I have a database with songs. Every song have an unique id. How I can generate a random unique value for every id in database? Example: ``` id | song name 1 | song1 2 | song2 3 | song3 ``` After shuffle ``` id | song name 45 | song1 96 | song2 10 | song3 ``` Any idea?
Use a combination of `FLOOR` and `RAND()` to get what you want. If there are 1000 songs in your db. ``` SELECT FLOOR(RAND() * (1 - 1000 + 1)) + 1 AS ID, "song name" FROM yourtable ``` If there are 7000 songs in your db. ``` SELECT FLOOR(RAND() * (1 - 7000 + 1)) + 1 AS ID, "song name" FROM yourtable ``` Update.. `...
Does the ID have to be an *integer*? If not you could think about using *GUIDS* . If this is a possibility for you, then you get further information for migrating your table here: [Generate GUID in MySQL for existing Data?](https://stackoverflow.com/questions/6280789/generate-guid-in-mysql-for-existing-data)
Shuffle database id
[ "", "mysql", "sql", "random", "" ]
I'm trying to parse a logging table in PostgreSQL **9.5**. Let's imagine I'm logging SMS sent from all the phones belonging to my company. For each record I have a timestamp and the phone ID. I want to display how many SMS are sent by week but only for the phones that send SMS each week of the year. My table is as f...
Your concept of year seems very fuzzy. Let me instead assume that you mean for a period of time over the range of your data. ``` with w as ( select date_trunc('week', event_date) as wk, phone_id, count(*) as cnt from messages group by 1, 2 ), ww as ( select w.*, min(wk) o...
Below assumes that your table represents a full year. You didn't specify that. To find all phones that send SMSs every week, you can do something like ``` select phone_id, count(distinct extract(week from event_date)) as cnt from table having cnt >= 51 ``` Note, I use 51, but the notion of a week in a year is a bit ...
How to display rows happening every week of a year?
[ "", "sql", "postgresql", "timestamp", "aggregate", "" ]
* SQL Server 2008 R2 * A table with auto-increment key * Many different threads have to batch insert rows in the table. I would like to know how (if even it is possible) to insert the rows in a way that I'm absolutely sure that the keys of one thread's inserted rows will get sequential numbers. For example if 2 threa...
I was curious enough to test. On my virtual machine with SQL Server 2014 Express the answer is: --- Generated `IDENTITY` values are **not** guaranteed to be sequential when multiple threads insert values. Even if it is a single `INSERT` statement that inserts several rows at once. (Under default transaction isolation...
use transactions. The transaction will lock the table until you will commit so no other transaction will start until the previous is ended, so the identity values are safe
Sequential numbers for many rows inserted with auto-increment key
[ "", "sql", "sql-server", "sql-server-2008-r2", "auto-increment", "" ]
I'm working on project where I have to combine records from two different tables and display them on the screen based on the parameters. My first table contain time slot records. Here is example of my SLOT\_TABLE: ``` ID Event_ID Time_Slots 1 150 7:00 AM - 7:15 AM 2 150 7:15 AM - 7:30 AM 3 ...
Try this. You need to edit line 8 with the user ID you are after and line 9 with the event ID you are after. ``` select a.id ,a.event_id ,case when b.user_id is not null then 'User_ID(' + b.user_id + ')' else a.time_slots end as time_slots from slot_table a left join registration_table b on a.event_id = b.event_id...
When you use WHERE you limit the final result, in your case you left outer join and then you select only the items with user. You need to use the ON clause of the LEFT JOIN in order to selectively join, while keeping the original records from the first table. Maybe like this: ``` Select s.Time_Slots, r.User_ID From...
How to join two tables and get correct records?
[ "", "sql", "sql-server", "join", "left-join", "" ]
I have a number of tables, around four, that I wish to join together. To make my code cleaner and readable (to me), I wish to join all at once and then filter at the end: ``` SELECT f1, f2, ..., fn FROM t1 INNER JOIN t2 ON t1.field = t2.field INNER JOIN t3 ON t2.field = t3.field INNER JOIN t4 ON t3.fie...
The query optimizer will always attempt to take care of finding the most optimal plan from your SQL. You should concentrate more on writing readable, maintainable code and then by analyzing the execution plan find the inefficient parts of your query (and more likely) the inefficient parts of your database and indexing...
Your first approach will always be better as the SQL engine will evaluate where conditions first and then perform joins. So while evaluating where clause, it will filter records if conditions are available. ``` SELECT f1, f2, ..., fn FROM t1 INNER JOIN t2 ON t1.field = t2.field INNER JOIN t3 ON t2.field = t3.fiel...
Joining multiple tables: where to filter efficiently
[ "", "sql", "sql-server", "postgresql", "" ]
I am having a table consists of to datetime columns "StartTime" and "CompleteTime". Initially completeTime column will be NULL untill the process is completed. And now my requirement is to display hours and minutes as shown Below **Output:** Ex: 2:01 Hr (This Means "2" represents hours and "01" represents minutes) **...
Try this ``` DECLARE @STARTDATE DATETIME = '2016-03-31 04:59:11.253' DECLARE @ENDDATE DATETIME = GETUTCDATE() SELECT CONVERT(VARCHAR(10),DATEDIFF(MINUTE, @STARTDATE, @ENDDATE)/60)+':'+CONVERT(VARCHAR(10),DATEDIFF(MINUTE, @STARTDATE, @ENDDATE)%60)+' hr' AS DIFF ``` Result: ``` Diff 0:52 hr ``` Diff more than 24 hou...
try this (MS SQL query) - ``` Declare @StartDate dateTime = '2016-03-31 04:59:11.253' Declare @EndDate dateTime = GETUTCDATE() SELECT CONVERT(varchar(5), DATEADD(minute, DATEDIFF(minute, @StartDate, @EndDate), 0), 114) + ' hr' ``` Result - 00:47 hr
How to display Hours and Minutes between two dates
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have mySQL table and have column which have null and not null data. While running query and visibly i can see that BLOCKER column have null values. ``` mysql> select count(1), BLOCKER from mysql.PRSSTATE group by BLOCKER; +----------+----------------+ | count(1) | BLOCKER | +----------+----------------+ | ...
`BLOCKER` may be has zero length: ``` select count(1) from mysql.PRSSTATE where (BLOCKER is NULL or BLOCKER = ""); ```
The problem here is that you incorrectly assume that BLOCKER is NULL. In fact you are storing empty strings ("") and not a NULL value. You should modify your query to match both NULL and "" values: ``` select count(1) from mysql.PRSSTATE where BLOCKER IS NULL OR BLOCKER = ""; ``` Alternatively modify your script (or ...
MySQL column have null value but "is null" is not working
[ "", "mysql", "sql", "" ]
I have a query that is supposed to return a list of customers with the most popular product type for each customer. I have have a query that sums up each product purchased in all given product types and lists them in descending order per customer ``` SELECT c.customer_name as cname, ptr.product_type as pop_gen, sum(od...
Classic `greatest-n-per-group`. One possible solution is to use `ROW_NUMBER()`: ``` WITH CTE AS ( SELECT c.customer_name as cname, ptr.product_type as pop_gen, sum(od.quantity) as li ,ROW_NUMBER() OVER(PARTITION BY c.customer_name ORDER BY sum(od.quantity) DESC) AS rn FROM product_typ...
In Postgres, you can just use `distinct on`: ``` SELECT DISTINCT ON (c.customer_name) c.customer_name as cname, ptr.product_type as pop_gen, sum(od.quantity) as li FROM product_type_ref as ptr INNER JOIN product as p on p.product_type_ref_id = ptr.product_type_ref_id INNER JOIN order_detail as od on od...
Postgresql returning the most popular genre of product per customer
[ "", "sql", "postgresql", "" ]
I have problems with the following SQL Query: ``` SELECT job FROM (SELECT job, COUNT(*) AS cnt FROM Employee GROUP BY job) WHERE cnt=1 ``` As Result it should only shows all jobs where cnt (count of jobs) equals 1. When I test the select query above on Fiddle, I get following error : ``` Incorrect syntax near t...
No need to increase complexity by using sub-query when it is not require ``` SELECT job, count(job) FROM Employee GROUP BY job having count(job)=1; ```
You need to provide alias name to the nested query ``` SELECT A.job FROM (SELECT job, COUNT(*) AS cnt FROM Employee GROUP BY job)A WHERE A.cnt=1 ```
Nested SQL Query
[ "", "mysql", "sql", "nested", "" ]
So, I don't really understand the purpose of using an *implicit join* in SQL. In my opinion, it makes a join more difficult to spot in the code, and I'm wondering this: Is there a greater purpose for actually wanting to do this besides the simplicity of it?
Fundamentally there is no difference between the implicit join and the explicit `JOIN .. ON ..`. Execution plans are the same. I prefer the explicit notation as it makes it easier to read and debug. Moreover, in the explicit notation you define the *relationship* between the tables in the `ON` clause and the *search c...
[Explicit vs implicit SQL joins](https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins) When you join several tables no matter how the join condition written, anyway optimizer will choose execution plan it consider the best. As for me: 1) Implicit join syntax is more concise. 2) It easier to generat...
What's the purpose of an IMPLICIT JOIN in SQL?
[ "", "mysql", "sql", "join", "implicit", "" ]
I have a table with power outage information, which looks like this, ``` KEY OUTAGE TIME POWER LINE ID 1 1/1 2:30 pm 75 2 1/5 4:00 pm 247 3 1/5 6:00 pm 247 4 1/3 8:00 am 11 ``` KEY is just the primary key of the table. Outage time tells us when the outage occurred, and ...
I'm solving the problem using SQL Server so `#` means temp table. Assuming below tables and data ``` create table #outage ([key] int, outage_time datetime, power_line int) insert into #outage values (1, '2015/1/1 2:30 pm', 75), (2, '2015/1/5 4:00 pm', 247), (3, '2015/1/5 6:00 pm', 247), ...
Try this: ``` SELECT power_outage.key, meters.event_id, power_outage.power_line_id FROM power_outage JOIN meter_info meters ON power_outage.power_line_id = meters.power_line_id AND meters.event_timestamp < power_outage.outage_time WHERE meters.event_timestamp > (SELECT MAX(lpo.event_timestamp...
Finding a set based solution instead of looping through each row in SQL
[ "", "sql", "oracle", "" ]
I have 2 relationships: 1. Agents(many)-to-Properties(many) relationship (with a pivot table). 2. Properties(one)-to-Images(many) relationship (no pivot table). So an Agent can have 10 Properties, and each Property will have 10 Images; therefore, Agent has 100 Images. (I do not want to create a relationship between t...
You can use hasManyThrough <https://laravel.com/docs/5.1/eloquent-relationships#has-many-through> In your Agent model: ``` public function images() { return $this->hasManyThrough('App\Images', 'App\Properties'); } ``` Then you can use ``` $agent->images()->get(); ```
So, how about two queries like: ``` <?php $agent = new Agent(); $image = new Image(); $propertyIds = $agent->properties()->lists('id'); $images = $image->newQuery()->whereIn('property_id', $propertyIds)->get(); ```
How to get items from many to many relationships' one to many relationship in Laravel?
[ "", "sql", "database", "laravel", "orm", "relationship", "" ]
i have table storing product price information, the table looks similar to, (no is the primary key) ``` no name price date 1 paper 1.99 3-23 2 paper 2.99 5-25 3 paper 1.99 5-29 4 orange 4.56 4-23 5 apple 3.43 3-11 ``` right now I want to select all the rows where th...
``` SELECT * FROM product_price_info WHERE name IN (SELECT name FROM product_price_info GROUP BY name HAVING COUNT(*) > 1) ```
Try this: ``` SELECT no, name, price, "date" FROM ( SELECT no, name, price, "date", COUNT(*) OVER (PARTITION BY name) AS cnt FROM product_price_info ) AS t WHERE t.cnt > 1 ``` You can use the window version of `COUNT` to get the population of each `name` partition. Then, in an outer query, filter out `n...
Postgres: select all row with count of a field greater than 1
[ "", "sql", "postgresql", "" ]
I have a table like this. ``` |DATE |VOUCHER_NO|CURRENCY|AMOUNT|DESCRIPTION|JOURNAL_TYPE|COA_NO | |03/30/2016|0000000001|USD |2000 |ABCD |CREDIT |150001 | |03/30/2016|0000000001|USD |2000 |ABCD |DEBIT |150001 | |03/30/2016|0000000002|USD |1500 |ABCD |CREDIT |15...
You can `ORDER BY` a *group sum* first, like this ``` ORDER BY MAX(AMOUNT) OVER (PARTITION BY VOUCHER_NO) DESC, -- voucher with highest amount first VOUCHER_NO, -- all rows of that voucher CASE WHEN JOURNAL_TYPE = 'CREDIT' THEN 0 ELSE 1 END, -- credit first AMOUNT DESC ```
This should do the trick: ``` with your_table as (select to_date('30/03/2016', 'dd/mm/yyyy') dt, 1 voucher_no, 'USD' currency, 2000 amount, 'ABCD' description, 'Credit' journal_type, 150001 coa_no from dual union all select to_date('30/03/2016', 'dd/mm/yyyy') dt, 1 voucher_no, 'USD' currency, 2000 ...
ORACLE - Custom ORDER BY to order pairs of data rows
[ "", "sql", "oracle", "" ]
I have the following query that I'm trying to join two tables matching their ID so I can get the duplicated values in "c.code". I've tried a lot of queries but nothing works. I have a 500k rows in my database and with this query I only get 5k back, which is not right. Im positive it's at least 200K. I also tried to use...
``` with data as ( select c.code, c.name as SCT_Name, t.name as SYNONYM_Name from database.Terms as t inner join database.dbo.Concepts as c on c.ConceptId = t.ConceptId where t.TermTypeCode = 'SYNONYM' and t.ConceptTypeCode = 'NAME_Code' and c.retired = '0' ) select * ...
If you want just duplicates of c.code, your Group By is wrong (and so is your Having clause). Try this: ``` SELECT c.code FROM database.Terms as t join database.dbo.Concepts as c on c.ConceptId = t.ConceptId where t.TermTypeCode = 'SYNONYM' and t.ConceptTypeCode = 'NAME_Code' and c.retired = '0' Group by c.code...
Selecting ONLY Duplicates from a joined tables query
[ "", "sql", "sql-server", "group-by", "duplicates", "large-data", "" ]
I need to get the count of Male and Female users that did not place any order for a product. The result should show all the products and the number of male or female users that did not place any order. I want the query results to look like this: ``` productid | productName | No_MaleUsers | No_FemaleUsers| ------...
This is a complicated query. One approach is to use correlated subqueries: ``` select p.*, (select count(*) from users u where u.uid not in (select o.uid from orders o where o.productid = p.productid) and u.gender = 'Male' ) as NumMales, (select count(*) fro...
This should help you get started with ``` SELECT p.productid, p.productname, COALESCE(total_maleusers, 0) - COALESCE(no_maleusers, 0) AS No_MaleUsers, COALESCE(total_femaleusers, 0) - COALESCE(no_femaleusers, 0) AS No_FemaleUsers FROM (SELECT p.productid, p.productname, ...
List all products and count the male users, female users that did not place an Order
[ "", "mysql", "sql", "" ]
i have semester term values such as fall 2011, spring 2011 and so on. I want the result to be order in sequential manner example ``` fall 2001 spring 2001 fall 2002 spring 2002 .... ``` however I am getting ``` fall 2001 fall 2002 ..... spring 2001 spring 2002 ..... ``` when doing `order by semester`
``` SELECT Semester FROM Table ORDER BY regexp_replace(Semester, '[^0-9]+', ''), regexp_replace(Semester, '[^a-zA-Z]+', '') ``` This parses out the numbers from the text so you can first order by Year, then by the text. Or you could just get the right 4 most characters and order by them first... Assming the...
Use a CASE expression in your ORDER BY: ``` SELECT SEMESTER, whatever FROM SEMESTER_VALUES ORDER BY CASE SEMESTER WHEN 'spring 2001' THEN 1 WHEN 'fall 2001' THEN 2 WHEN 'spring 2002' THEN 3 WHEN 'fall 2002' THEN 4 WHEN 'spring 2003' THEN 5 ...
order by semester term in oracle
[ "", "sql", "oracle", "sql-order-by", "" ]
I have a complicated query that has to use a number called `SubUnitRate`. This variable comes from another table with special condition. in short we have: ``` DECLARE SUBUNITRATE NUMBER; BEGIN SELECT NVL (NULLIF (CU.SUBUNITRATE, 0), 1) INTO SUBUNITRATE FROM CURRENCYS CU JOIN ACCOUNTS ACC ON CU.ID = ACC.CURRE...
Assuming you want to use the value of SUBUNITRATE multiple times in the same query you could use the WITH clause: ``` with cte as ( select case when CU.SUBUNITRATE = 0 then 1 else CU.SUBUNITRATE end as SUBUNITRATE FROM CURRENCYS CU JOIN ACCOUNTS ACC ON CU.ID = ACC.CURRENC...
A PL/SQL block cannot return the results of a query as a query. Instead, you can print the results out. So, does this do what you want? ``` DECLARE SUBUNITRATE NUMBER; BEGIN SELECT NVL(NULLIF(CU.SUBUNITRATE, 0), 1) INTO SUBUNITRATE FROM CURRENCYS CU JOIN ACC ON CU.ID = ACC.CURRENCY...
How to declare and assign value to a variable before query?
[ "", "sql", "oracle", "plsql", "" ]
I'm struggling with this! My data is like the table below except there would be more than one user. Note that it isn't just a start/end time, there are many dates in between. ``` +-------------------------+--------+---------------------------+ | Date | Name 2 | Access | +---------...
I think the problem is with your cast, try `CAST AS DATE` : ``` select name_2, min(`date`) as EntryTime, max(`date`) as ExitTime, cast(`date` As Date) as YourDate from table where UserName like '%User1%' and EventTime between '2014-09-30 12:00:00' and '2014-10-05 12:00:00' group by cast(`dat...
this will give you a list of users each with every day's min and max ``` select cast(Date as datetime) as Date,Name,min(Date) as EntryTime, max(Date) as ExitTime from table where Date between '2014-09-30 12:00:00' and '2014-10-05 12:00:00' group by cast(Date as datetime),Name ``` you may need to cast Date field into ...
Get minimum and maximum datetime for each row between a date range
[ "", "sql", "sql-server", "" ]
I have been trying for days this SQL statement. I have a DB made for sales and all I need to do is: ``` SELECT SUM(orders.total) as total, orders.transaction_date as date, orders.id as orderid, orders.employee_id as empl from orders GROUP by orders.employee_id ``` This query is perfect it gives me all I need....
You need to aggregate the two tables separately *before* joining them together: ``` select sum(oi.quantity), sum(o.total) as total, o.employee_id as empl from orders o join (select oi.order_id, sum(oi.quantity) as quantity from order_items oi group by oi.order_id ) oi on oi.order_i...
You have two different `GROUP BY` statements between the first two queries, but they aren't both reflected in the merged query. ``` SELECT SUM(order_items.quantity) as quantity, SUM(orders.total) as total, orders.transaction_date as date, orders.id as orderid, orders.employee_id as empl from orders ...
SQL - Unable to correctly calculate a SUM
[ "", "mysql", "sql", "" ]
How can I count the number of occurrences of a substring within a string in PostgreSQL? --- Example: I have a table ``` CREATE TABLE test."user" ( uid integer NOT NULL, name text, result integer, CONSTRAINT pkey PRIMARY KEY (uid) ) ``` I want to write a query so that the `result` contains column how many o...
A common solution is based on this logic: *replace the search string with an empty string and divide the difference between old and new length by the length of the search string* ``` (CHAR_LENGTH(name) - CHAR_LENGTH(REPLACE(name, 'substring', ''))) / CHAR_LENGTH('substring') ``` Hence: ``` UPDATE test."user" SET re...
A Postgres'y way of doing this converts the string to an array and counts the length of the array (and then subtracts 1): ``` select array_length(string_to_array(name, 'o'), 1) - 1 ``` Note that this works with longer substrings as well. Hence: ``` update test."user" set result = array_length(string_to_array(na...
Counting the number of occurrences of a substring within a string in PostgreSQL
[ "", "sql", "string", "postgresql", "" ]
Input Rows ``` userid | no | version_no --------------|----------|-------------- abc | 100 | 1 abc | 2 | 1 abc | 101 | 2 abc | 3 | 2 def | 9 | 1 def | 1 | 2 def | 6 | 3 def ...
You need to apply a ranking function after aggregation: ``` SELECT * FROM ( SELECT userid, SUM(no) AS no_sum, version_no, ROW_NUMBER() OVER (PARTITION BY userid ORDER BY version_no DESC) AS rn FROM table_name GROUP BY userid, version_no ) AS dt WHERE rn = 1 ```
To get just the aggregated results for the highest version\_no without a self join, you can use `TOP` and `ORDER BY`: ``` SELECT TOP 1 userid, sum(no), version_no FROM your_table GROUP BY userid, version_no ORDER BY version_no DESC ``` `TOP 1` will return only the first record in the result set ordered...
Latest instance of sql row without self join
[ "", "sql", "sql-server", "" ]
I am trying to get a singel result row per date in SQL, using a single table in a postgres DB. I tried using Union, but I think this is not the right way. Can somone help me construct the right SQL. Sample Data Columns for Table content: id,creationdate,contenttype ``` 1 |2016-04-02|PAGE 2 |2016-04-02|ATTACHMENT 3 |2...
You can do it with conditional aggregation by selecting from the table only once: ``` SELECT date(creationdate) AS create_date, count(CASE WHEN contenttype='PAGE' then 1 end) as PAGE, count(CASE WHEN contenttype='ATTACHMENT' then 1 end) as ATTACHMENT FROM content GROUP BY content.creationdate ORDER ...
You need a *conditional aggregate*: ``` SELECT date(creationdate) AS create_date, SUM(CASE WHEN contenttype='PAGE' THEN 1 ELSE 0 END) AS PAGE, SUM(CASE WHEN contenttype='ATTACHMENT' THEN 1 ELSE 0 END) AS ATTACHMENT FROM content GROUP BY content.creationdate ORDER BY create_date ASC; ```
Aggregating postgres union results
[ "", "sql", "postgresql", "" ]
Generate the following two result sets: **1).** Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S). **2).** ...
Sometimes on HackerRank concat functon will give an error. You can use || to seperate in the same way. So if the code below doesnt work for you: ``` ( SELECT CONCAT(NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')') as THETEXT, '1' as SELECTNUMBER FROM OCCUPATIONS ) UNION ALL ( SELECT CONCAT('There are total ', CO...
I just tried on hackerrank and it works, You don't need to use Union. ``` select concat(name,'(',upper(substring(occupation,1,1)),')') from occupations order by name; select concat("There are a total of",' ',count(occupation),' ',lower(occupation),'s',".") from occupations group by occupation order by count(occupati...
MySQL Query error using UNION/UNION ALL and Group By
[ "", "mysql", "sql", "database", "" ]
I'm running the below query to try and get all the categories in my forum, with their latest topics posted. There are some categories that have no topics posted yet and want to return those also. ``` SELECT cat_id,cat_name,cat_description, Null as topic_date, Null as topic_subject FROM categories UNION ALL ...
What you need is a left outer join clause to join the results of topics to those of categories *only if they exist*. Somewhere along these lines: ``` SELECT c.cat_id, c.cat_name, c.cat_description, max(t.topic_date), t.topic_subject FROM categories c LEFT OUTER JOIN topics t ON t.topic_cat=c.cat_id GROUP BY c....
Replace `UNION ALL` with `UNION`. The latter removes duplicates. However, by your code you're probably trying to do a `LEFT OUTER JOIN`, so you should check some tutorials on `OUTER JOIN`s
SQL query to combine two tables while also showing all records from one table
[ "", "mysql", "sql", "" ]
I have a table with online sessions like this (empty rows are just for better visibility): ``` ip_address | start_time | stop_time ------------|------------------|------------------ 10.10.10.10 | 2016-04-02 08:00 | 2016-04-02 08:12 10.10.10.10 | 2016-04-02 08:11 | 2016-04-02 08:20 10.10.10.10 | 2016-04-02 09:0...
Try this one, too. I tested it the best I could, I believe it covers all the possibilities, including coalescing adjacent intervals (10:15 to 10:30 and 10:30 to 10:40 are combined into a single interval, 10:15 to 10:40). It should also be quite fast, it doesn't use much. ``` with m as ( select ip_addr...
Please test this solution, it works for your examples, but there may be some cases I didn't notice. No connect-by, no self-join. ``` with io as ( select * from ( select ip_address, t1, io, sum(io) over (partition by ip_address order by t1) sio from ( select ip_address, start_time t1, 1 io from ip_s...
Get envelope.i.e overlapping time spans
[ "", "sql", "oracle", "analytics", "timespan", "" ]
I have a simple SQL statement that does not seem to work. I want the of table match\_team ("match\_id") on the table match ("id"). Therefore I wrote the following INNER JOIN STATEMENT ``` SELECT * FROM match_team INNER JOIN match ON match_team.match_id = match.id ``` This throws an error however. Any thoughts on wh...
The problem is that `match` is a reserved word in your RDBMS, you didn't specify your RDBMS, and it really depend on it, but try one of this: ``` SELECT * FROM match_team INNER JOIN `match` ON match_team.match_id = `match`.id SELECT * FROM match_team INNER JOIN "match" ON match_team.match_id = "match".id ``` I don't ...
You can use double quotes for avoiding keywords. ``` SELECT * FROM match_team INNER JOIN "match" ON match_team.match_id = "match".id ```
Inner join statement does not seem to work
[ "", "sql", "" ]
I have the following table in the database. ``` +----+---------+---------------------+-----------+ | id | user_id | timeid | course_id | +----+---------+---------------------+-----------+ | 02 | 2 | 2016-01-27 19:24:17 | 14 | | 03 | 2 | 2016-02-27 19:24:27 | 15 | | 04 | 2 |...
A simple way uses `=` and a correlated subquery: ``` select t.* from t where t.timeid = (select max(t2.timeid) from t t2 where t2.user_id = t.user_id); ```
You can use the following query: ``` SELECT t1.id, t1.user_id, t1.timeid, t1.course_id FROM mytable as t1 JOIN ( SELECT user_id, MAX(timeid) AS timeid FROM mytable GROUP BY user_id ) AS t2 ON t1.user_id = t2.user_id AND t1.timeid = t2.timeid ``` `t2` is a derived table containing the latest `timeid` value p...
How to extract latest rows from Database for specific column?
[ "", "mysql", "sql", "" ]
I was wondering if its possible to add a condition like the code below in a select statement, and if it is, how should I do it ? code that looks like these > SELECT first\_name ,last\_name FROM persons\_table [condition: WHERE last\_name is on exclusiveList]
if your exclusiveList is on another table you can do: ``` SELECT first_name ,last_name FROM persons_table WHERE last_name in (select lastName from exclusiveListTable) ``` or even nicer: use join as a filter: ``` select * from -- or select A.* from (SELECT first_name ,last_name FROM persons_table) A inner join (sel...
It should be ``` SELECT first_name ,last_name FROM persons_table WHERE last_name in ('name1','name2',,,,'nameN') ```
How to check a specific string in List on a SQL Select statement?
[ "", "sql", "t-sql", "soql", "" ]
I'm running MySql Server 5.7.11 and this sentence: ``` updated datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ``` is **not** working. Giving the error: ``` ERROR 1067 (42000): Invalid default value for 'updated' ``` But the following: ``` updated datetime NOT NULL DEFAULT '1000-01-01 00:00:00' ``` **just works**...
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation. [MySQL Documentation 5.7 says](http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict): > Strict mode affects whether the server permits '0000-00-00' as a valid date: > If strict mode is not enabled, '00...
I got into a situation where the data was mixed between NULL and 0000-00-00 for a date field. But I did not know how to update the '0000-00-00' to NULL, because ``` update my_table set my_date_field=NULL where my_date_field='0000-00-00' ``` is not allowed any more. My workaround was quite simple: ``` update my_tabl...
Error in MySQL when setting default value for DATE or DATETIME
[ "", "mysql", "sql", "date", "datetime", "console", "" ]
I have table called `emp` and I a trying to find the lowest paid Clerk. My code `select min(sal) as min from emp where job='CLERK';` works fine and i get this: ``` MIN ---------- 800 ``` but I also want to show the name of the clerk which is `Smith`. When I run this code `select ename, min(sal) as min from e...
try this ``` SELECT * FROM emp WHERE SAL = (select MIN(SAL) sal from emp WHERE JOB ='CLERK') and JOB ='CLERK'; ```
You can use `row_number`: ``` select ename, sal as min from ( select ename, sal, row_number() over (order by sal) as rn from emp where job='CLERK' ) t where t.rn = 1 ```
Find min(sal) along with employee name SQL Oracle
[ "", "sql", "oracle", "greatest-n-per-group", "" ]
I need to do this but I don't know as. I have this table. ``` SSN | SALARY | MONTH YEAR 1234 1881,33 01 2008 8762 2578 01 2008 8726 2183,6475 01 2008 2321 1745,8525 01 2008 3123 1639,2 01 2008 1934 2572 01 2008 ``` Is it possible to select from months ...
``` SELECT * FROM ( SELECT t.*, ROW_NUMBER() OVER ( PARTITION BY year_month ORDER BY money DESC ) AS rn FROM ( SELECT A.ssn, SUM(B.WAGE)- SUM(B.SALARY/(8*20)) AS money, TRUNC( rep_date, 'MM' ) AS year_month FROM REP_LINES A INNER ...
You can use `keep`: ``` select year, month, max(salary) as salary, max(ssn) over (dense_rank first order by salary desc) as max_ssn from (select to_char(l.rep_date, 'YYYY') as year, to_char(l.rep_date, 'MM') as month, l.SSN, (SUM(c.WAGE)- SUM(c.SALARY/(8*20))) as salary from rep_lines l join...
Retrieve rows with highest salary per month and year
[ "", "sql", "oracle", "oracle11g", "oracle-sqldeveloper", "" ]
I am trying to get a date range using the following SQL condition in MySQL. ``` and a.timestamp >= '2016-03-29' and a.timestamp <= '2016-03-30' ``` This returns 0 rows but when I try a longer range like and a.timestamp >= '2016-03-20' and a.timestamp <= '2016-03-31' It returns the rows I want which is shown below i...
Presumably, you have no values on 2016-03-29. So, you only want to consider the *date* portion. One method is to use `date()`: ``` date(a.timestamp) >= '2016-03-29' and date(a.timestamp) <= '2016-03-30' ``` However, that is a bad habit, because the use of the function precludes the use of an index (if available). Ins...
Any time after midnight 2016-03-30 is greater than 2016-03-30, so you need to check like this to get values like "2016-03-30 15:55" ``` and a.timestamp >= '2016-03-29' and a.timestamp < '2016-03-31' ``` This will return all datetime values on March 29th and March 30th.
Sql condition to return specific date range
[ "", "mysql", "sql", "" ]
I have a table like this: ``` X Y ====== 20 20 20 20 20 21 23 22 22 23 21 20 ``` I need to find those rowid's where `X=Y` but their rowid is not the same? Like 1st row's `X` and 2nd row's `Y` is the same but they are in different rows.
you can do it many ways, and since you brought the `rowid` up, this is one of them: ``` select * from yourtable tab1 join yourtable tab2 on tab1.x = tab2.y and tab1.rowid <> tab2.rowid ```
You want duplicate rows: ``` select * from ( select x, y, rowid, count(*) over (partition by x,y) as cnt from tab where x=y ) dt where cnt > 1 ```
How to Find similar data with different Rowid in oracle?
[ "", "sql", "database", "oracle", "rowid", "" ]
I have two tables `Emp` and `Dept` and I am trying to display how many people work in each department along with their department name, but I can't get it to work. I have tried this `select count(ename) as count from emp group by deptno;` but the output I am getting is this : ``` COUNT ---------- 6 5 3...
Please try: ``` select count(*) as count,dept.DNAME from emp inner join dept on emp.DEPTNO = dept.DEPTNO group by dept.DNAME ```
A request to list "Number of employees in each department" or "Display how many people work in each department" is the same as "For each department, list the number of employees", this must include departments with no employees. In the sample database, Operations has 0 employees. So a LEFT OUTER JOIN should be used. `...
Find the number of employees in each department - SQL Oracle
[ "", "sql", "oracle", "" ]
Check the below Script ``` SELECT getdate() CurrentDate,getdate()+getdate() NewDate ``` Result is : ``` CurrentDate NewDate 2016-04-04 13:57:51.713 2132-07-08 03:55:43.427 ``` My question is , why year is 2132 and Month is 07 in New Date field.
`1900-01-01` is date 0 ``` SELECT CONVERT(datetime, 0) ``` when you add 2 dates together, it is implicitly convert to integer, perform the addition and then convert back to datetime ``` SELECT CONVERT(INT, getdate()), -- no of days since 1900-01-01 CONVERT(INT, getdate()) + CONVERT(INT, getdate()), ...
As your dates are going down to seconds you should - as one learns this in school :-) - go down to the smallest unit, do the maths there and then - if needed - go back to any format you want to use for display. The following will calculate the difference between two DATETIME values. If your elapsed times are really D...
SQL add Two date variables (Date + Date)
[ "", "sql", "sql-server", "t-sql", "" ]
I want to populate a table with data from a staging table. The interesting column in the staging table has the datatype `text` but is otherwise filled with either values that are parsable as doubles or are the empty string (ie `"4.209"`, `"42"` or `""`). The according column in the destination table has the data type `...
Use an `IIf()` expression: if `theColumn` contains a string which represents a valid number, return that number; otherwise return Null. ``` SELECT IIf(IsNumeric(theColumn), Val(theColumn), Null) FROM src ``` My first impulse was to use `IsNumeric()`. However I realized this is a more direct translation of what you re...
Convert empty strings to zero maybe also work. ``` insert into dest (.., theColumn, ... ) select ...., theColumn+0, .. from src ```
How do I convert an empty string into a numerical null in Access SQL_
[ "", "sql", "ms-access", "ado", "" ]
I want to create a view named saledetailfortax and it will consist 13 columns. They are saledetaildate, saledetailtime, shopid, productid, unitid, expdate, batchno, mrp, totalprice, qty, looseqty, priceperunit and taxid. My query is: ``` CREATE OR REPLACE VIEW saledetailfortax2 AS select sd.saledetaildate, sd.sa...
`GROUP BY` solution: ``` CREATE OR REPLACE VIEW saledetailfortax2 AS select sd.saledetaildate, sd.saledetailtime, sd.shopid, sd.productid, sd.unitid, sd.expdate, sd.batchno, sd.mrp, sd.totalprice, sd.qty, sd.looseqty, sd.unitprice as priceperunit, MAX(ord.taxid) from saledetail sd left JOIN distinctPr...
You could use a GROUP BY these columns productid , expdate , batchno , mrp and unitprice.
How to eliminate duplicate record in left join?
[ "", "sql", "postgresql", "" ]
Below is the query I'm working with - I need to get the MAX date for each of the PhaseEndDt. I've tried the ``` (SELECT Max(v) FROM (VALUES (aphase1.updated_ts), (aphase2.updated_ts), (aphase3.updated_ts)) AS VALUE(v)) AS [MaxDate] ``` but it isn't working :-( any help would be greatly appreciated! ``` SELECT dc.cas...
you can do it much easier, and probably faster: ``` WITH parms as (select 'Phase 1' AS "Phase1", 'Phase 2' AS "Phase2", 'Phase 3' AS "Phase3", '{091225F8-4606-401C-872E-FC5ACDC1D8E2}' AS case_id from dual) SELECT dc.case_id, parms."Phase1", SELECT Max(updated_ts) FROM a_identifiers WHERE identifier_value = parms....
if you only need max of updated\_ts you can use subquery or case: ``` SELECT dc.case_id, aphase1.identifier_value AS "phase1", aphase1.updated_ts AS "phase1_enddt", aphase2.identifier_value AS "phase2", aphase2.updated_ts AS "phase2_enddt", aphase3.identifier_value AS "phase3", aphase3.updated_ts AS "phase3_enddt", (S...
Need multiple maxdates-oracle sql developer 4.0.2
[ "", "sql", "oracle", "" ]
i dont have much expiriance with SQL and i am trying to crack my head on this query. i have 3 tables: Projects, Calculator and partialBilling (note: the 'calculator' columns you see at the code ive added 'k','l','m' etc are real...i didnt gave them those names...). the query is working fine but **part** of the values ...
Instead of proprietary `IFNULL` better use Standard SQL `COALESCE`: ``` SUM(COALESCE(Calculator.K,0) + COALESCE(Calculator.L,0), ...` ``` Or maybe a bit more efficient: ``` SUM(COALESCE(Calculator.K,0)) + SUM(COALESCE(Calculator.L,0)), ...` ```
Try to use IFNULL() ``` SUM(IFNULL(Calculator.K,0) + ... + IFNULL(Calculator.AR,0)) AS sumofTotal ```
SQL query: NULL values that should not be NULL when using aggregate function with left join
[ "", "mysql", "sql", "left-join", "aggregate-functions", "" ]
I have two tables Table 1: ``` process status 1 completed 2 completed 3 not completed ``` `table 2` ; is a history table that gets its data from table1 ``` process status 1 completed 2 completed 3 not completed ``` Next time when the data gets pushed into history table from...
Try this. ``` INSERT INTO table2 (process,status) select process,'completed' as status From table1 where process in (select distinct process from table2 where status <> 'completed') ```
Use this if you want to **match some column** in **both** the **Tables**: ``` UPDATE _table_name_ SET col1 = _alias_table_.col1, ... /* all columns except merge keys and Identity column */ FROM (SELECT * FROM _tmp_table1_ UNION SELECT * FROM _tmp_table2_) _alias_table_ WHERE _table_name_._merge_key_ = _alias_table_._...
Insert into..select with condition
[ "", "sql", "sql-server", "select", "insert", "" ]
There are two tables ``` DEPT ( DEPT_ID NUMBER(5) PRIMARY KEY, DEPT_NAME VARCHAR2(10) ); COURSE ( COURSE_ID NUMBER(5) PRIMARY KEY, COURSE_NAME VARCHAR2(15),DEPT_ID NUMBER(5), FOREIGN KEY(DEPT_ID) REFERENCES DEPT ) ``` I want to change the size equal to `5` of the column `DEPT_ID` which has a `FOR...
I think you need to do the following: * drop the foreign key constraints to the tables (you can use `alter table drop constraint`). * change the data types in all the tables (you can use `alter table modify column`) * add the foreign key constraints back (`alter table add constraint`) This doesn't require dropping an...
You have to drop the foreign key constraint first. Then execute the command you mentioned. Then add back the constraint.
How to change the size of a column with FOREIGN KEY constraint?
[ "", "sql", "oracle", "oracle10g", "" ]
I need to create a range number from 1 to n. For example, the parameter is `@StartingValue` ``` @StartingValue int = 96 ``` Then the result should be: ``` Number ------------- 96 95 94 93 92 ff. 1 ``` Does anyone have an idea how to do this? Thank you.
Use a Jeff Moden's [**Tally Table**](http://www.sqlservercentral.com/articles/T-SQL/62867/) to generate the numbers: ``` DECLARE @N INT = 96 ;WITH E1(N) AS( -- 10 ^ 1 = 10 rows SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N) ), E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 ...
One simple method is a numbers table. For a reasonable number (up to the low thousands), you can use `spt_values`: ``` with numbers as ( select top 96 row_number() over (order by (select null)) as n from t ) . . . ``` Another method is a recursive CTE: ``` with numbers as ( select 96 as n ...
Create a Range From n to 1 in SQL
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
Have a table in Oracle db such like this: ``` Word Cnt A 20 B 25 C 23 B 29 D 31 ``` What I trying to do - is to add an additional column with id of a word. But it is not a primary key it wont be unique because of repeating words. So the outcome I'm looking for is: ``` Word Cnt ID A ...
You can use a window function to calculate the ID: ``` select word, cnt, dense_rank() over (order by word) as id from the_table; ``` You can update the table using the above, if you really need to persist that: ``` merge into the_table tg using ( select rowid as rid, dense_rank() over (ord...
My solution requires a lot of nested subqueries, but it works... ``` alter table mytable add (id number(12)); update mytable set id = (select n from (select word, rownum n from (select word from mytable group by word order by word) ) x where mytable.word = x.word ...
Add column with id in Oracle SQL
[ "", "sql", "oracle", "" ]
I have the following table: ``` FileName | SubFileName | TotalPlayersCount | ------------------------------------------- AAA | SF1 | 11 | AAA | SF2 | 5 | AAA | SF3 | 3 | BBB | SF1 | 8 | BBB...
Easy way, use `NOT EXISTS` to return a row if there are no other row with same FileName that has a higher TotalPlayersCount: ``` select FileName, SubFileName, TotalPlayersCount from dbo.MyTestTable t1 where not exists (select 1 from dbo.MyTestTable t2 where t2.FileName = t1.FileName ...
``` select fileName,subFileName,max(TotalPlayersCount ) from table_name group by filename ```
Compare rows and select max value
[ "", "mysql", "sql", "foreach", "max", "" ]
How can I connect two grouped below query? ``` select [Fiscal Year],[Fiscal Quater],sum([colX])as X from table1 group by [Fiscal Year],[Fiscal Quater]; select [Fiscal Year],[Fiscal Quater],sum([colY]) as Y from table2 group by [Fiscal Year],[Fiscal Quater]; ``` result should return column: [Fiscal Year],[Fiscal Quat...
You probably want something like this: ``` select coalesce(t1.[Fiscal Year], t2.[Fiscal Year]) as [Fiscal Year], coalesce(t1.[Fiscal Quater], t2.[Fiscal Quater]) as [Fiscal Quater], coalesce(t1.X, 0) as X, coalesce(t2.Y, 0) as Y from ( select [Fiscal Year], [Fiscal Quater], sum([colX]) as X ...
`UNION ALL` the two tables together in a derived table, do `GROUP BY` at main level: ``` select [Fiscal Year], [Fiscal Quater], sum([colX])as X, sum([colY]) as Y from ( select [Fiscal Year], [Fiscal Quater], colX, NULL as colY from table1 UNION ALL select [Fiscal Year], [Fiscal Quater], NULL as colX, colY from table2 ...
Combine two grouped query into one select
[ "", "sql", "sql-server", "sql-server-2008", "group-by", "" ]
If I have a user that can be associated with multiple keys would the proper table setup be: 1. One table with two columns such as: ``` UserName | Key ``` where there is no primary key and a user can have multiple rows, or: 2. Two tables with an matching identifier ``` Table 1 UserName | UserI...
If you wanted to find all the keys associated with a given user you might use the following `JOIN` query: ``` SELECT Key FROM keys k INNER JOIN users u ON k.UserId = u.UserId WHERE u.UserName = 'username' ``` The place which would benefit most from an index in this case would be the `UserId` columns in the two ta...
Without an understanding of the entities and attributes you are attempting to model, it's not really possible to give you an answer to the question you asked. **Entity Relationship Modeling** What *entities* does your data model represent? An entity is a person, place, thing, concept or event that can be uniquely ide...
Performance of primary/foreign key versus single table with no primary key
[ "", "sql", "sql-server", "database", "" ]
Recently I've been developing a leave management system. In this application I need a report like in a month wise employee leave statement. So here's my sample table: ``` Employee Id application Date Start Date End Date 20130002 14-Mar-2016 16-Mar-2016 17-Mar-2016 20130012 15-Mar-2016 29-Mar-2016 2-Ap...
Assuming that the time component of the dates is set to `00:00:00` then: ``` SELECT EmployeeId, application_date, GREATEST( start_date, DATE '2016-03-01' ) AS start_date, LEAST( end_date, DATE '2016-03-31' ) AS end_date FROM table_name WHERE Start_date <= DATE '2016-03-31' AND end_date >= ...
This is for SQL Server ``` SELECT * FROM Leaves WHERE MONTH(StartDate) <= 4 and Month(EndDate) >= 4 ``` For Oracle ``` SELECT * FROM Leaves WHERE EXTRACT(month FROM StartDate) <= 4 and EXTRACT(month FROM EndDate) >= 4 ```
How to get all info about start date to end date within a given date range?
[ "", "sql", "oracle", "plsql", "" ]
I'm returning total sales for a period of time for each country. Sometimes a country will not appear in the results because they haven't had any orders during that time period. For these countries with no sales, I would like to include in the results the countries abbreviated name and sales total with a value of '0'. F...
This should do it: ``` SELECT Country , Sales_Total=ISNULL(Sales_Total,0) FROM (SELECT o.Country , SUM(TOTAL) AS Sales_Total FROM Orders WHERE OrderDate BETWEEN '2014-01-01' AND '2014-12-31' GROUP BY Country) AS o ...
I would use (create if needed) a country table you could outer join from. Then you can write like so; ``` SELECT c.CountryCode, SUM(TOTAL) AS Sales_Total FROM Country c LEFT JOIN Orders o in c.CountryCode = o.Country AND o.OrderDate BETWEEN '2014-01-01' AND '2014-12-31' GROUP BY c.CountryCode ```
Microsoft SQL: include dummy row(s) in results when value doesn't exist
[ "", "sql", "sql-server", "" ]
``` select mydate from Tble_xxx where CONVERT(varchar(20), mydate, 120) BETWEEN CONVERT(varchar(20), (@startdate, 'yyyy-MM-dd HH:m:ss:mmm', 'en-US') , 120) AND CONVERT(varchar(20), (@enddate, 'yyyy-MM-dd HH:m:ss:mmm', 'en-US'), 120) ``` When I am try to get date between to data and change the Specific Format datet...
Try this ``` DECLARE @startdate DATETIME='08/01/2015 12:00:00' DECLARE @enddate DATETIME='06/04/2015 12:00:00' select mydate from Tble_xxx where CAST(mydate AS DATE) BETWEEN CAST(@startdate AS DATE) AND CAST(@enddate AS DATE) ```
SQL server supports implicit conversion between character types (char, nchar, varchar, nvarchar) and date/time types (datetime, date, time, etc), so you do not need to use explicit `Convert` statements. See the Data Type Conversion chart here: <https://msdn.microsoft.com/en-gb/library/ms191530.aspx> For character/dat...
error Display Datetime in Specific Format
[ "", "sql", "sql-server", "" ]
I'm trying to join two tables like this: Table A ``` ID Value1 1 A 2 B 3 C ``` Table B ``` ID Value2 1 A 3 B 4 C ``` Result should be: ``` ID Value1 Value2 1 A A 2 B null 3 C B 4 null C ``` I.e. join Table A to Table B on ID. If ID doesn't ex...
You are very close, you just need a little push in the right direction: ``` SELECT COALESCE(a.ID, B.ID) As ID, a.Value1, b.Value2 FROM TableA a FULL OUTER JOIN TableB b ON a.ID=b.ID ``` The `COALESCE` function returns the first parameter it gets that is not null. since this is a full outer join, `a.id` will be null...
Try this: ``` SELECT * FROM TableA A FULL OUTER JOIN TableB B ON A.ID = B.ID; ``` Just a note: you should not name your tables in SQL with spaces in them.
SQL - not sure how to join tables
[ "", "sql", "oracle", "" ]
I have an app that cannot display any year past 2016 in a drop down. At the same time, and as time goes on, I need to display past years. For example: * in the year 2017, I will need to display 2016 and 2017. * In the year 2018, I will need to display 2016, 2017, and 2018. * And so on So I have developed the follow...
Try this, this will generate a list of Year from 2016 to current year ``` WITH CTE_TEST AS( SELECT 2016 AS NYEAR UNION ALL SELECT NYEAR+1 FROM CTE_TEST WHERE NYEAR+1 <= YEAR(GETDATE()) ) SELECT * FROM CTE_TEST ```
Create a Year table that has all valid years you ever want the application to handle. ``` Select Year From Year Where Year>=2016 AND Year<=DATEPART(Year,GETDATE()) ```
Display year in the future
[ "", "sql", "sql-server", "" ]
This is related to: [Why is selecting specified columns, and all, wrong in Oracle SQL?](https://stackoverflow.com/questions/2315295/why-is-selecting-specified-columns-and-all-wrong-in-oracle-sql) The query: ``` select is_parent, animals.* from animals order by is_parent ``` throws the error: ``` [Error] ORA-00960: ...
I have managed to come up with a neat solution thanks to the very helpful comments and answers that say that I will confuse the compiler if I don't use an alias. I find having to rename the columns cumbersome, for example, if I had selected more columns: ``` select is_parent, age, animals.* from animals order by is_p...
Something you can try: 1) Use the table name (or its alias) in the ORDER BY clause: ``` SQL> select is_parent, animals.* 2 from animals 3 order by animals.is_parent; no rows selected ``` 2) Write your ordering clause based on the position of fields in your select list: ``` SQL> select is_parent, animals.* ...
How to resolve 'ambiguous column naming in select list' when 'select col, t.*' is used with an order by clause
[ "", "sql", "oracle", "" ]
My Databases look like so: **PEAK (NAME, ELEV, DIFF, MAP, REGION)** **CLIMBER (NAME, SEX)** **PARTICIPATED (TRIP\_ID, NAME)** **CLIMBED (TRIP\_ID, PEAK, WHEN)** * PEAK gives info about the mountain peaks that the user is interested in. The table lists the name of each peak, it elevation(in ft), its difficulty l...
For your first question, you should just be able to remove the Having clause to get climbs where either Mark or Mary participated. ``` SELECT PEAK FROM CLIMBED WHERE TRIP_ID IN (SELECT TRIP_ID FROM PARTICIPATED WHERE NAME IN ('MARK','MARY') GROUP BY TRIP_ID ); ``` Leaving the Having clause ther...
``` This is for your first query : Select c.NAME from PARTICIPATED a // join with Climbed to get only peak based trips inner join CLIMBED b on a.TRIP_ID=b.TRIP_ID // join with peak to ge the name of peak inner join PEAK c on c.NAME=b.PEAK // on the result set, filter the result...
SQL Query - 2 queries involving COUNT() and the owner's of a certain trip
[ "", "sql", "count", "oracle-xe", "" ]
This for HackerRank Weather Observation 5 problem on databases (<https://www.hackerrank.com/challenges/weather-observation-station-5>). How would I solve this? > Query the two cities in STATION with the shortest and longest CITY > names, as well as their respective lengths (i.e.: number of characters > in the name). I...
Here is a solution with window functions: ``` select city, length(city) from ( select city, row_number() over (order by length(city), city) as shortest_is_one, row_number() over (order by length(city) desc, city) as longest_is_one from station ) where shortest_is_one = 1 or longest_is_one = 1; ``` A...
In a single table scan: ``` SELECT MIN( city ) KEEP ( DENSE_RANK FIRST ORDER BY LENGTH( city ) ) AS shortest_city, MIN( city ) KEEP ( DENSE_RANK LAST ORDER BY LENGTH( city ) ) AS longest_city, LENGTH( MIN( city ) KEEP ( DENSE_RANK FIRST ORDER BY LENGTH( city ) ) ) AS shortest_length, LEN...
Finding max length of a string + which string it is in Oracle SQL
[ "", "sql", "oracle", "" ]
I dont know SQL, but I need to use it for PHP, and I have a problem. When I try to create this table: ``` CREATE TABLE logs ( userbeinglogged VARCHAR(255) NOT NULL, action_location VARCHAR(255) NOT NULL, log_date DATE('YYYY-MM-DD') NOT NULL, log_time TIME('00:00:00') NOT NULL, ); ``` At the last line, I get the erro...
Remove your comma, right before the closing parenthesis. And for advice just use `log_Date DATETIME`
Remove the last comma. Looks like it has an extra. ``` CREATE TABLE logs ( userbeinglogged VARCHAR(255) NOT NULL, action_location VARCHAR(255) NOT NULL, log_date DATE('YYYY-MM-DD') NOT NULL, log_time TIME('00:00:00') NOT NULL); ```
MySQL error doesnt make sense?
[ "", "mysql", "sql", "" ]
I have a table, containing numbers (phone numbers) and a code (free or not available). Now, I need to find series, of 30 consecutive numbers, like 079xxx100 - 079xxx130, and all of them to have free status. Here is an example how my table looks like: ``` CREATE TABLE numere ( value int, code varchar(10) ); ...
This seems like it works in my dataset. Modify the select and see if it works with your table name. ``` DECLARE @numere TABLE ( value int, code varchar(10) ); INSERT INTO @numere (value,code) SELECT 123100, 'free' WHILE (SELECT COUNT(*) FROM @numere)<=30 BEGIN INSERT INTO @numere (value,code) SELECT MAX(value)+...
This is usual Island and Gap problem. ``` ; with cte as ( select *, grp = row_number() over (order by value) - row_number() over (partition by code order by value) from numere ), grp as ( select grp from cte group by grp having count(*) >= 30 ) select c.grp, c.value, c.c...
Find consecutive free numbers in table
[ "", "sql", "sql-server", "gaps-and-islands", "" ]
I want to generate a list of hours between to hours with an interval of 30 minutes. For example an employee enters work at 09:00 and leaves at 18:00, so I want to generate this: ``` Hours ----- 09:00 09:30 10:00 10:30 11:00 11:30 12:00 12:30 13:00 13:30 14:00 14:30 15:00 15:30 16:00 16:30 17:00 17:30 18:00 ``` How c...
Well using recursive CTE, you can achieve this result. Try below query - ``` DECLARE @timeFrom TIME = '09:00' DECLARE @timeTo TIME = '18:00' ;with SourceHrs as ( select @timeFrom as [Hours] UNION ALL SELECT DATEADD(MINUTE, 30, [Hours]) from SourceHrs WHERE [Hours] < @timeTo ) SELECT CONVERT(VARCHAR(5),Ho...
This will give you what you need, using a tally is faster than recursive: ``` DECLARE @from time = '09:00' DECLARE @to time = '09:00' IF @from <= @to WITH N(N)AS (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1))M(N)), tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a) SELECT top (datediff(minute, @from, @t...
How to generate hours between two hours in SQL Server?
[ "", "sql", "sql-server", "time", "hour", "" ]
I'm working out of VB6 with SQL SERVER 2012. I found myself in a pickle. Basically i have a query that works fine and pulls the necessary data in SQL SERVER, however, I'm having a difficult time translating it to vb6 SQL code. Here's a working query in SQL SERVER... ``` SELECT 'TotalSum' = SUM(Units) FROM tblDetail ...
This should work. I'm able to use SQL queries using NOT with ADODB in VB6. ``` g_SQL = "SELECT 'SUM' = SUM(Units) " & _ "FROM tblDetail WHERE " & _ "MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _ "CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _ "CAST(SStartD As DateTime) <= '" & D...
Your translation of NOT(InvoiceNo = '11880' AND DtlNo = 2) to (InvoiceNo <> '11880' AND DtlNo <> 2) is incorrect. In formal logic, !(A & B) is equivalent to (!A or !B), so it should be: ``` (InvoiceNo <> '11880' OR DtlNo <> 2) ``` This is why you're getting different results. However, why not use the original query?...
SQL query assistance needed with 'NOT'
[ "", "sql", "sql-server", "select", "sql-server-2012", "vb6", "" ]
show create table USERS; And i will get that result . ``` CREATE TABLE `USERS` ( `UR_ID` bigint(20) NOT NULL, `DEPT_ID` bigint(20) DEFAULT NULL, `DN_ID` bigint(20) NOT NULL, `CREATED_BY` varchar(45) NOT NULL, `LAST_UPDATED_BY` varchar(45) NOT NULL, `LAST_UPDATED_DT` datetime NOT NULL, `UR_LOGIN_NAME`...
The root cause is file(s) #sql2-3ea-2c\* in data directory and/or table with such name in internal InnoDB dictionary. That would prevent any ALTER operation on USERS table.. Search google for 'removing orphaned innodb tables' for instructions reg. that
By default MariaDB appends \_ibfk to the name of the foreign keys if you do not specify it.So, please use the following code format to drop foreign keys where you have not specified foreign key name: ``` ALTER TABLE table_name DROP FOREIGN KEY foreign_key_ibfk; ```
Can not drop FOREIGN KEY in Maria DB
[ "", "mysql", "sql", "database", "foreign-keys", "mariadb", "" ]
I have a system integration project which needs to CRUD from one DB to another. Not especially complicated. However, when it comes to deleting rows which exist in the target but not in the source, I ran into a little trouble. The standard patterns include: LEFT JOIN, NOT EXISTS or NOT IN. I chose the LEFT JOIN. My 'Pho...
Use `exists`. ``` DELETE p FROM @Phone p where exists (select 1 from @tmpPhones where Id = p.Id) AND not exists (select 1 from @tmpPhones where PhoneType = p.PhoneType) ``` Edit: Deleting using `cte`. ``` with todelete as ( select id,phonetype from phone except select id,phonetype from tmpphones t whe...
I think two exists statements pretty much capture the logic: as you describe it ``` DELETE p FROM @Phone p WHERE EXISTS (SELECT 1 FROM @tmpPhone t WHERE t.id = p.id) AND NOT EXISTS (SELECT 1 FROM @tmpPhone t WHERE t.id = p.id AND t.PhoneType = p.PhoneType) ; ```
SQL Delete Where Not In with Composite Key
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm trying to return the `DISTINCT` IDs from a table if it meets certain criteria. > 1. An ID must contain CID of 1,26,33,49 (all) > 2. An ID should NOT contain CID of 38 or 46 or 67 Here's the table. [![enter image description here](https://i.stack.imgur.com/oUA2F.png)](https://i.stack.imgur.com/oUA2F.png) Here's ...
[SQL Fiddle](http://sqlfiddle.com/#!6/9c862/9) Use conditional aggregation. ``` SELECT id FROM cte group by id having sum(case when cid in (1,26,33,49) then 1 else 0 end) = 4 and sum(case when cid in (38,46,67) then -1 else 0 end) = 0 ```
EXCEPT is opposite to UNION in a manner of speaking. ``` SELECT c1.id FROM cte c1 WHERE c1.CID IN(1,26,33,49) GROUP BY c1.id HAVING COUNT(DISTINCT c1.CID) = 4 EXCEPT SELECT DISTINCT c1.id FROM cte c1 WHERE c1.CID IN(38,46,67) ```
Return distinct ID based on few criteria
[ "", "sql", "sql-server-2012", "" ]
I have a search box for people's names in my application. Candidate's names are stored as firstName and then lastName. When I search the application, the application input submits a call to an ajax function, where I have this piece of code. ``` filters.where = { $or: ['firstName', 'lastName', 'email'].map((item)...
Seems like you might have to split the query input and search all fields on the terms passed in. for example: ``` var queryClause ='John Smith'; filters.where = { $or: _.flatten(_.map(['firstName', 'lastName', 'email'], function(){ return _.map(queryClause.split(' '), function(q){ return {[item...
use something like the following to search by full name in this form "firstName lastName" ``` Sequelize.where(Sequelize.fn("concat", Sequelize.col("firstName"), ' ', Sequelize.col("lastName")), { $ilike: '%john smith%' }) ``` by doing so you fix the issue of firstname or la...
Query two combined fields at once in Sequelize
[ "", "sql", "node.js", "sequelize.js", "" ]
I can't seem to figure out the syntax issue here. This works, but returns nulls; ``` SELECT jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs, (SELECT SUM(jot.Act_Run_Hrs) FROM PRODUCTION.dbo.Job_Operation_Time jot WHERE jot.Job_Operation = jo.Job_Operation) AS Cost FROM PRO...
try this: ``` SELECT jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs, ISNULL((SELECT SUM(jot.Act_Run_Hrs) FROM PRODUCTION.dbo.Job_Operation_Time jot WHERE jot.Job_Operation = jo.Job_Operation),0) AS Cost FROM PRODUCTION.dbo.Job_Operation jo WHERE jo.Job = 'A5076027' ```
I don't think you need a correlated subquery here. This seems to me like a standard left join is all that is required. ``` SELECT jo.Job_Operation , jo.Job , jo.Work_Center , jo.Operation_Service , jo.Est_Total_Hrs , SUM(isnull(jot.Act_Run_Hrs, 0)) AS Cost FROM PRODUCTION.dbo.Job_Operation jo left ...
ISNULL Syntax Challenge
[ "", "sql", "sql-server", "" ]
I have a SQL date field that is stored as `nvarchar(max)`. Example: `4/7/2016 12:50:03 AM` I need to convert this to `int`. I have this: `cast(convert(char(8), DateField,112) as int)` but I'm getting an error message > Conversion failed when converting the varchar value '5/22/201' to data type int Obviously, `/` ...
I believe if you cast the varchar to a date it will work cast(convert(char(8),cast(DateField as datetime),112) as int)
You can `replace` the slashes with blanks: ``` CAST(REPLACE(CONVERT(char(8),DateField,112),'/','') as int) ```
Trying to convert nvarchar stored as datetime to int
[ "", "sql", "sql-server-2012", "" ]
I have two tables with a many-to-many association in postgresql. The first table contains activities, which may count zero or more reasons: ``` CREATE TABLE activity ( id integer NOT NULL, -- other fields removed for readability ); CREATE TABLE reason ( id varchar(1) NOT NULL, -- other fields here ); ``` ...
We need to compare *sorted* lists of reasons to identify equal sets. ``` SELECT count(*) AS ct, reason_list FROM ( SELECT array_agg(reason_id) AS reason_list FROM (SELECT * FROM activity_reason ORDER BY activity_id, reason_id) ar1 GROUP BY activity_id ) ar2 GROUP BY reason_list ORDER BY ct DESC, reaso...
I think you can get what you want using this query: ``` SELECT count(*) as count, reasons FROM ( SELECT activity_id, array_agg(reason_id) AS reasons FROM ( SELECT A.activity_id, AR.reason_id FROM activity A LEFT JOIN activity_reason AR ON AR.activity_id = A.activity_id ORDER BY activity_id, reason_...
Query to count the frequence of many-to-many associations
[ "", "sql", "arrays", "postgresql", "many-to-many", "aggregate", "" ]
I have a table of 20000 records. each Record has a datetime field. I want to select all records where gap between one record and subsequent record is more than one hour [condition to be applied on datetime field]. can any one give me the SQL command code for this purpose. regards KAM
This can also be done with a sub query, which should work on **all** DBMS. As gordon said, date/time functions are different in every one. ``` SELECT t.* FROM YourTable t WHERE t.DateCol + interval '1 hour' < (SELECT min(s.DateCol) FROM YourTable s WHERE t.ID = s.ID AND s.DateCol > t.DateCol) ``` Y...
ANSI SQL supports the `lead()` function. However, date/time functions vary by database. The following is the logic you want, although the exact syntax varies, depending on the database: ``` select t.* from (select t.*, lead(datetimefield) over (order by datetimefield) as next_datetimefield from t ...
Difference of datetime column in SQL
[ "", "sql", "datetime", "" ]
I try to select all names with "Schmidt". But some names are lower case and some upper case. I try this : ``` Select * from Account where name like '%chmidt%' or name like '%CHMIDT%' ``` But when one letter inside the word is upper case(e.g. SchmidT), the statement didnt find this. Know somebody a easy way to solve ...
I am guessing that you are using Oracle and not MySQL, because it is case senstive by default. Just use the `upper()` or `lower()` functions: ``` Select * from Account where lower(name) like '%chmidt%'; ``` I would add an `s` if you want names like "Schmidt": ``` Select a.* from Account a where lower(a.name) like '%...
Do a lower case comparison: ``` Select * from Account where lower(name) like '%chmidt%' ```
SQL - Select name, no matter upper or lower case letters
[ "", "sql", "database", "oracle", "plsql", "" ]
**Task :** Find country to which maximum of customers belong. **Query** ``` SELECT country, count(*) FROM customers GROUP BY country HAVING count(*) = (SELECT max(max_sal) FROM (SELECT count(*) max_sal FROM customers GROUP BY country)) ; ``` **Result**: [![enter image description here]...
I might be missing something, but it can be as simple as this: ``` SELECT * FROM ( SELECT country, COUNT (*) max_sal FROM customers GROUP BY country ORDER BY COUNT (*) DESC) WHERE ROWNUM <= 1; ```
You can use `WITH` clause: ``` WITH c AS ( SELECT country, Count(1) n FROM customers GROUP BY country) SELECT country, n FROM c WHERE n = (SELECT Max(n) FROM c) ```
Query simplification Oracle Northwind
[ "", "sql", "database", "oracle", "northwind", "" ]
Why do I need the SELECT privilege on this: ``` UPDATE Sailors S SET S.rating = S.rating - 1 ``` While I don't need it for this query: ``` UPDATE Sailors S SET S.rating = 8 ```
In the first you are selecting ``` = S.rating - 1 ``` In the second you are not selecting ``` = 8 ``` [sp\_table\_privileges](https://msdn.microsoft.com/en-us/library/ms173835.aspx) > SELECT = GRANTEE can retrieve data for one or more of the columns. > > INSERT = GRANTEE can provide data for new rows for one or mo...
It looks like you're reading from S in the first query (the second S.rating) where as in the second query you're only ever writing data to S. To read data you will need SELECT permissions.
UPDATE and SELECT
[ "", "sql", "database", "select", "updates", "privileges", "" ]
I have two tables here: table Product: ``` ╔═════════════╦════════════╦════════════════════╗ β•‘ ProductID β•‘ Name β•‘ productImageURL β•‘ ╠═════════════╬════════════╬════════════════════╣ β•‘ 10 β•‘ Product 1 β•‘ β•‘ β•‘ 20 β•‘ Product 2 β•‘ β•‘ β•‘ 30 β•‘ Product ...
Use `JOIN` in your `UPDATE`: ``` UPDATE p SET p.productImageURL = i.ImageURL FROM Product p INNER JOIN ProductImage i ON i.ProductID = p.ProductID ```
Same idea as that of Felix but cleaner SQL. Works in MySql. ``` UPDATE Product p, ProductImage i SET p.productImageURL = i.ImageURL WHERE i.ProductID = p.ProductID; ```
Copy data from one table to another table that has the same id
[ "", "sql", "sql-server", "" ]
My sql script is like this : ``` SELECT hotel_code, star FROM hotel WHERE star REGEXP '^[A-Za-z0-9]+$' ``` The result is like this : <http://snag.gy/kQ7t6.jpg> I want the result of select the field that contains numbers and letters. So, the result is like this : ``` 3EST 2EST ``` Any solution to solve my problem...
I guess you're trying to get Must alphanumeric values. It can be achieved by following. ``` ^([0-9]+[A-Za-z]+[0-9]*)|([A-Za-z]+[0-9]+[A-Za-z]*)$ ```
The solution seems be like that: ``` '^[A-Za-z]+[0-9]+[A-Za-z0-9]+$|^[0-9]+[A-Za-z]+[A-Za-z0-9]+$' ``` You'll find elements beginning with letters and numbers OR numbers and letters and then containing both ones.
How to select the field that contains numbers and letters?
[ "", "mysql", "sql", "" ]
I would like to know which SQL dialect is being used in the snippet. Is it MSSQL, MySQL, PL/SQL or is it invalid SQL? ``` CREATE TABLE ACTable ( id int NOT NULL, x float NOT NULL, y float NOT NULL, z float NOT NULL ) CONSTRAINT [PK_FTTable] PRIMARY KEY( id ) ```
The SQL is incorrect but this SQL would work in SQL Server: ``` CREATE TABLE ACTable ( id int NOT NULL, x float NOT NULL, y float NOT NULL, z float NOT NULL CONSTRAINT [PK_FTTable] PRIMARY KEY( id )) ```
This part is OK in almost every rdbms ``` CREATE TABLE ACTable ( id int NOT NULL, x float NOT NULL, y float NOT NULL, z float NOT NULL ) ``` The problem is the constraint, and doesnt look like a valid statment for any db. You can try that `CREATE TABLE` on every rdmbs on **[sqlFiddle](http://sqlfiddl...
Detect SQL dialect
[ "", "sql", "sql-server", "" ]
I have select statement like below: ``` select [Fiscal Year], sum([value]), YEAR(DATEADD(year,-1,[Fiscal Year])) as previous_year from [table1] group by [Fiscal Year] ``` How to add after column `previous_year`, `sum([value])` from previous year? [![enter image description here](https://i.stack.imgu...
Please try the below query for SQL 2008 ``` select t1.[Fiscal Year],t1.Value,(t1.[Fiscal Year]-1) [previous_year],t2.Value [previous_value] from ( select [Fiscal Year], sum([value]) value from [table1] group by [Fiscal Year] )t1 LEFT JOIN ( select [Fiscal Year], sum([value]) value from [table1] group b...
``` --to prepare the environment, let said this is your table declare @table table ( fiscalYr integer, Value integer, previousyr integer, prevValue integer ) --to prepare the value, let said these are your value insert into @table values (2014,165,2013,0); insert into @table values (2015,179,2014,0); insert in...
Display sum from previous year
[ "", "sql", "sql-server", "sql-server-2008", "datetime", "sqldatetime", "" ]
Suppose I have two tables `PO` and `PO_Line` and I want to list all fields from `PO` plus the quantity of rows from `PO_Line` that link back to each row in `PO` I would write a query something like - ``` SELECT PO.propA, PO.propB, PO.propC, PO.propD, PO.propE, ... PO.propY, COUNT(PO_Line.propA) LINES F...
I think you just want window functions: ``` SELECT . . ., COUNT(PO_Line.propA) OVER (PARTITION BY PO.ID) as LINES FROM PO LEFT JOIN PO_Lines ON PO.ID = PO_Lines.PO_ID; ```
Reading your query I think you might not need a `GROUP BY` to begin with: ``` SELECT PO.propA, PO.propB, PO.propC, PO.propD, PO.propE, ... PO.propY, (SELECT COUNT(*) FROM PO_Lines WHERE PO.ID = PO_Lines.PO_ID) LINES FROM PO ```
Grouping by all non-aggregated columns in MSSQL
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have the following SQL query: ``` SELECT SUM(tmp.mval), tmp.timekey FROM (SELECT teghamas, MAX(arzheq) as mval, ceil(UNIX_TIMESTAMP(zhamanak)/(60 * 60)) AS timekey FROM `masnakcutyun` LEFT JOIN teghkentron ON `masnakcutyun`.`teghKentronId`=`teghkentron`.`teghKentronId` WHERE teghkentron.ha...
It seems to be a phpMyAdmin parser bug, see [the issue on github](https://github.com/phpmyadmin/phpmyadmin/issues/12080), the query itself is valid.
MySQL allow write subquery in `from` clause, but this is know [issue](https://github.com/phpmyadmin/phpmyadmin/issues/12080), you can create view and use it : ``` CREATE VIEW viewname AS (SELECT teghamas, MAX(arzheq) as mval, ceil(UNIX_TIMESTAMP(zhamanak)/(60 * 60)) AS timekey FROM `masnakcutyun` LEF...
MySQL parsing error in phpMyAdmin ("This type of clause was previously parsed")
[ "", "mysql", "sql", "select", "phpmyadmin", "" ]
This may have been asked and answered before, but I'm having difficulty even phrasing it as a question (hence the title). I have a databse table with is essentially ``` [EventId] INT, [FirstOccurance_Month] DATETIME, [LastOccurance_Month] DATETIME ``` With some data similar to this: ``` [EventId] [FirstOccurance_Mo...
You can use a Tally table for this task: ``` ;WITH Tally AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS i FROM (VALUES (0), (0), (0), (0), (0)) AS t1(n) CROSS JOIN (VALUES (0), (0), (0), (0), (0)) AS t2(n) ) SELECT m.EventId, DATEADD(m, t.i, FirstOccurance_Month) AS [Month] FROM Tally AS t INNER J...
One way is using recursive CTE ``` ; with rcte as ( select EventId, [Month] = FirstOccurance_Month from yourtable union all select t.EventId, [Month] = dateadd(month, 1, r.[Month]) from rcte r inner join yourtable t on r.EventId = t.EventId where r.[Month] < t.Las...
T-SQL All occurrences in a range
[ "", "sql", "sql-server", "" ]
I have the following select statement that returns exactly what I want: ``` DECLARE @result varchar(max) = '' SELECT @result += (result.Fullname + '<br/>') FROM (SELECT DISTINCT Fullname FROM Providers WHERE Status='A') as result select substring(@result, 0, len(@result) - 4) ``` The only problem is, I want the o...
You need aggregate string concatenation in SQL Server. There are already many answers on the subquery, but to save you the trouble: ``` SELECT Column AS [AColumnName], STUFF((SELECT DISTINCT '<br/>' + Fullname FROM Providers WHERE Status = 'A' FOR XML PATH (''), TYPE ...
Which Database? If you can use for xml, then something like... ``` select substring(a.innards, 0, len(a.innards) - 4) as [LenderList] from ( SELECT innards = STUFF( (SELECT DISTINCT Fullname + '</br>' FROM Providers WHERE [Status] = 'A' FOR XML PATH(''), TYPE).value('.[1]', 'nvarch...
Select statement within a select statement
[ "", "sql", "sql-server", "select", "" ]
How do I get all Mondays or Tuesdays of Previous Month? I haven't seen any example about it.
``` ;WITH CTE (X) AS ( SELECT DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0) ), CTE2(N) AS ( SELECT 0 UNION ALL SELECT 1+N FROM CTE2 WHERE N< (SELECT DATEDIFF(DD,DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0),DATEADD(MM,1,DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0))-1)) ) SELECT DATEADD(DD,N,X),DATENAME(DW,DATEADD(DD,N,X)...
You could use: ``` DECLARE @d DATE = GETDATE(); SELECT sub.prev_date FROM (SELECT @d, MONTH(DATEADD(MM, -1, @d))) AS s(d,m) CROSS APPLY ( SELECT DATEADD(D, c-1, DATEADD(MM, -1, DATEADD(DD, 1 - DAY(d),d))) AS prev_date FROM ( VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10), (11),(12),(13),(14),(...
How to get all Mondays or Tuesdays of Previous Month
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I need to copy data from one table to another. the two tables have almost the same structure, but are in different databases. i tried ``` INSERT INTO db1.public.table2( id, name, adress, lat, lng ) SELECT id, name, adress, lat lng FROM db2.public.table2; ``` wenn i try this, i get error cross dat...
This is a really straightforward task. Just use dblink for this purpose: ``` INSERT INTO t(a, b, c) SELECT a, b, c FROM dblink('host=xxx user=xxx password=xxx dbname=xxx', 'SELECT a, b, c FROM t') AS x(a integer, b integer, c integer) ``` If you need to fetch data from external database on a regular basis, it would b...
There's also another way to do it. If dblink extension is not available, it's possible to copy data directly in command line, using pipe connecting standard input and ouput: ``` psql source_database -c 'COPY table TO stdout' | psql target_database -c 'COPY table FROM stdin' ``` But this is gonna work only in postgres...
PostgreSQL copy/transfer data from one database to another
[ "", "sql", "postgresql", "copy", "cross-database", "" ]
I want to SUM a lot of rows. Is it quicker (or better practice, etc) to do Option A or Option B? **Option A** ``` SELECT [Person] SUM([Value]) AS Total FROM Database WHERE [Value] > 0 GROUP BY [Person] ``` **Option B** ``` SELECT [Person] SUM([Value]) AS Total FROM Database GROUP BY...
Well, *if you have a filtered index that exactly matches the `where` clause*, and if that index removes a significant amount of data (as in: a good chunk of the data is zeros), then definitely the first... If you *don't* have such an index: then you'll need to test it *on your specific data*, but I would probably expec...
Assuming that `Value` is always positive the 2nd query might still return less rows if there's a `Person` with all zeroes. Otherwise you should simply test actual runtime/CPU on a really large amount of rows.
Quicker with SQL to SUM 0 values or exclude them?
[ "", "sql", "t-sql", "" ]
I am new to ssrs. I want to get all the possible data for ssrs subscribed report, which are Available in ResportServer database. I have found some queries, but that does not have proper data. It only works for single report. I need list of unique subscription with it's data. If possible stored procedure is preferabl...
I have same requirement once as like you have now... See below stored procedure.. ``` CREATE PROCEDURE [dbo].[GetSubscriptionData] AS BEGIN SET NOCOUNT ON; WITH [Sub_Parameters] AS ( SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters]) FROM [Subscriptions] a ), [MySubscriptions] AS ( SELEC...
In case you need to find the sql server agent Job use this updated code ``` SET NOCOUNT ON; WITH [Sub_Parameters] AS ( SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters]) FROM [Subscriptions] a ), [MySubscriptions] AS ( SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value(...
How to get all SSRS Subscription Data using stored procedure?
[ "", "sql", "sql-server", "reporting-services", "" ]
I have an employee saved search that needs to return the internal ID of the {supervisor} field, by default it displays the employee ID (not internal ID) and the supervisors full name. thanks
Please try using formula,set value {supervisor.id}
Scroll down to the bottom of the field selection list and find "Supervisor fields...", then select "Internal ID" from the ensuing popup. This is how you do JOINs in the search UI.
NetSuite employee Saved Search needs to return employee superior internal ID
[ "", "sql", "netsuite", "" ]
I'm using PL/SQL if that matters. ``` Table = Stuff ID: FRUIT: 100 Apple 100 Grape 200 Apple 200 Orange 550 Apple 700 Orange 800 Orange 900 Grape ... ... ``` I want to list all of the Apples and their IDs that do NOT share the same ID as Orange. How do I go about doing this? The output should be...
You can do this with a subquery so you effectively pick all of the ID's for Oranges out in this subquery then pick all of the fruit which are Apples and ID's aren't in the subquery. Something like this; ``` SELECT * FROM stuff WHERE fruit = 'Apple' AND ID NOT IN (SELECT ID FROM stuff WHERE fruit = 'Orange') ```
Or you could do it using the MINUS set operator: ``` SELECT a.ID, a.FRUIT FROM STUFF a WHERE a.FRUIT = 'Apple' MINUS SELECT b.ID, 'Apple' AS FRUIT FROM STUFF b WHERE b.FRUIT = 'Orange' ``` Best of luck.
Simple SQL Query 1
[ "", "sql", "oracle", "" ]
I have two tables that have a one-many relationship, and I would like to put together a query that follows a rule to join a particular row in the 'many' table to a row in the 'one' table. user table: ``` ╔════╦══════════════╦ β•‘ id β•‘ name β•‘ ╠════╬══════════════╬ β•‘ 1 β•‘ user 1 β•‘ β•‘ 2 β•‘ user 2 β•‘ β•‘ ...
Try something like this: ``` SELECT message_id , [user_id] , name , [Text] , [date] FROM ( SELECT M.id AS message_id , U.id AS [user_id] , name , [Text] , [date] --Rank rows for each users by date , RANK() OVER(PARTITION BY M.[user_id] ORDER BY [date] DESC, M.id DESC) AS...
You can join the tables and than filter the results: ``` select tbl.name , tbl.Text from (select User.name, Messages.Text, RANK() OVER (PARTITION BY User.name ORDER BY Messages.date desc) AS rank from User inner join Messages on User.id = Messages.user_id) as tbl where rank=1 ```
SQL: filter a joined table
[ "", "sql", "" ]
If I want to know for each user how much time they spent on the intranet on a certain day, I can use a custom function - 2 examples: ``` select * from [dbo].[usertime]('2016-04-08') userid totaltime ----------------- 1 4430 2 11043 5 13045 select * from [dbo].[usertime]('2016-04-09') userid tot...
There's no need for any looping (something that should almost always be avoided in SQL). ``` SELECT T.userid, D._date, T.totaltime FROM #dates D -- Probably no need for a temporary table either... CROSS APPLY dbo.usertime(D._date) T ``` If you need to then pivot those results, then you can do that a...
It's easier to use a permanent table for the dynamic table structure due to temp table scoping. If you must use a #usertime temp table for some reason, you'll need to nest dynamic SQL, which is pretty ugly. Below is an example of how you can pivot the results from rows to columns dynamically. ``` SET NOCOUNT ON; IF ...
How do I fill a temp table iteratively and stuff() the result into columns?
[ "", "sql", "sql-server", "" ]