Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an issue with my SQL Server request:
```
SELECT *
FROM table
WHERE M.StatutMandatId =
CASE
WHEN @Mandat = '1' THEN '5'
WHEN @Mandat = '0' THEN 'IN(1,2,3,4,5)'
END
```
But I have this issue:
> Conversion failed when converting the varchar value 'IN(1,2,3)' to
> data type int.
It's not possible to u... | You can't do an `IN` like that, instead if you have to use the `CASE` do it like this:
```
SELECT *
FROM table
WHERE
CASE
WHEN @Mandat = '1' AND M.StatutMandatId = 5 THEN 1
WHEN @Mandat = '0' AND M.StatutMandatId IN(1,2,3,4,5) THEN 1
ELSE 0
END = 1
```
It probably won't be very performant, I would instea... | No, you can't create dynamic SQL like that. You could achieve the same using the follow statement though
```
SELECT *
FROM table
WHERE (M.StatutMandatId IN(1,2,3,4,5) AND @Mandat=0)
OR (M.StatutMandatId =5 AND @Mandat=1)
``` | CASE and IN in WHERE | [
"",
"sql",
"sql-server",
""
] |
I have SQL table with duplicated record but one filed is different
How can Delete duplicated record which this filed is null ?
and if two pair is null delete one
```
my table is :
id Number No
1 A25 10
2 A24 20
3 A25
4 C12
5 C12
```
---
```
new table :
id Number No
1 A25 10
2 A24 20
4 C12
5 C12
``` | ```
delete from mytable where id in(
select t1.id
from mytable t join mytable t1 on t.number=t1.number and t1.id>t.id
where (t1.no is null and t.no is not null) or (t1.no is null and t.no is null)
)
``` | Try this.
```
select *
into #temp1
from My_table
group by Number
having Count(*)>1
delete My_table
from My_table
join #temp1
on My_table.Number = #temp1.Number
where My_table.Number is null
``` | How to delete duplicated record? | [
"",
"sql",
""
] |
I have table:
* Products(ID, weight, expired, ...)
I would like to get the N first products which expired is false and sum of the weight is form `example >= 5kg`.
How could I do this query?
Thanks so much.
EDIT: it seems that I was not very clear in my question. For example I can have this products:
* p1: ID = 1,... | You can write as:
```
select top 10 * from -- top N goes here
(
SELECT *,SUM(weight) OVER (partition BY expired ORDER BY Id asc) as cumulativesum
FROM
Products
WHERE expired = 0
)T
where cumulativesum>=5
```
`DEMO` | ```
SELECT TOP 10 p.*
FROM Prodcts p
WHERE p.expired = 0
AND p.weight >= 5
```
However, currently it's not clear how you want to `sum` a single record. | How to get the first N rows where the sum is ≥ X? | [
"",
"sql",
"sql-server",
""
] |
How can I group an unknown number of rows into a single row, where the set columns determine the grouping?
I want to shift
```
Group1 Group2 Group3 Val1 Val2 Val3
===============================================
John Smith 25 1 0 0
John Smith 25 0 6 0
John ... | ```
declare @t table (group1 varchar(10),group2 varchar(20),group3 int,val1 int,val2 int,val3 int)
insert into @t (group1,group2,group3,val1,val2,val3)values ('John','Smith',25,1,0,0),
('John','Smith',25,1,6,0),
('John','Smith',25,1,0,8),
('Chris','Green',30,1,0,0),
('Chris','Green',30,1,3,0),
('Chris','Green',30,5,0,... | ```
select Group1, Group2, Group3, SUM(val1), SUM(val2), SUM(val3)
from tablename
GROUP BY Group1, Group2, Group3
``` | How can I group rows into columns with multiple values? | [
"",
"sql",
"sql-server",
"t-sql",
"grouping",
"pivot-table",
""
] |
I have a table named `route_location` like the following table:

This table is for a map. There are routes, and each route has a unique `routeID`. The routes contain locations, and the order of the locations appearing in any route is defined by `orde... | It's still unclear, but you seem to ask for logic applied to an order set: return all data **after** there was a `locationID = 11` on the same route at a previous `orderID`
```
SELECT *
FROM route_location AS rl
WHERE EXISTS
( SELECT *
FROM route_location AS rl2
WHERE rl.routeID = rl2.routeID -- on the same ro... | Try this
```
SELECT *
FROM route_location AS rl
inner join route_location AS r2
on rl.routeID = r2.routeID and rl.orderID < r2.orderID and r2.locationID = 11
``` | SQL advanced filtering | [
"",
"mysql",
"sql",
"set",
""
] |
Say I have a query that is something like this:
```
select
table1.column1,
table1.column2,
...,
case when foo.id is null then 'N/A' else sum(foo.points) end as score -- same result using ifnull()
from
table1 inner join table2 on ...
left join foo on ...
group by ...
```
Since I do a `LEFT J... | When you have different data types in the results in the case it will return a value with the data type `blob` if it can't find a common type.
Try casting the sum to a char:
```
case when foo.id is null then 'N/A' else cast(sum(foo.points) as char) end as score
``` | If you are grouping, you should really put your sum around the case, like:
`sum(case when foo.id is null then 0 else foo.points)`
..as otherwise you are summing just the row value (meaning only one value).
Also, a column should only have one data type, so either number or text, which is why you might be seeing this ... | Mysql SUM inside a CASE | [
"",
"mysql",
"sql",
""
] |
I've searched around and couldn't find an answer anywhere.
I'm querying a database that has stored numbers as a `VARCHAR2` data type.
I'm trying to find numbers that are greater than `1450000` (`where BI_SO_NBR > '1450000'`), but this doesn't bring back the results I'm expecting.
I'm assuming it's because the val... | You can try to use like this:
```
where to_number(BI_SO_NBR) > 1450000
```
Assuming you are using Oracle database. Also check [To\_Number](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions191.htm) function
**EDIT:-**
You can try this(*after OP commented that it worked*):
```
where COALESCE(TO_NUMBER(... | If the number is too long to be converted correctly to a number, and it is always an integer with no left padding of zeroes, then you can also do:
```
where length(BI_SO_NBR) > length('1450000') or
(length(BI_SO_NBR) = length('1450000') and
BI_SO_NBR > '1450000'
)
``` | SQL Query - Greater Than with Text Data Type | [
"",
"sql",
"oracle",
"varchar2",
""
] |
Not sure if this is possible on DB side, but so far I can only get this result:
Query:
```
SELECT City.city_name "City", PC.subcategory_id "Subcategory", PC.count "count" FROM products_counter PC , Cities City WHERE PC.city_id = City.city_id
+-----------+----------------+-------+
| city_name | subcategory_id | count... | You can use cross join for this.
```
SELECT c.city_name, pc.subcategory_id,
IFNULL((select `count` from products_counter where city_id = c.city_id
and subcategory_id = pc.subcategory_id),0) as 'Count'
FROM cities c CROSS JOIN products_counter pc
```
working example here - <http://sqlfiddle.com/#!9/34... | Try this.
```
select c.city_name ,
ps.subcategory_id ,
( select `count`
from products_counter
where city_id = c.city_id
and subcategory_id = ps.subcategory_id) as 'Count'
from cities c
cross join products_counter pc
``` | mysql combining data from two tables | [
"",
"mysql",
"sql",
""
] |
I currently have this over long query that I'm trying to optimize. I looked at combining subquery's but I fail to get a count for every group in one query while having my constraints.
Is it possible to slim down the following query?
```
SELECT
val_year,
spg,
SUM(val_q1) val_q1,
SUM(val_q2) val_q2,
... | You can replace the UNIONs with a single query using CASEs:
```
SELECT
val_year,
spg,
CASE WHEN val_quarter = 'Q1' THEN count_prods ELSE 0 END val_q1,
CASE WHEN val_quarter = 'Q2' THEN count_prods ELSE 0 END val_q2,
CASE WHEN val_quarter = 'Q3' THEN count_prods ELSE 0 END val_q3,
CASE WHEN val_... | It looks like a PIVOT query, so you could do all in one
```
SELECT
val_year, spg,
coalesce(q1_total, 0) as q1,
coalesce(q2_total, 0) as q2,
coalesce(q3_total, 0) as q3,
coalesce(q4_total, 0) as q4,
coalesce(q1_total, 0) + coalesce(q2_total, 0) + coalesce(q3_total, 0) + coalesce(q4_total, 0) as total
FROM
(SELECT va... | Is a combined subquery possible for this scenario? | [
"",
"sql",
"oracle",
"optimization",
"subquery",
""
] |
I have been given this task to try to detect some duplicate records in a table with a large volume of rows. The table comprises 2 joined tables. So to begin with I have:
```
select
b.event_number_id, b.tenure_number_id, a.work_start_date, a.work_stop_date, a.amount
from
MTA.mta_sow_event a, mta_tenure_event_xref b
wh... | Here's an approach based on a join of the data sets:
```
with cte_base_data as (
select
... your query here ...)
select
from cte_base_data t1 join
cte_base_data t2 on (t1.tenure_number_id = t2.tenure_number_id and
t1.work_start_date = t2.work_start_date and
... | General idea: group rows with the same values (`partition by tenure_number_id, work_start_date, work_end_date, amount`), find minimal `event_number_id` for each group and row number of `event_number_id` inside group starting from zero (using analytic functions `min` and `row_number`), then compare sum of minimal ID and... | How to find consecutive values in column | [
"",
"sql",
"oracle",
""
] |
I have a table in a SQL Server database with some columns along with
```
CreatedBy (varchar)
CreatedOn (datetime)
UpdatedBy(varchar)
UpdatedOn(datetime)
```
as standard columns. The `CreatedOn` and `CreatedBy` values are automatically populated as and when there is a new row added to this table (using default value a... | Apart from adding a trigger as mentioned by Alex K et all., you could also add a RowVersion column. This data type was previously called TimeStamp, but unfortunately the name is misleading.
This will give you the **UpdatedOn** smalldatetime timestamp, but not the UpdatedBy information.
If you want to convert the RowV... | You can add a trigger like the one below. This trigger works if multiple rows are updated are the same time. Please notes it assumes you have added an identity column to your source table.
```
CREATE TRIGGER [dbo].UpdateTrans ON [dbo].YourTable
FOR UPDATE
AS
SET NOCOUNT ON
UPDATE yt
SET UpdatedBy = SU... | Automatically update column values in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
In a QUERY I've SELECT a specific product data from Book Table. Like title, author, year, etc. I wanna get all it's authors, but it's **only showing the** **first one**.
Product Table:
```
produto
idproduto
sku
titulo
others not important
```
Author Table:
```
autor
id_autor
nome_autor
```
Relati... | Thanks for all patient with me, as I'm learning I was really lost.
Here is the completed result for what I need, and it's working as expected.
Much more simple than before.
This code gets all authors from related product and shows as Author 1, Author 2, Author 3...
```
"SELECT
....get stuff...
... | I don't believe it is wrong but your sql is a little strange in mixing the join styles. Can I suggest this:
```
SELECT
p.titulo AS titulo, p.imgprod AS imgprod, p.marca AS idmarca, p.sku AS sku,
p.prodcateg AS prodcateg, p.ano AS ano, p.titeng AS titeng,
p.codbarra AS codbarra, p.desc AS descricao, // product i... | How query all results in a Relational Table? | [
"",
"mysql",
"sql",
"select",
"foreign-key-relationship",
""
] |
Using SQL Server 2014
I have a table with four fields. Each record contains a separate donation. It's possible for two separate donations from the same Donor to have the same amount and even the same date (say they gave the same amount twice on a given day - rare but it happens).
I'd like to return a set that has ful... | Use ROW\_NUMBER to rank your records, so that the records you want get row number 1:
```
select *
from
(
select
donations1.*,
row_number() over (partition by donoridnumber order by amount desc, transactiondate desc, idnumber desc) as rn
from donations1
) donations
where rn = 1;
``` | You can do this with the `ROW_NUMBER()` function:
```
;with cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY DonorIDNumber ORDER BY Amount DESC, TransactionDate DESC, IDNumber DESC) AS RN
FROM Donations1
)
SELECT *
FROM cte
WHERE RN = 1
```
The `ROW_NUMBER()` function assigns a number to e... | Select the MAX Record with tie breaking logic | [
"",
"sql",
"t-sql",
""
] |
I get an incorrect syntax near '.' and can't seem to identify why in the following code:
```
select
o.object_id,
(select top 1 Zone from dbo.getzone(o.object_id)) as Zone from object as o
```
getzone is a table-valued Function that works perfectly when I reference it directly, or if I put a specific object\_id in, b... | You can't do that. You need to have a scalar version that returns only one result. It can be just a wrapper script if you want. Something like this:
```
CREATE FUNCTION [dbo].[getSingleZone](@object_id varchar(20))
RETURNS varchar(20)
AS
BEGIN
DECLARE @Zone varchar(20)
select @Zone = max(Zone) from dbo.getzone(@object... | Fix your alias
```
select o.object_id,
(select top 1 Zone from dbo.getzone(o.object_id)) as Zone
from object AS o
``` | Transact SQL Subquery calling a function incorrect syntax | [
"",
"sql",
"sql-server",
"t-sql",
"syntax-error",
""
] |
I'm currently working on a sample script which allows me to calculate the sum of the previous two rows and the current row. However, I would like to make the number '2' as a variable. I've tried declaring a variable, or directly casting in the query, yet a syntax error always pops up. Is there a possible solution?
```... | ```
DECLARE @test VARCHAR = 1
DECLARE @sqlCommand VARCHAR(1000)
DECLARE @myTable TABLE (myValue INT)
INSERT INTO @myTable ( myValue ) VALUES ( 5)
INSERT INTO @myTable ( myValue ) VALUES ( 6)
INSERT INTO @myTable ( myValue ) VALUES ( 7)
INSERT INTO @myTable ( myValue ) VALUES ( 8)
INSERT INTO @myTable ( myValue ) ... | You can try something like this which does not use dynamic SQL.
```
DECLARE @myTable TABLE (myValue INT)
INSERT INTO @myTable ( myValue ) VALUES ( 5)
INSERT INTO @myTable ( myValue ) VALUES ( 6)
INSERT INTO @myTable ( myValue ) VALUES ( 7)
INSERT INTO @myTable ( myValue ) VALUES ( 8)
INSERT INTO @myTable ( myVal... | Dynamic row range when calculating moving sum/average using window functions (SQL Server) | [
"",
"sql",
"sql-server",
"t-sql",
"window-functions",
""
] |
I have a table with multiple entries. One entry consists of start Datetime and end datetime.
I want to find clusters of entries in such way that:
If an entry starts before the prior entry ends then both are part of the cluster.
It is some kind of overlapping problem.
Example:
```
id start en... | Ok here is some solution with recursive cte:
```
CREATE TABLE t
(
id INT,
s DATE,
e DATE
);
INSERT INTO t
VALUES (1, '20070411', '20070511'),
(2, '20070613', '20090721'),
(3, '20071126', '20071211'),
(4, '20080214', '20100223');
WITH cte AS (
SELECT id, s, e, id AS rid, s AS rs... | Try this...
```
select a.id ,a.start,a.end,b.id,b.start,b.end
from tab a
cross join tab b
where a.start between b.start and b.end
order by a.start, a.end
```
We will have to check each row against all other rows, just like using a loop and an inner loop. for this purpose we do a cross join.
Then we will check t... | Find clusters of time intervals | [
"",
"sql",
"sql-server",
"group-by",
"lead",
""
] |
I have a table in db2 that I want to sort. The table has four columns.
The data looks like:
```
KEY Type GROUP_ID SpecialType
2 T02 700 S
2 T01 500 R
1 T02 300 B
2 T02 600 S
1 T02 400 S
2 T02 700 B
1 T01 400 R
1 T... | This should return the list in the order you provided. It includes an analytic function in the sort which counts the number of times 'R' is included in each GroupId in order to have those groupIds listed first.
```
SELECT
t.KeyId,
t.TypeName,
t.GroupId,
t.SpecialType
FROM @Table t
ORDER BY
KeyId,
... | You're almost there.
Try `select * from myTable ORDER BY KEY, CASE WHEN SPECIALTYPE = 'R' THEN 1 ELSE 2 END, GROUP_ID` | How can I sort the data in a table over four columns? | [
"",
"sql",
"db2",
""
] |
I tried to order by Integer but it seemed that it order by the larger to the smaller number but it order by 2-digit then 3-digit
sc is the score i need to order
Code i used
```
SELECT * FROM `users` ORDER BY `sc` DESC
```
The result are :
47
3
102 | You may use silent conversion to integer as
```
select * from users order by sc+0 desc
``` | Looks like datetype of `sc` is char/varchar. You have to [cast](https://dev.mysql.com/doc/refman/5.0/en/cast-functions.html) it to an integer:
```
SELECT * FROM `users` ORDER BY cast(`sc` as UNSIGNED) DESC
``` | Wrong OrderBy in Sql query ordered in opposite way | [
"",
"mysql",
"sql",
""
] |
I have table:
```
+-------+-------+------+----------+
| Name | Price | Url | Adress |
+-------+-------+------+----------+
| John | Smith | blah | London 1 |
+-------+-------+------+----------+
| John | Smith | blah | London 1 |
+-------+-------+------+----------+
| Jenny | Cole | blah | Prague 1 |
+-------+----... | ```
;WITH C AS(
SELECT 'John' AS Name , 'Smith' AS Price , 'blah' AS URL , 'London 1' AS Address
UNION ALL
SELECT 'John' AS Name , 'Smith' AS Price , 'blah' AS URL , 'London 1' AS Address
UNION ALL
SELECT 'Jenny','Cole' ,'blah' ,'Prague 1'
UNION ALL
SELECT 'Jenny','Cole' ,'blah' ,'Prague 2'
... | ```
Select * From your_table_name
Group By Name, Price, Url, Adress
Having Count(*) = 1;
``` | I want to get only NON-duplicate row in sqlite | [
"",
"sql",
"sqlite",
"duplicates",
"unique",
""
] |
i have a condition in where clause like:
```
LocationId=IFNULL(LocId,LocationId)
```
here LocId is NULL so by IFNUll its returning LocationId which is Also Null in this case this query is not returning anything.
Please tell me the solution for it. | You could use the [null safe comparison](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to) operator:
```
LocationId <=> IFNULL(LocId, LocationId)
```
The difference between the regular `=` operator is that the `null` value is not treated as special, e.g. if both left and right hand ... | mysql NULL is not equal to NULL, check here <https://dev.mysql.com/doc/refman/5.0/en/working-with-null.html>
> Because the result of any arithmetic comparison with NULL is also
> NULL, you cannot obtain any meaningful results from such comparisons.
>
> In MySQL, 0 or NULL means false and anything else means true. The
... | Comparing NULL value in MYSql | [
"",
"mysql",
"sql",
""
] |
I want to filter rows from a single table between two datetimes and those filtered rows should come under a single date, for example
i want to get all the rows between
(16 mar 2015 6AM) and (17 mar 2015 6AM) datetimes as (17 mar 2015) date and
(17 mar 2015 6AM) and (18 mar 2015 6AM) datetimes as (18 mar 2015) date and... | You can calculate FetchedOn based on the time part of the LogTime field:
```
SELECT B.*, dateadd(day, (iif(cast(LogTime as time) < '06:00:00', 0, 1)), cast(LogTime as date)) + cast('06:00:00' as datetime) as FetchedOn
from Biometric B
ORDER BY FetchedOn DESC, LogTime
```
**Update:**
Simpler formula to calculate Fet... | Here is some code. The Idea is to get all possible distinct ranges from test data. This is what CTE returns:
```
st ed
2015-03-15 06:00:00.000 2015-03-16 06:00:00.000
2015-03-16 06:00:00.000 2015-03-17 06:00:00.000
2015-03-17 06:00:00.000 2015-03-18 06:00:00.000
2015-03-18 06:00:00.000 2015-03-19 ... | how to filter rows between dates without using loop in tsql | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014",
""
] |
I have the following tables:
* **ROUTE (id, train\_number, station\_id, arrival\_time, departure\_time)**
* **SERVICE (train\_number, train\_name)**
* **STATION (id, name, city)**
A row in ROUTE table will contain the train number, it's arrival and departure time (or one of these two if the station is the first/last ... | Setup:
```
CREATE TABLE STATION (
id NUMBER PRIMARY KEY,
name VARCHAR2(20),
city VARCHAR2(20)
);
CREATE TABLE SERVICE (
train_number NUMBER PRIMARY KEY,
train_name VARCHAR2(20)
);
CREATE TABLE ROUTE (
id NUMBER PRIMARY KEY,
train_number NUMBER REFERENCES SERVICE( train_nu... | If there are no branches in the paths then the problem is simply to order the stations by arrival or departure time:
```
SELECT s.station_id, name FROM ROUTE r INNER JOIN STATION s r.station_id = s.station_id ON WHERE train_number = 1 ORDER BY departure_time
``` | SQL query - getting arrival and departure stations based on time table | [
"",
"sql",
"oracle",
""
] |
I have a table which can have a maximum of 5 rows and minimum 1 row. Now I need to store these rows in different variable like `@v1,@v2,@v3,@v4,@v5`. How can I do it?
The Table has only 1 column `custid`.
```
CustId
100
200
300
400
```
If the table contain only 1 row then `@v1` should have that value and rest can be... | You can use the following query:
```
SELECT @v1 = MAX(CASE WHEN rn = 1 THEN CustId END),
@v2 = MAX(CASE WHEN rn = 2 THEN CustId END),
@v3 = MAX(CASE WHEN rn = 3 THEN CustId END),
@v4 = MAX(CASE WHEN rn = 4 THEN CustId END),
@v5 = MAX(CASE WHEN rn = 5 THEN CustId END)
FROM (
SELECT CustId... | If you have SQL Server 2012 or newer, you can try [LAG()](https://msdn.microsoft.com/en-us/library/hh231256.aspx) function.
```
SELECT
@v1 = custID
, @v2 = LAG(custID, 1) OVER (ORDER BY custID DESC)
, @v3 = LAG(custID, 2) OVER (ORDER BY custID DESC)
, @v4 = LAG(custID, 3) OVER (ORDER BY custID DESC)
, @v5... | How to store fixed row values in a variable - SQL server | [
"",
"sql",
"sql-server",
""
] |
I'm having an issue returning a value when the other values are `NULL`.
My SQL is as follows:
```
select id
, CASE WHEN value1 IS NOT NULL THEN value1
WHEN value1 IS NULL THEN value2
WHEN value1 IS NULL AND value2 IS NULL THEN value 3
END
from ('table containing these values')
```
It successfull... | I think you should just use `coalesce`:
```
select coalesce(value1, value2, value3)
```
The correct form for your `case` is:
```
SELECT (CASE WHEN value1 IS NOT NULL THEN value1
WHEN value2 IS NOT NULL THEN value2
ELSE value3
END)
``` | The third case is never used, because the first and second cases are each others complements, so they cover all possibilities.
Change the order, so that you check the third case before the second:
```
select id
, CASE WHEN value1 IS NOT NULL THEN value1
WHEN value1 IS NULL AND value2 IS NULL THEN value3
... | Nulls within a CASE Statement | [
"",
"sql",
"case",
"case-when",
""
] |
I have 3 tables :

This a part of my query to join two tables (tbl\_ads and tbl\_inf\_adstate):
```
@state_id int=NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT a.Id
,a.ad_title
,a.ad_brief
,a.ad_pic
... | ```
Try this one :
SELECT Id
,ad_title
,ad_brief
,ad_pic
INTO #Results
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.ID) AS rn, a.Id
,a.ad_title
,a.ad_brief
,a.ad_pic
,a.ad_type
FROM [tbl_ads] a JOIN tbl_inf_adstate b ON a.Id=b.ad_id
WHERE... | Just distinguish them with `DISTINCT` keyword:
```
SELECT DISTINCT a.Id
,a.ad_title
,a.ad_brief
,a.ad_pic
INTO #Results
FROM [tbl_ads] a JOIN tbl_inf_adstate b ON a.Id=b.ad_id
WHERE (b.state_id=@state_id OR @state_id IS NULL)
AND a.ad_is_accept=1
AND a.ad_is_show=1
... | Joining two tables with GROUP BY | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have table `Foo` like:
```
id,
bar_1,
bar_2,
bar_3
```
`bar1, bar2, bar3` could contain foreign key (integer) or `null`. I want to select all rows from `Foo`, where ids `2, 4` (both) are present in any two of `bar1, bar2, bar3`.
Simple way would be to make lot of `OR`'s, but I believe there's simplier way.
I thou... | Well, almost :-)
```
SELECT * FROM foo
WHERE 2 IN (bar_1, bar_2, bar_3)
AND 4 IN (bar_1, bar_2, bar_3);
``` | ```
SELECT * FROM foo WHERE bar_1 IN (2,4) OR bar_2 IN (2,4) OR bar_3 IN (2,4)
``` | MySQL - cast columns to array and use IN statement on it | [
"",
"mysql",
"sql",
""
] |
```
SELECT rollID
FROM [dbo].[dbo_Roll] a
INNER JOIN [evt_Building Permits] b
ON LEFT(a.rollnumber, LEN(a.rollnumber)-4) = b.rollnumber COLLATE DATABASE_DEFAULT
```
And I want to update the result to this table `[evt_Building Permits].roll_id = [dbo].[dbo_Roll].rollID`?
How can I attain this? | Try this
```
UPDATE b
SET b.roll_id = a.rollID
FROM
[dbo].[dbo_Roll] a
INNER JOIN
[evt_Building Permits] b
ON LEFT(a.rollnumber, LEN(a.rollnumber)-4) = b.rollnumber COLLATE DATABASE_DEFAULT
``` | Something like this.
```
update b
set rollID = a.rollID
from [dbo].[dbo_Roll] a
inner join [evt_Building Permits] b
on LEFT(a.rollnumber, LEN(a.rollnumber)-4) = b.rollnumber COLLATE DATABASE_DEFAULT
``` | Update statement with select to another table | [
"",
"sql",
"sql-server",
"t-sql",
"sql-update",
""
] |
I have a table called location which has one to many relations with rates table.
The following is a description of the rate table:
```
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----... | This question appears about once a week, just with different data. My latest answer is [here](https://stackoverflow.com/questions/29692750/return-only-most-recent-entry-per-id/29738276#29738276).
Your query will look like this:
```
select l.*, r.price
from location l
join rate r
on r.Location_ID = l.I... | I'll take a guess at your data structure. I will guess that you have pricing for many locations. I will guess that you have both past and future pricing for each location.
So, if you want the so-called "current" price for each location, this query gets it. This will give back one row for each distinct location with th... | Get Latest Price from Location table in SQL | [
"",
"mysql",
"sql",
""
] |
Hi. Below i have written query to retrieve total-hours, last-month-total-hours and current-month-total-hours. All these are calculating from hours column of time\_entries table and spent\_on column of same table. Sorry if table formatting is not good.
Following three query is giving correct result.
Query#1
```
selec... | You may run the query with joins and no aggregations to see how those joins are working when used together and why that will lead to wrong results.
You can achieve the desired result by using one join and moving the criteria to aggregate calculations:
```
select p.name,
FORMAT(sum(te.hours), 2) AS totalhours,
FORMAT... | You could dump the data from the queries into temporary tables making sure the project is in each and then query those based on the project to pull it all together | How to retrieve sql results with different calculated values for same column with join and group by? | [
"",
"mysql",
"sql",
""
] |
When i try to divide the first nested select statement by the count of a column, the query returns a zero. When I replace the "/" with a ",", I receive two different numbers so the return value shouldn't be a zero. Could this have something to do with there being zeros in the data set? Any help would be appreciated
``... | There is no need for two selects, simply use a Case statement for count.
Also I think you are trying to avoid a Zero `0` in divisor.
Also for date parameters pass date values as ANSI Date i.e `YYYYMMDD`
```
select count(CASE WHEN iscoded=1 THEN iscoded END) * 1.00
/ NULLIF(count(iscoded), 0)
from ope.ope.vwe... | ```
declare @hospitalfk int;
set @hospitalfk='1335'
declare @startdate date;
set @startdate='03/01/2014'
declare @enddate date;
set @enddate='02/28/2015'
declare @reportname varchar(50);
set @reportname='%Medicaid Billable Report%'
declare @metasectionname varchar(100);
set @metasectionname='Medicaid Primary'
sele... | Query returning a zero when dividing in the select statement | [
"",
"sql",
"sql-server",
""
] |
What I am asking is this query-
```
select * from emp order by sal + 2000;
```
Gives exactly same result as this query-
```
select * from emp order by sal;
```
Then what is the difference in terms of calculation?
What does `order by sal + 2000` mean?
How this influences the result? | **Those queries do not give the same results if SAL is stored as a string.**
```
create table emp as
select '90000' sal from dual union all
select '100000' sal from dual union all
select '110000' sal from dual;
select * from emp order by sal;
SAL
---
100000
110000
90000
select * from emp order by sal + 2000;
SAL
... | Consider the following result set from your query, sorted (by default) in ascending order by the salary:
```
select name, salary from emp order by sal;
+------+--------+
| name | salary |
+------+--------+
| John | 10000 |
| Mike | 15000 |
| Joe | 30000 |
+------+--------+
```
Here is the result set using `ORDER... | What does it mean if I add something with some column in Order by clause? | [
"",
"sql",
"oracle",
""
] |
Here's the query which works well:
```
select MIN(dbo.GetDiscountedPrice(P.AutoID))
FROM Product P
where P.AutoID in (2910,2912,2820)
```
It returns the cheapest price among 2910,2912 and 2820 (AutoID is the primary key)
BUT this query returns an error:
```
select MIN(dbo.GetDiscountedPrice(P.AutoID))
FROM Product ... | If statement
`where P.AutoID in (SELECT AutoID FROM Product WHERE Category=2)`
fails but
`where P.AutoID in (2910,2912,2820)`
works, then the problem is definitely in function itself, because first statement can not produce mentioned error. I.e. first statement returns different set then second statement and data p... | try this code (i did not check it)-
```
DECLARE @tbl TABLE (id int IDENTITY(1,1),AutoID int)
INSERT INTO @tbl
SELECT AutoID FROM Product WHERE Category=2
DECLARE @x int=1
DECLARE @y int=1
WHILE @x <= (SELECT count (*) from @tbl)
BEGIN
set @y=(select AutoID FROM @tbl WHERE id=@x)
select MIN(dbo.GetDiscountedPrice... | SQL Server Scalar Function with "IN" Getting Subquery Returned more than 1 Error | [
"",
"sql",
"sql-server",
""
] |
I have two tables, employee records (id, firstName, lastName) and violation (violatorId, supervisorId).
My query pulls a list of violators and supervisors. I would like to rather than displaying the id of the person, display their first and last name. So this is my query so far...
```
SELECT
emp.firstName as vFirstN... | ```
SELECT
e1.firstName AS violatorFirstName,
e1.lastName AS violatorLastName,
e2.firstName AS supervisorFirstName,
e2.lastName AS supervisorLastName
FROM violator v
LEFT JOIN employee e1 ON v.violatorId = e1.id
LEFT JOIN employee e2 ON v. supervisorId = e2.id
``` | You need to join once more to `employee`:
```
SELECT emp.firstName AS vFirstName, emp.lastName AS vLastName,
v.violatorId AS vId, v.supervisorId AS sId,
s.firstName AS sFirstName, s.lastName AS sLastName
FROM employee emp
LEFT JOIN violator v ON v.violatorId = emp.id
LEFT JOIN employee s ON v.supervisorI... | SQL Query pulling same field with different values | [
"",
"mysql",
"sql",
""
] |
I have a simple MYSQL table with 2 columns:
```
id | status
1 | b
```
`status` is `ENUM('a','b','c')`
I want to update this row so that if:
1) The current status is `c` then new value `b`
2) The current status is `b` then new value `a`
3) The current status is `a` then do nothing
I tried the following but of c... | ```
UPDATE tablename SET status = case status when 'b' then 'a'
when 'c' then 'b' end
WHERE id = '1' and status <> 'a'
```
(`<> 'a'` in `WHERE` is to avoid 'a'-rows in transaction.) | Try like this:
```
update table_name
set status = case when status = 'c' then 'b'
when status = 'b' then 'a'
when status = 'a' then 'a'
end
where id = 1;
``` | mysql update row to previous enum value | [
"",
"mysql",
"sql",
"enums",
""
] |
How can I update 2 of my rows randomly from 4 other rows that have this condition `F01=1 And F02=1` in a table with 5 rows?
and i want the number of that rows that changed after the execute of the code.
like this
```
ID F01 F02 ID F01 F02
1 0 1 1 0 1
2 1 1 ... | ```
;WITH CTE AS
(
SELECT TOP 30 *
FROM TableName
WHERE F01 = 1 AND F02 = 1
ORDER BY NEWID()
)
UPDATE CTE
SET ColumnName = 'NewValue'
```
OR
```
UPDATE t
SET t.ColumnName = 'NewValue'
FROM (
SELECT TOP 30 *
FROM TableName
WHERE F01 = 1 AND F02 = 1
ORDER BY NEWID()
)t
```
## Edit
If... | ```
DECLARE @ids AS TABLE(id INT)
INSERT INTO @ids(id) SELECT TOP(2) ID FROM Chess.dbo.Sheet1$ WHERE F01 = 1 AND F02 = 1 ORDER BY NEWID()
UPDATE Chess.dbo.Sheet1$ SET F01 = 'A'
WHERE ID IN (
SELECT id
FROM @ids)
``` | How I can update 2 of my rows randomly, that have this codition F01=1 And F03=1 in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I posted a question at MSDN (Brazilian) site. My problem is that I want to make a select at a table that returns a first and last number (from a column) WITHOUT INTERRUPTION and WITHOUT CHANGES on other columns related on the search.
**QUESTION UPDATE (2015-04-23)**
I've updated my own post on MSDN as on this [link](... | I've wrote a query and got the results i was trying to find. I still don't like it very much as i think it will have a big cost on the database to run it, and i'd like to find one simpler. But anyway, the "problem" it self is resolved.
The resulting query is writen as follows:
```
SELECT
[Pre].[pfPrefix],
[Pro].[prId... | This is not going to be a simple query using a `GROUP BY`.
For simplicity and to show the basic idea I assume `Entries` table just got two columns: `enNumber` and `enProduct`. You can add all other columns and criteria later.
```
CREATE TABLE [Entries](
[enNumber] [int] NOT NULL,
[enProduct] [int] NOT NULL,
... | SQL Server SELECT Sequential Data, Breaking Lines at any Column Diference | [
"",
"sql",
"sql-server-2008",
""
] |
Tables in my db:
```
CREATE TABLE items (
id serial NOT NULL,
user_id integer NOT NULL,
status smallint
);
CREATE TABLE phones (
phone character varying,
users integer[]
);
```
My Query for find phone numbers where status = 1:
```
SELECT phones.phone, COUNT(*) AS "count"
FROM phones,items
WHERE phones.p... | It's a bit tricky to create non-existing rows. (There are billions of them, at least...)
Do a `UNION ALL` with a select providing the result you want if that phone no doesn't exist.
```
<current query>
UNION ALL
select '8985545444',0
from one_row_table where not exists (select 1 from phones
... | You shouldn't do that in the query. However it is rather easy to do it if you want to:
```
WITH phone_seek AS(
SELECT '8985545444' AS phone
UNION ALL
SELECT '7924445588 '
)
SELECT phone_seek.phone, COUNT(items.id) AS "count"
FROM
phones_seek
JOIN phones
ON phones_seek.phone = phones.phones
CROSS J... | SELECT COUNT(*) GROUP BY out zero rows | [
"",
"sql",
"database",
"postgresql",
""
] |
Okay so I have a table and in one column I have some data and the second column the average of the data. Example
```
id|Data|avg
1 |20 |20
2 |4 |12
3 |18 |14
```
How do I populate the avg column on insert with the running average of the Data column using T-SQL?
EDIT: Sorry guys, this was actually a stupid mistak... | SQL Server <=2008 doesn't have the `OVER(ORDER BY ...)` clause for aggregate functions.
```
CREATE TRIGGER trg_running_avg ON myTable
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
UPDATE old
SET avg = new_avg
FROM myTable old
CROSS APPLY (
SELECT AVG(Data) AS new_avg FROM myTable WHERE ID <= old.ID
) new
--S... | On insert, assuming `id` is an identity and you are just putting in `data`:
```
insert into table t(id, data, avg)
select @data, @data * (1.0 / n) + avg * (n - 1.0)/n
from (select count(*) as cnt, avg(data) as avg
from t
) t;
```
In SQL Server 2012+, it is easy enough just to get it on outp... | Get the running average of a column in T-SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have the following table in Postgres that has overlapping data in the two columns `a_sno` and `b_sno`.
```
create table data
( a_sno integer not null,
b_sno integer not null,
PRIMARY KEY (a_sno,b_sno)
);
insert into data (a_sno,b_sno) values
( 4, 5 )
, ( 5, 4 )
, ( 5, 6 )
, ( 6, 5 )
, ( 6, 7 )
, ( 7, 6 )
, ... | Assuming that all pairs exists in their mirrored combination as well `(4,5)` and `(5,4)`. But the following solutions work without mirrored dupes just as well.
### Simple case
All connections can be lined up in a **single ascending sequence** and complications like I added in the [fiddle](http://sqlfiddle.com/#!15/55... | I want to say another way, it may be useful, you can do it in 2 steps:
**1.** take the `max(sno)` per each group:
```
select q.sno,
row_number() over(order by q.sno) gn
from(
select distinct d.a_sno sno
from data d
where not exists (
select b_sno
from data
where b_sno=d.a_sn... | SQL grouping interescting/overlapping rows | [
"",
"sql",
"postgresql",
"common-table-expression",
"recursive-query",
""
] |
I have the following code which gives me production dates and production volumes for a thirty day period.
```
select
(case when trunc(so.revised_due_date) <= trunc(sysdate)
then trunc(sysdate) else trunc(so.revised_due_date) end) due_date,
(case
when (case when sp.pr_typ in ('VV','VD') then 'DVD' when sp.p... | You can get the 30-day period from `SYSDATE` as follows (I assume you want to include `SYSDATE`?):
```
WITH mydates AS (
SELECT TRUNC(SYSDATE) - 1 + LEVEL AS due_date FROM dual
CONNECT BY LEVEL <= 31
)
```
Then use the above to do a `LEFT JOIN` with your query (perhaps not a bad idea to put your query in a CTE... | what you can do is this :
creating a new table with all the days you need .
```
WITH DAYS AS
(SELECT TRUNC(SYSDATE) - ROWNUM DDD
FROM ALL_OBJECTS
WHERE ROWNUM < 365)
SELECT
DAYS.DDD
FROM
DAYS;
```
then full outer join between thoes table :
```
select DUE_DATE , CD_OF_VOLUME , DDD
from (
select
(ca... | ORACLE SQL: Fill in missing dates | [
"",
"sql",
"oracle",
""
] |
This question is a bit vague and I do apologize, hopefully the example below will clear it up. It's a fairly elementary question, I just can't seem to quite find the right solution with my very limited knowledge and SQL relevant vocabulary
There is a table with people,
```
create table People (
id integer,
... | You can join the tables and select both fields like this:
```
SELECT p.name, p.id
FROM People p
JOIN Works_for wf ON (p.id = wf.worker)
GROUP BY id
HAVING COUNT(wf.worker) > 20;
```
[sqlfiddle](http://sqlfiddle.com/#!15/bd2da/6/0) | ```
SELECT worker,name
FROM Works_for join People on worker=id
GROUP BY worker,name
HAVING COUNT(employer) > 20;
```
<http://sqlfiddle.com/#!15/e03e3/1>
There will be no 20 but just 3 records but I think it's enough as a demo | Use id values from one query, to corresponding column with same id in another table | [
"",
"sql",
"postgresql",
""
] |
if a table has many rows and each row has many columns which query is faster?
If the value of the column is within {1,2,3,4}
```
SELECT * FROM table t WHERE t.column1<>3
```
Or
```
SELECT * FROM table t WHERE t.column1 in {1,2,4}
```
Is it 3 compares vs 1 compare in these two cases? | In Oracle, it would make a huge difference if you have an **INDEX**. You could make a small test case, and check the explain plan for each statement.
* **CASE# 1 : Without an Index**
**Setup**
For demo purpose, I am creating a small table from scott.emp table with 4 rows.
```
SQL> CREATE TABLE t AS SELECT * FROM em... | They are different. The first selects all records which don't have an ID of 3 whereas the second selects all which are 1, 2 or 4. So for example the record with ID = 5 is not included.
So performance should not be the reason to choose one query over the other.
Either you have millions of records in this table, then th... | which query is optimal id<>3 or id in {1,2,4} | [
"",
"mysql",
"sql",
"sql-server",
"oracle",
""
] |
I am having two Drop Down list Country and state both list are filled from database. In Drop Down list for states I want to add "Others" at the end of the list. I tried adding "Others" from database but when I use order by Name to show name of states in alphabetic order in my Drop Down List even "Other" gets rearranged... | You need to ensure that `AppendDataBoundItems` is set to true.
Then items can be added after the data source like:
```
ddl.AppendDataBoundItems = true;
ddl.DataSource = CreateDataSource();
ddl.DataTextField="TextField";
ddl.DataValueField="ValueField";
ddl.DataBind();
ddl.Items.Add("Static value here....");
``` | Yes, you can set static value with datasource in the dropdown list. You need to do following steps:
1. Select properties of dropdownlist, and find AppendDataBoundItems and set AppendDataBoundItems = true.
2. After binding the dropdown list, add following line of code ddl.Items.Add("Others") in vb.net
3. Also order by ... | Can we set static value at the end of Dropdown list? | [
"",
"sql",
"asp.net",
"sql-server",
"t-sql",
""
] |
I'm trying to join three tables. But I get this error
```
Syntax error(missing operator) in query expression STUDENTAI.mėgstamiausia_laida = TV_LAIDOS.id
LEFT JOIN MIESTAI
ON STUDENTAI.kilme = MIESTAI.koda'.
```
Here is my code
```
SELECT MIESTAI.pavadinimas, TV_LAIDOS.pavadinimas
FRO... | This query:
```
SELECT MIESTAI.pavadinimas, TV_LAIDOS.pavadinimas
FROM STUDENTAI LEFT JOIN
TV_LAIDOS
ON STUDENTAI.mėgstamiausia_laida = TV_LAIDOS.id LEFT JOIN
MIESTAI
ON STUDENTAI.kilme = MIESTAI.kodas
WHERE STUDENTAI.ugis > 190;
```
Looks structurally correct for any database . . . except MS Acce... | This column name looks special:
```
STUDENTAI.mėgstamiausia_laida
```
It ran on my MySQL if I enclosed it in ``` `` ```, i.e.
```
SELECT MIESTAI.pavadinimas, TV_LAIDOS.pavadinimas
FROM STUDENTAI
LEFT JOIN TV_LAIDOS
ON STUDENTAI.`mėgstamiausia_laida` = TV_LAIDOS.id
LEFT JOIN MIESTAI
ON STUDENTAI.kilme =... | SQL syntax error JOIN three tables | [
"",
"sql",
"ms-access",
"left-join",
""
] |
I'm trying to use an `INNER JOIN` in SQL to show a column from one table into another. Here is the query that I'm using:
```
SELECT *
FROM Person.BusinessEntity
INNER JOIN HumanResources.Employee ON Person.BusinessEntity.BusinessEntityID = HumanResources.Employee.JobTitle
```
When I execute this, I get an error:
> ... | As you are trying to join to columns with different data types you are forcing the database to make an implicit conversion which it can't do in this case. What you want to do is to join the tables on the keys the share (which would be BusinessEntityID in this case).
The table and column names look familiar and I'm gue... | I think type of column BusinessEntityID is INT while the type of column JobTitle is NVARCHAR. So this:
```
ON Person.BusinessEntity.BusinessEntityID = HumanResources.Employee.JobTitle
```
is equals to:
```
ON 1 = 'Chief...Officer'
```
And you can't compare an int with a NVARCHAR, both must be the same type. | INNER JOIN SQL query conversion nvarchar value to int | [
"",
"sql",
""
] |
I've created a script that getting a total of sales in the month that's declared by the user and grouping in weekly. But the problem is the total is exceeding in my declared date range. Because the month declared is not dividend in 7(This is the number of days in a week). And now I want to get the result based only in ... | Here is your desired result with little amendments in your query.
```
declare @starttime datetime
```
`declare @endtime datetime
declare @time datetime
Set @starttime = '2014-10-01'
Set @endtime = '2014-10-31'`
`while @endtime > @starttime
begin
print @starttime
set @time = DATEADD(DAY, 6,@starttime)
If @time<@endti... | ```
DECLARE @starttime date
,@endtime date
,@xendtime date
Set @starttime = '2014-10-01'
Set @endtime = '2014-10-31'
while @endtime > @starttime
begin
set @xendtime = CASE WHEN DATEADD(DAY, 6,@starttime) >= @endtime THEN @endtime ELSE DATEADD(DAY, 6,@starttime) END
SELECT @starttime, @xendtime
set @star... | How to get the result of data from sql by month and divided into weeks | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am trying to subtract to date from each other
The question says that I have to create a query to display the orders that were not shipped within 30 days of ordering.
Here is my trying:
```
select orderno
from orders
where 30> (select datediff(dd,s.ship_date,o.odate )
from o.orders,s.shipment);
```
T... | Here is one method, using Oracle syntax:
```
select o.orderno
from orders o
where 30 > (select o.date - s.ship_date
from shipment s
where s.orderno = o.orderno
);
```
Note the correlation clause in the subquery, but each table is only mentioned once.
The problem that you have is th... | You'd be wanting something along the lines of:
```
select ...
from orders o
where not exists (
select null
from shipments s
where s.orderno = o.orderno
and s.ship_date <= (o.odate + 30))
```
Date arithmetic is pretty easy if you just want a difference in days, as you can... | Oracle find whether a corresponding record exists within a number of days | [
"",
"sql",
"oracle",
"date-arithmetic",
""
] |
I've been trying to convert a mySQL query in my Rails application to use Postgres Syntax and have been pouring over the Postgres documentation, specifically looking at the differences between conditionals. The query is:
```
Story.select('*', 'IF (views.id is null, 0, 1) as viewed')
.join('left join views on(
... | `EXISTS(...)` yields a boolean, which solves the NULL case quite elegantly:
```
select s.*
, EXISTS (select 42 from views v
where v.story_id = s.id
and v.user_id = 1) as viewed
from stories s
where 1=1
;
```
If you want to use the `viewed` column in an `ORDER BY` clause, you'll have to pus... | Based on the error:
**wrong number of arguments (2 for 0..1)**
Rails (no postgres) is telling you that some method is receiving two arguments but the method only supports or none arguments or only one argument.
Looking into the code, the only two methods where you are sending two arguments are `select` and `join` so... | converting a conditional MySQL query syntax to Postgres in my Rails application | [
"",
"mysql",
"sql",
"ruby-on-rails",
"postgresql",
"activerecord",
""
] |
This may be too much of an opinion-based question but here goes:
I've found an interesting quirk with Entity Framework and database migrations. It seems that whenever we create a foreign key it also creates an index on that column.
I read this SO question: [Entity Framework Code First Foreign Key adding Index as well... | In EF Code First, the general reason why you would model a foreign key relationship is for navigability between entities. Consider a simple scenario of `Country` and `City`, with eager loading defined for the following LINQ statement:
```
var someQuery =
db.Countries
.Include(co => co.City)
.Where(co => ... | Short answer. No.
To expand slightly, at the database create time, entity framework does not know how many records each table or entity will have, nor does it know how the entities will be queried.
\*In my opinion \* the creation of a foreign key is more likely to be right than wrong, I had massive performance issues... | Entity Framework Indexing ALL foreign key columns | [
"",
"sql",
"sql-server",
"entity-framework",
""
] |
I'm trying to combine 2 querys in oracle, those lines have the same value expect one field.
Ex:
```
SELECT NAME, AGE, EMAIL, DATE FROM table_a WHERE NAME = 'JOAO' AND FLAG = '0'
UNION
SELECT NAME, AGE, EMAIL, DATE FROM table_a WHERE NAME = 'JOAO' AND FLAG = '1'
```
Result:
```
NAME AGE EMAIL DATE
JOAO ... | You can use COALESCE(). <http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617/ms190349.aspx>
This Query should work for every name, and should coalesce the other rows.
```
SELECT
NAME1 AS NAME,
COALESCE(AGE1, AGE2) AS AGE,
COALESCE(EMAIL1, EMAIL2) AS EMAIL,
COALESCE(DATE1... | If you're just trying to ignore the NULL values:
```
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG in ( '0', '1' )
and date is not null
/
```
or
if you want to keep the nulls, but defer to available non-null values:
```
with w_data as (
SELECT NAME, AGE, EM... | Union null in Oracle | [
"",
"sql",
"oracle",
"union",
""
] |
Why am I getting `*` in the result where I have two digits.?
```
Declare @Product TABLE(id int identity(1,1),Cust VARCHAR(25),
Product VARCHAR(20), QTY INT)
INSERT INTO @Product(Cust, Product, QTY)
VALUES('KATE','VEG',2),
('KATE','SODA',6),
('KATE','MILK',1),
('KATE','BEER',... | It is because the resulting datatype is too short to display. As per [msdn](https://msdn.microsoft.com/en-us/library/ms187928.aspx)
> **Truncating and Rounding Results**
>
> When you convert character or binary expressions (char, nchar,
> nvarchar, varchar, binary, or varbinary) to an expression of a
> different data ... | You have only specified a single character in your `TRY_CONVERT(VARCHAR(1), QTY) qty1`.
If you change it to `VARCHAR(2)`, it will work:
```
DECLARE @Product TABLE
(
id INT IDENTITY(1, 1) ,
Cust VARCHAR(25) ,
Product VARCHAR(20) ,
QTY INT
)
INSERT INTO @Product
( Cust, Product... | Try_convert issue * sql server 2012 | [
"",
"sql",
"sql-server",
""
] |
I have a SQL database that has a column that is a string. The data inside is numbers such as..
```
$12,000,394.09
$56,874.94
$110,339,384.11
```
It is a string column but I am wanting to sort it with lowest on top. Is it possible to do this? Right now I have only tried the simple..
```
SELECT * FROM sales ORDER BY s... | You can do this with `regexp_replace` to keep only numeric characters and the decimal point, and `to_number` to convert the result to a number:
```
select *
from sales
order by to_number(regexp_replace(string_num_field, '[^0-9.]+', ''))
```
**Fiddle:** <http://sqlfiddle.com/#!4/7d46e/2/0> | If all of your strings have the same format -- starting with a currency symbol, commas separator (if appropriate) and two decimal places -- then you can use the following:
```
order by length(saleamount) desc,
saleamount desc
```
If you want the smallest value first, then:
```
order by length(saleamount) as... | Sort SQL string column with currency | [
"",
"sql",
"oracle",
""
] |
I want to convert my string data to array in sql server.
I tried it like below.
```
SELECT '223456789' AS SerialOriginalCode
-- SerialOriginalCode 223456789
DECLARE @tbl_SerialOriginalVerion TABLE(ID INT, SerialOriginalCode INT);
INSERT INTO @tbl_SerialOriginalVerion VALUES
(1, 2),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, ... | ```
DECLARE @InputText AS VARCHAR(MAX) = '223456789'
DECLARE @Pos Int = 1
DECLARE @End Int
DECLARE @TextLength Int = DATALENGTH(@InputText)
DECLARE @Array TABLE
(
TokenID Int PRIMARY KEY IDENTITY(1,1),
Match Varchar(MAX)
)
-- Exit function if no text is passed in.
IF @TextLength <> 0
BEGIN
WHILE @Pos <= @... | Try this `INSERT` using `number` from `master..spt_values`
```
SELECT '223456789' AS SerialOriginalCode
-- SerialOriginalCode 223456789
DECLARE @tbl_SerialOriginalVerion TABLE(ID INT, SerialOriginalCode INT);
INSERT INTO @tbl_SerialOriginalVerion
SELECT number + 1, SUBSTRING(t.SerialOriginalCode, sv.number + 1, 1)
F... | SQL server varchar.toArray() or string.toArray() method | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In table i have field pwd which goes like this 001 , 002, 003 , 004 .
To get highest value of that i go like this
```
("SELECT pwd FROM users WHERE pwd= (SELECT max(pwd) FROM users)")
```
That way i got number 004. To increment it and add again to table i use
```
biggest= CInt((SQLDataset.Tables(0).Rows(0).Item(0)... | This way i will get all of the missing numbers in array and then i use row index 0 to get only the first one.
```
select u1.pwd+1 as firstmissing
from users as u1
left outer join users as u2
on u2.pwd=u1.pwd+1
where u2.pwd is null
``` | You could use a subquery (presuming sql-server):
```
SELECT MIN(u.pwd) + 1 AS FirstMissing
FROM users u
WHERE (u.pwd + 1) <> (SELECT TOP 1 u2.pwd
FROM users u2
WHERE u2.pwd > u.pwd)
```
`Demo`
If you want to do that in memory since you already have the `DataSet` you could... | Get missing number sql | [
"",
"sql",
"vb.net",
""
] |
I would like to take the following query
```
select '2009042 Restraint 151214.pdf',
'2009042 Restraint 170215.pdf',
'2009042 Restraint 240215.pdf',
'2009856 Restraint 190215.pdf',
'208272 Notice 120215.pdf',
'208272 Restraint 120215.pdf',
'212598 Restraint 160215.pdf',
... | Just phrase the query as a union all in the first place:
```
select '2009042 Restraint 151214.pdf' from dual union all
select '2009042 Restraint 170215.pdf' from dual union all
select '2009042 Restraint 240215.pdf' from dual union all
select '2009856 Restraint 190215.pdf' from dual union all
select '208272 Notice 1202... | > The pivot statement doesn't seem to be able to do this.
Yes, because you're not trying to pivot your rows into columns, you're trying to *unpivot* them from columns into rows.
If your columns had a predefined, enumerated set of names, you could use `UNPIVOT` like this:
```
select *
from (
select '2009042 Restrai... | Oracle SQL convert a single row with multiple columns into multiple rows | [
"",
"sql",
"oracle",
""
] |
I have a table that looks like this:
```
Name | Product | Total
---- --------- ------
A Toy $5
A Car $30,000
A Equipment $500
B Car $100,000
```
etc...
I would like to remove the duplicate name entries but keep the relationship to the product example:
```
Name | Product | ... | I assumed you want to make `Name = ''` because you cannot delete the duplicate records.
So you can use a [`ROW_NUMBER`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm) function inside a [`WITH`](http://oracle-base.com/articles/misc/with-clause.php) clause and update `Name` field
```
;WITH C AS... | If you want to keep the `Name` only when `Product ='Toy'` then use `Case` statement
```
Select case when Product ='Toy' then Name else '' END as Name,
Product,
Total
From yourtable
``` | Remove duplicate entry but keep relationship | [
"",
"sql",
"oracle11g",
""
] |
I've written the following function:
```
declare
v_count DATE;
strsql VARCHAR2(200);
begin
for r in (select OBJECT_NAME from all_objects where OBJECT_TYPE='TABLE'
and OWNER='SALES'
and OBJECT_NAME LIKE 'T%'
ORDER BY OBJECT_NAME DESC)
loop
DBMS_OUTPUT.PUT_LINE(r.OBJECT_NAME);
... | After a bunch of work, breakage, consulting the almigty Google, I came up with this function:
```
declare
v_count TIMESTAMP;
strsql VARCHAR2(200);
tblname VARCHAR2(32);
begin
for r in (select OBJECT_NAME from all_objects where OBJECT_TYPE='TABLE'
and OWNER='SALES'
and OBJECT_NAME LIKE 'T%'
... | Your strsql contains incorrect SQL which cannot be executed. So, first `execute immediate` raises an exception (sure you saw it).
Table name cannot be used from parameter. You should something like
```
strsql := 'select .... from ' || r.owner || '.' || r.object_name;
``` | Oracle Function to Get Last Updated Timestamps For All Tables In A Schema | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I'm trying to get the amount of days it has been since April 15th from the current date, excluding the year so that no matter what its never greater than 365
When this is performed:
```
SELECT DATEDIFF(dd, '04/15/2015', GETDATE())
```
it will only work for this year and need to get it to work for each year. | You need conditional logic to handle dates before April 15th in the current year:
```
SELECT (case when month(getdate()) > 4 or
month(getdate()) = 4 and day(getdate()) > 15
then DATEDIFF(day, cast(year(getdate()) as varchar(255)) + '-04-15', GETDATE())
else DATEDIFF(day, cas... | Just pop the current year into your query
```
SELECT DATEDIFF(dd, '04/15/'+ CAST(YEAR(GETDATE()) AS CHAR(4)), GETDATE())
``` | SQL for amount of days since specified date each year (SQL Server) | [
"",
"sql",
"sql-server",
"datediff",
""
] |
Hi so here is the table:
```
Select * from LogTable order by insert_time desc
```
LogTable:
```
|user_id|action|object_id|insert_time|
|2 |start |123 |20.04.2015 |
|2 |stop |123 |19.04.2015 |
|2 |start |123 |17.04.2015 |
|1 |stop |321 |16.04.2015 |
|1 |start |321 |... | You would seem to want all users where the last value for `action` is `stop`. Here is one method using `row_number()`:
```
select lt.*
from (select lt.*,
row_number() over (partition by user_id, object_id
order by insert_time desc) as seqnum
from logtable lt
) lt... | Try this:
```
SELECT T1.*
FROM LogTable T1
WHERE T1.Action = 'stop'
AND NOT EXISTS (
SELECT 1
FROM LogTable T2
WHERE T1.UserId = T2.UserId
AND T2.Action = 'start'
AND T1.insert_time < T2.insert_time
)
```
[See sql fiddle](http://sqlfiddle.com/#!6/8d799/1) | complex SQL depending on each object insert time? | [
"",
"sql",
"sql-server",
""
] |
I want to perform sorting and filtering in my stored procedure.
My create table for Holiday table:
```
CREATE TABLE [dbo].[Holiday](
[HolidaysId] [int] IDENTITY(1,1) NOT NULL,
[HolidayDate] [date] NULL,
[HolidayDiscription] [nvarchar](500) NULL,
[Name] [nvarchar](max) NULL,
CONSTRAINT [PK_Holiday] PR... | This is how i have done and i am getting expected output but still i want to take improvement suggestion from all of you if there is any.
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[HolidayFetchList]
@pageno int,
@pagesize int,
@sortorder varchar(10),
@sortcolumn varchar(100),
@filter v... | I've not tested this, but something like this you can use as starter and do modifications to make it stable:
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_PagedItems]
(
@ID int = NULL,
@Name varchar(50) = NULL,
@HolidayDate date = NULL,
@SortCol varchar(20) = '',
... | how to perform sorting and filtering in stored procedure with performance optimization? | [
"",
"sql",
"sql-server",
"select",
"stored-procedures",
"sql-server-2008-r2",
""
] |
I have the following value format :
**1234567890**
I want to convert it to the following format : **123-45A67890**
Table Name: Test
Column Name : MyCode
Note that I am using Microsoft SQL 2012. | You can use `STUFF` . Something like this
```
DECLARE @v VARCHAR(15) = '1234567890'
SELECT STUFF(STUFF(@v,4,0,'-'),7,0,'A')
```
Your `SELECT` would be
```
SELECT STUFF(STUFF(MyCode,4,0,'-'),7,0,'A')
FROM Test
```
Your `UPDATE` would be
```
UPDATE Test
SET MyCode = STUFF(STUFF(MyCode,4,0,'-'),7,0,'A')
``` | Does SQL Server support the `PASTE` function?
```
paste(paste('1234567890',7,0,'A'),4,0,'-')
```
For example:
```
select paste(paste(column_name,7,0,'A'),4,0,'-') from table_name
```
or
```
update table_name set column_name = paste(paste(column_name,7,0,'A'),4,0,'-')
``` | updating a text with additional characters in SQL | [
"",
"sql",
"sql-server",
"character",
""
] |
My table 'Customer' contains customerid , firstname, lastname, company,city,state,country, email, invoicetotal
Question: For countries that have at least two customers using yahoo as email provider, display the name alongside the revenue
My solution:
```
select county,sum(invoiceTotal)from customer where email like ... | You are grouping by `email` as well - just group by `Country` and you should be fine
```
select
county,
sum(invoiceTotal)
from customer
where email like '%yahoo%'
group by Country
having Count(Country)>2
``` | You can't group by `email`, since that's unique. Fortunately, you don't have to. | sql query for the following statement? | [
"",
"sql",
""
] |
I have a table with 3 columns - a timestamp, a real, and a string. The String columns holds various time frequency values (like Minutes, Hours, Days). I want to take the value in my timestamp column and add to it the values in the other columns. For example I'd like to do something like
```
select timestamp '2015-04-2... | You can use following query to convert `rate` and `frequency` columns to ***interval***
```
select format('%s %s',rate,frequency)::interval
from actions
```
and then get the exact timestamp just by adding the interval with `action_start_time` *column*
```
select action_start_time + format('%s %s',rate,frequency)::in... | Simply:
```
SELECT action_start_time + rate * ('1'|| frequency)::interval
```
The all trick is in a using multiplication of some interval value:
```
postgres=# select 3 * interval '1 hour';
┌──────────┐
│ ?column? │
╞══════════╡
│ 03:00:00 │
└──────────┘
(1 row)
```
You can simply create any interval value without ... | Postgresql using date interval and SELECT statement | [
"",
"sql",
"postgresql",
"intervals",
""
] |
How can I make following query work? This is inside stored procedure `@GetClosedMeetings` `bit` parameter passed true to get the meetings which are finished, otherwise get planned and current meetings. (Status: 0 - Planned, 1 - Current, 2 - closed)
```
SELECT
MeetingId, Status
FROM
dbo.Meeting
WHERE
Sta... | You missed end in case
```
SELECT MeetingId, Status
FROM dbo.Meeting
WHERE Status IN
(CASE
WHEN @GetClosedMeetings = 1 THEN 1
ELSE @OtherStatuses end)
``` | If I understand your requirement correctly, if `@GetClosedMeetings` is `TRUE`, you want to return `Meetings` that are finished, which from your question seems to have a `STATUS` of 2. On the other hand, if `@GetClosedMeetings` is `FALSE`, then you want to get planned and current meetings. Here is one way to achieve thi... | CASE syntax inside a WHERE clause with IN on SQL Server | [
"",
"sql",
"sql-server",
"case",
""
] |
This question is about a `DELETE` query involving two tables.
I have two tables called `TableOne` and `TableTwo`.
I have the same columns in `TableTwo` as in `TableOne`.
```
CREATE TABLE TABLEONE
(
ColumnOne INT,
ColumnTwo INT
);
CREATE TABLE TABLETWO
(
ColumnOne INT,
ColumnTwo INT
);
```
**[HERE ... | The `Column2` values in `TableOne` that are associated with all groups are found by:
```
select column2
from TableOne
group by column2
having count(*) = (select count(distinct column1 from tableone));
```
To delete these values from `TableTwo`:
```
delete from TableTwo t2
where t2.column2 in (select column2
... | ```
Try this one:
DELETE FROM @TABLETWO
WHERE ColumnTwo IN (SELECT ColumnTwo FROM @TABLETWO
GROUP BY ColumnTwo
HAVING COUNT(DISTINCT ColumnOne) > 1)
AND ColumnOne IN (SELECT ColumnOne FROM @TABLEONE)
``` | SQL Server : delete a record only if it is associated with all the groups of the table | [
"",
"sql",
"sql-server",
"delete-row",
""
] |
I am using the below query
```
SELECT *
FROM [dbo].[QUANTITY]
WHERE getdate() BETWEEN fromdate AND todate
```
If the `todate` is `null` (`1900-01-01 00:00:00.000`) it just filters them out. I want even the fields with `todate` to be `null` (`1900-01-01 00:00:00.000`) in the result. How can this be done? | You could explicitly check it with a combination of `and` and `or` operators:
```
SELECT *
FROM [dbo].[QUANTITY]
WHERE (getdate() >= fromdate AND
(todate IS NULL OR
todate = '1900-01-01 00:00:00.000')
) OR
getdate() BETWEEN fromdate AND todate
``` | ```
SELECT *
FROM [dbo].[QUANTITY]
WHERE getdate() >= fromdate
AND getdate() <= COALESCE(todate
,NULLIF(todate,'1900-01-01 00:00:00.000')
,'9999-12-31 23:59:59.997'
)
``` | Using getdate() | [
"",
"sql",
"sql-server",
"select",
"getdate",
""
] |
I have to update XML of table based on some conditions of that XML. Sample XML:
```
<CountryValues>
<CountryRow>
<CountryName>Brazil</CountryName>
<PlaceName>Place 1</PlaceName>
<Month>1</Month>
<PlaceValue>0</PlaceValue>
</CountryRow>
<CountryRow>
<CountryName>Brazil</CountryName>
... | Basically, I see 2 ways of dealing with this. First - split xml to sql table/derived table, do your work and then combine into xml again.
```
declare @data xml =
'<CountryValues>
<CountryRow>
<CountryName>Brazil</CountryName>
<PlaceName>Place 1</PlaceName>
<Month>1</Month>
<PlaceValue>0</PlaceValue>... | You need to use the .modify() method of the xml data type (see here: <https://msdn.microsoft.com/en-us/library/ms187093.aspx>) and XQuery to find which nodes you should change.
You can find some nice examples in this link: <http://www.mssqltips.com/sqlservertip/2738/examples-of-using-xquery-to-update-xml-data-in-sql-se... | How to Update XML in SQL based on values in that XML | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
"sqlxml",
""
] |
Is it possible to return all rows between matched rows?
What I'm trying to is query an audit table where jobs writes an audit table. There is a clear start audit message and end audit message as well as info between. Is it possible to get a select statement to return all the rows between the "start" audit entry and "e... | Here's a simple and clean solution. If you have any questions or need anything else let me know.
```
SELECT A.[DATE],
A.[TIME],
A.[User],
A.[Entry]
FROM @Table A
CROSS APPLY(SELECT MIN([Date]) FROM @Table WHERE [Entry] LIKE 'Some Job%') CA_min(start_dt)
CROSS APPLY(SELECT MAX([Date]) FROM @Tab... | # Data sample
```
DECLARE @Table TABLE
(
[DATE] DATETIME ,
[TIME] TIME ,
[USER] VARCHAR(100) ,
[ENTRY] VARCHAR(1000)
)
INSERT INTO @Table
VALUES ( '2015-04-13 07:30:15.150', '07:30:15', 'CmdLne',
'SOME JOB STARTED FOR PROCESSING DATE 13/04/2015' ),
( '2015-04-13 07:3... | SQL - Select all rows between two string rows | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am having some real trouble with this CASE statement...
It says I get an error near > which seems to point to the 3rd line where its checking > 15. However I don't see anything wrong with this query.
I tried searching around on google and here and didn't see anyone with this exact problem, hopefully you can point it... | Your problem lies in the `CASE` expression. When using multiple conditions, you use `WHEN` instead of `ELSE`. `ELSE` should only be used once.
```
SELECT
CASE
WHEN DATEDIFF(day, C1.RecvdDate, GETDATE()) > 15 AND DATEDIFF(day, C1.RecvdDate, GETDATE()) <= 30 THEN '15+'
WHEN DATEDIFF(day, C1.RecvdDate, GETDATE(... | You've got the syntax wrong; you can't use multiple ELSE clauses - it should be multiple WHENs:
```
SELECT
CASE
WHEN DATEDIFF(day, C1.RecvdDate, GETDATE()) > 15 AND DATEDIFF(day, C1.RecvdDate, GETDATE()) <= 30 THEN '15+'
WHEN DATEDIFF(day, C1.RecvdDate, GETDATE()) > 30 AND DATEDIFF(day, C1.RecvdDate, GETDATE... | SQL Error (102): Incorrect syntax near '>' | [
"",
"sql",
"sql-server",
""
] |
Why is this query returning an error. I am trying to load the code for table as a constant string, the flag for data again a constant string, the time of insertion and the counts for a table. I thought, let me try and run the secelct before writing the inserts.
But for some reason, it fails listing column names from ta... | The double quotes on the literals is a problem. Here is a simpler version that I tested successfully:
```
hive -e "select 'WEB' , '1Hr' , from_unixtime((unix_timestamp(substr(sysDate, 0, 11), 'dd/MMM/yyyy')), 'MM/dd/yyyy') as time, count(*) from weblog where year=2015 and month=04 and day=17 group by 1,2 , from_unixti... | Just leave out the constants in the `group by`. It isn't doing anything:
```
select "WEB" as src_cd, "1Hr" as Load_Flag,
from_unixtime((unix_timestamp(substr(sysDate, 0, 11), 'dd/MMM/yyyy')), 'MM/dd/yyyy') as time, count(*)
from weblog
where year = 2015 and month = 04 and day = 17
group by from_unixtime((uni... | How to Select count and literal value in hive | [
"",
"sql",
"hadoop",
"mapreduce",
"hive",
"hortonworks-data-platform",
""
] |
I have two tables:
**test:**
```
id
name
last_name
price
```
**test1**
```
id
name
price
```
I want to combine the two fields (price) from two tables and calculate their average. But I get an average of the field for each of these tables.
```
SELECT AVG(price) FROM test as p
UNION
SELECT AVG(price) FROM test1 as ... | How about this:
```
SELECT AVG(price) AS P FROM
(
SELECT price FROM test
UNION ALL
SELECT price FROM test1
) AS TMP
```
I think you need `UNION ALL` to really include ALL prices, otherwise duplicate prices will be omitted, which may have influence on the average. | You can do it using subquery, or with clause:
```
WITH all_data as(
SELECT id,name,price FROM test as t
UNION ALL
SELECT id,name,price FROM test as t2
)
SELECT AVG(price) FROM all_data
``` | Combining two fields from two different tables in SQL | [
"",
"sql",
"database",
""
] |
I've got this situation where I think the best solution is using a pivot function, but I don't really know how to. Or maybe there is a much better way to do this...
I got this table as a source :
```
ID | version | code | property | value
-----|---------|------|----------|------
110| 1| AA| prop1| ... | You want grouping on id, version and code, so it is simple pivot:
```
Select * from TableName
pivot(max(value) for property in([prop1],[prop2],[prop3]))p
```
If table has more columns then you will need to pick right columns first:
```
;with cte as(Select id, version, code, property, value from TableName)
Select * f... | If the `property` is always `prop1`, `prop2` and `prop3`, you could do this using conditional aggregation:
```
SELECT
ID
, Version
, Code
, MAX(CASE WHEN Property = 'prop1' THEN VALUE END) AS [prop1]
, MAX(CASE WHEN Property = 'prop2' THEN VALUE END) AS [prop2]
, MAX(CASE WHEN Property = 'pro... | Pivot table without aggregation and multiple pivot columns | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
"pivot",
""
] |
At school We saw you can select this way:
```
SELECT *
FROM BLALBLA
WHERE id=1 AND id = 2 AND id=3 AND id=4
```
But how can we do :
```
SELECT
FROM BLABLA
WHERE id = 1 to 4
```
Thank you
goldiman | ```
SELECT * FROM BLABLA WHERE id => 1 AND id =< 4
``` | There are several ways
1) if `id` field is integer.
```
SELECT *
FROM BLALBLA
WHERE id between 1 and 4
SELECT *
FROM BLALBLA
WHERE id => 1 AND id =< 4
SELECT *
FROM BLALBLA
WHERE id IN (1,2,3,4)
```
2) if `id` is varchar
```
SELECT *
FROM BLALBLA
WHERE id IN ('1','2','3','4')
``` | Select in a primary key interval SQL | [
"",
"mysql",
"sql",
"primary-key",
""
] |
I have a form with several inputs, that are then passed on to a query. This is pretty straightforward, except I want one of my parameters to be used in an IN statement in my sql like such:
```
Select sum(id) as numobs from table where year=[form]![form1]![year] and (group in([form]![form1]![group]));
```
When [form]!... | This can be very simply done with a sub in a VBA module:
```
Sub MakeTheQuery()
Dim db As DAO.Database
Dim strSQL As String
Dim strElements As String
Set db = CurrentDb()
strSQL = "SELECT Sum(id) AS numobs " & _
"FROM ErrorKey WHERE ErrorKey.ID In ({0});"
' Example: "3,5"
strElem... | I can't figure out a way to do it with `IN`.
My solution: in a VBA module in your database, write a sub to build a query based on the values in the form control. Let's use the `Split` method to make an array, which we can iterate through to build a query.
```
Sub MakeTheQuery()
Dim strSQL As String, db As DAO.Databas... | Using parameter from form in IN statement | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2010",
""
] |
I have wide table with 100 columns.
I need a SP which takes 100 parameters and then does the insert.
I know how to do this manually. But having the table definition and knowing that SP parameters will have exact same name of the table columns, can you think of a better/faster way to generate this stored procedure? | I use SQL to write it for you. Check it out and let me know if it needs any tweaks or if you have any questions.
```
IF OBJECT_ID('yourTable') IS NOT NULL
DROP TABLE yourTable;
CREATE TABLE yourTable
(
col1 INT,
col2 VARCHAR(100),
col3 NUMERIC(18,2)
)
DECLARE @InputParams VARCHAR(MAX),
@In... | For this type of scenario, I like to leverage table types.
First, create the table type:
`CREATE TYPE [YourType] AS TABLE (columns...)`
In C#, populate a `DataTable` "template" by running this query (using a `DataAdapter`):
```
DECLARE @tt AS [YourType]
SELECT * FROM @tt
```
Then add a row to the table and cycle t... | Generate insert statement which has same columns of a table in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm looking to implement a sort of Type 2 Slow Changing Dimension like behavior into my dimension table using PL/SQL's MERGE statement. It workd just fine for updating existing values and inserting new ones. I'm looking to extend this functionality by not only updating existing values but creating a different row with ... | If you are truly doing a Type 2 dimension and want to use a merge, yes it can be done but it's not terribly straightforward. Effectively, if you will need to compare your data using an inline view in the USING clause, that features a column that indicates whether its an insert or an update. This field gets joined to an... | You need to run two statements instead of 1 here.
(in your pseudo-code)
```
UPDATE END_DATE IN A WHERE A.ID = something_from_B
INSERT new VALUES IN A
```
The insert needs to happen no matter what. So no need of checking if the row exists or not (and only updating if the row exists). Just end\_date all records that ... | PL/SQL Merge statement | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
My query below is used to retrieve list of items which has been ordered and returned by the customer. I'm confused with the last join, `ReturnCustomer`, where I want the query to return data with `status = 20` or otherwise it returns `NULL`. Below is my query:
```
SELECT Product.id AS product_id, Product.supplier_prod... | `a LEFT JOIN b` works exactly like that.. (the `a` will always be present, where `b` may be null)
`ON` works only removing the `b`, where `a` won't be affected..
`WHERE` works by removing rows
so when
```
A have 1,2,3
B have 1,2
C have 1,3
```
when those three left joined, for example:
```
SELECT *
FROM A
... | this may works
```
SELECT
Product.id AS product_id,
Product.supplier_product_id AS vip_id,
Product.name AS product_name,
detailSO.qty,
detailRC.return_qty
FROM
Product
RIGHT JOIN detailSO
ON detailSO.product_id = Product.id
RIGHT JOIN SalesOrder
ON SalesOrder.id = detailSO.so_id
AND ... | LEFT JOIN doesn't consider ON clause | [
"",
"mysql",
"sql",
""
] |
I've an array `priority = ['HIGH', 'MEDIUM', 'LOW']` which is used to set an 'urgency' database column. I'd like to retrieve the data sorted by priority, though applying `Task.order(:urgency)` returns the results alphabetically (i.e. HIGH, LOW, MEDIUM).
I'm using PostgreSQL for the database.
I'd (obviously) like thes... | A simple `CASE WHEN` can do the trick (postgreSQL syntax used here):
```
scope :urgency_ordered {
order(<<-SQL)
CASE tasks.urgency
WHEN 'HIGH' THEN 'a'
WHEN 'MEDIUM' THEN 'b'
WHEN 'LOW' THEN 'c'
ELSE 'z'
END ASC,
id ASC
SQL
}
```
Call it this way:
```
Task.urgency_ordered
``` | I am late to the party, but I am surprised none has come up with this answer yet: If you are using MySQL (untested but should work for Postgres, too), there is a shorter, safer and more generic way than any of the previous answers. It works with any field and is protected against sql injection, so you can pass any list... | Rails - order on column's values (priority column) | [
"",
"sql",
"ruby-on-rails",
"postgresql",
""
] |
I am writing java program and based on user input I have to perform operation.
If user gives me id (suppose id=3) then I have to execute
```
select emp_name
from employee
where empid = 3
```
else if user doesn't provide id then I have to show everything from table (here is my question how to achieve this)
```
sel... | You should use parameters, don't know Java to help with that part but you could provide NULL to the query as such.
```
select emp_name
from employee
where empid = (case when @parameter is null then empid else @parameter end)
``` | There are several answers to your question. You can choose to implement what you feel more comfortable;
```
Method 1: Check the user input and construct 2 different queries:
If the user enters "nothing" execute
"select emp_name from employee",
else execute "select emp_name from employee where empid=X", where X is t... | How to write query in SQL Server to select everything | [
"",
"sql",
"sql-server",
""
] |
the next sql statement work fine. it shows both patient\_id and serv\_name, but i try to show patient\_name instead of patient\_id
```
SELECT C1.patient_id, S.serv_name
FROM
Checkup_Details C
INNER JOIN Services S ON (C.serv_id=S.serv_id),
Checkup C1
WHERE
C1.today = DATE() AND C1.check_id=C.check_id
... | Assuming the field patient\_name is in Checkup\_Details, you have to put
```
SELECT C1.patient_name ...
```
instead from
```
SELECT C1.patient_id ...
``` | Simply add the INNER JOIN clause to get the columns of the table Patient and change C1.patient\_id by P.patient\_name.
```
SELECT P.patient_name, S.serv_name
FROM
Checkup_Details C
INNER JOIN Services S ON (C.serv_id=S.serv_id),
INNER JOIN Patient P ON (C1.patient_id=P.patient_id)
Checkup C1
WHERE
... | INNER JOIN SQL QUERY | [
"",
"sql",
""
] |
I have the following data in a column named `datos`. I want to update the text after the 8th slash (DR004), to be DR013.
```
/1/14/0/0/ / / /DR004/1/rttrgftgr/ZM003/0/0/0/1/0/
```
I have tried using this
```
update sumcon
set substr(datos, instr(datos, '/', 1, 8) + 1, 1) =
decode(substr(datos, instr(datos... | Per [@LalitKumarB's](https://stackoverflow.com/users/3989608/lalit-kumar-b) suggestion, change your UPDATE statement to
```
UPDATE SUMCON
SET DATOS = SUBSTR(DATOS, 1, INSTR(DATOS, '/', 1, 8)) ||
'DR013' ||
SUBSTR(DATOS, INSTR(DATOS, '/', 1, 9))
WHERE NIS_RAD = 200000732;
```
[SQLFiddle... | You can use a regular expression:
```
UPDATE sumcon
SET datos = REGEXP_REPLACE( datos, '(/(.*?/){7}).*?/', '\1' || :new_value || '/' )
WHERE nis_rad = 200000732;
```
* `(/(.*?/){7})` - will find the first `/` then will match zero-or-more of any characters `.*?` until another `/` is found and then repeat this ma... | Using substr and instr to update a delimited string | [
"",
"sql",
"oracle",
"decode",
"substr",
""
] |
I am transferring some SQL query into C# code, now I am having problem understand the following query.
So far my understanding to the following query is: If `PREFIX` is between `0` to `99`, then trim `PREFIX`, but what does `|| '-' ||` mean here? My understanding for line 3 is after finishing the trim function in line ... | * `DIGITS(CLNUMBER)` returns the number stored in CLNUMBER as a string with leading zeros.
* `TRIM(L '0' FROM something)` removes leading zeros from something.
* `TRIM(something)` removes leading and trainling blanks from something.
* || concatenates strings.
PREFIX is a string. In case it contains a two-digit number,... | Your code does the following.
Line1: If you prefix is between `'00'` AND `'99'`
Line2: Then trim the spaces from prefix and then append `-`
Line3: Then append `CLNUMBER` by removing the leading `0` from `CLNUMBER` first
You can lookup the syntax of `TRIM` function [here](http://www-01.ibm.com/support/knowledgecente... | DB2 SQL Query Trim inside trim | [
"",
"sql",
"db2",
"trim",
""
] |
I have a table, which has around 2 million records and out of these there are around 70000 records which have duplicate Deal ID's.
1. Here for only duplicated Deal ID records I want to consider the record with last updated Month(**FP**).
2. only if the Last Updated Month(**FP**) is Equal then the record with **Sour... | Looks like basic ROW\_NUMBER case, doesn't it?
```
select *
from (
select *,
[rank] = ROW_NUMBER() OVER(
partition by deal
order by fp desc, case when source = 'MDM' then 0 else 1 end asc
)
from src
) ranked
where [rank] = 1
```
<http://sqlfiddle.com/#!6/46b96/12> | give this a try
```
Select * from [table]
where DealId in(
Select DealId from [table]
Group by DealId
Having count(DealId) > 1)
where source = 'MDM'
```
this should give you all the records with duplicate dealIds and source = 'mdm' | Retrieve last updated record in SQL with conditions | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query that returns a row of multiple `Itemcodes`. The result is
```
Date group list of item code
2015-04-15 118 FYCT-00063,FYCM-00016,FYCM-00064,FYCF-00018
```
it's working fine but i need the result like this, with quotes around every code `'FYCT-00063','FYCM-00016','FYCM-00064','F... | Try this
```
SELECT DISTINCT SS.PostDate
,SS.U_Unit
,STUFF((
SELECT ', '
+ QUOTENAME(CAST(OWOR.ItemCode AS VARCHAR(10), ''''))
FROM OWOR
WHERE OWOR.PostDate = SS.PostDate
AND OWOR.U_Unit = SS.U_Unit
AND OWOR.STATUS = SS.STATUS
... | ```
SELECT DISTINCT SS.PostDate,SS.U_Unit,
STUFF((
SELECT ', ',+ '''' + CAST(OWOR.ItemCode AS VARCHAR(10) + '''') [text()]
FROM OWOR
WHERE OWOR.PostDate=SS.PostDate
AND OWOR.U_Unit=SS.U_Unit
AND OWOR.Status=SS.Status
FOR XML PATH('') , TYPE) .value('.','N... | sql server comma delimted string values into one row | [
"",
"sql",
"sql-server",
"sapb1",
""
] |
Here is my current query:
```
SELECT `performers`.`hash`,
`performers`.`alias`,
`performers`.`date_updated`,
`performers`.`status`,
IF(`performers`.`status` = 'active', 'deleted','active') AS `statususe`,
`images`.`image_hash_file`
FROM `performers`
LEFT JOIN `images` ON `ima... | You may add the WHERE clause in the LEFT JOIN so not matching rows are still in the result set.
```
SELECT `performers`.`hash`, `performers`.`alias`,
`performers`.`date_updated`, `performers`.`status`,
IF(`performers`.`status` = 'active', 'deleted','active') AS `statususe`,
`images`.`image_hash_file`
FROM `perf... | Try something like this:
```
WHERE (`images`.`asset_type` = 'performer' OR `images`.`asset_type` IS NULL)
``` | making a where clause optional in a sql statement | [
"",
"mysql",
"sql",
""
] |
So I have this sample table. Contains data of what `OS` are installed of all internet shop branches.
```
ID ShopName PCName OS
1 Mineski M101 WinXP
2 Mineski M102 WinXP
3 GameCity G201 Win7
4 GameCity G202 Win7
5 CyberBob C301 WinXP
6 CyberBob C302 Win7
```... | You can use `case` with `distinct` `OS` value `count` for each `ShopName` check :
```
select ShopName
, case when count(distinct OS) > 1 then 'Mixed' else min(OS) end
from ShopInv
group by ShopName
```
[**SQLFiddle**](http://sqlfiddle.com/#!6/a92ad4/8) | This is easy: As you want to have one row per shop, group by shop only. Then get the OS with an aggregate function. This can be MIN or MAX. If you detect however, that MIN <> MAX, then you must show 'Mixed' instead.
```
select
ShopName,
case when MIN(OS) = MAX(OS) then MIN(OS) else 'Mixed' end as OS
from ShopInv
... | How to combine two values (row) into a single row with custom value? | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I have the following two relations:
```
Game(id, name, year)
Devs(pid, gid, role)
```
Where Game.id is a primary key, and where Devs.gid is a foreign key to Game.id.
I want to write a SQL query that finds the game with the largest amount of people who worked on that game. I wrote the following query:
```
SELECT Gam... | The task can be shorten to:
> Give me all the rows from the original query with the maximum number of developers
It can be reached through the `WITH` [statement](https://msdn.microsoft.com/en-us/library/ms175972.aspx). The answer is the following:
```
WITH GamesDevs (GameName, DevsCount)
AS
(
SELECT Game.name AS... | Try this query :
```
select g.name, count(d.gid)
from
game g
join
devs d
on g.id=d.gid
group by g.name
having count(d.gid)= (select max (temp.cnt) from
(select gid p, count(*) cnt
from devs
group by gid) temp)
;
``` | Select only largest values in a SQL relation? | [
"",
"sql",
"max",
""
] |
Suppose we have a table with scheme
```
student(id (primary key), name, math_score, english_score)
```
I am trying to get student information (id and name) with highest rank (ordered by highest sum of math score and english score). There may be several student with tie, and we want all of them. The way I thought abou... | Use WITH TIES
```
create table #student(
id int primary key identity(1,1),
name varchar(50),
math_score decimal,
english_score decimal
)
insert into #student
values
('Tom', 90, 90),
('Dick', 70, 70),
('Harry', 80, 100)
select TOP(1) WITH TIES
id,
name,
math_score,
english_score,... | This should accomplish it, you're adding in an unnecessary step.
```
select id,
name,
math_score+english_score as total_score
from student
where math_score+english_score=(select max(math_score+english_score)
from student)
``` | Removing redundancies in sql query that contains subquery | [
"",
"sql",
"azure",
"subquery",
""
] |
In our database we do have a table that keeps track of the power consumption of a device. The rate at which new values get inserted is not fixed, they only get written when there really is a change, so the temporal distance between the values is varying and may reach from 1 second to several minutes. The entries consis... | Your sample data does not match the result intervals, so you may miss increases within an interval at the end or the beginning.
Therefore, I assumed a linear increase between sample data rows and matched them to the result interval.
```
declare @start datetime2 = '2015-01-09 09:00:00'
declare @end datetime2 = '2015-01... | I think the best way to deal with this is to first generate your intervals, and then left join your data, since this firstly makes the grouping much less complicated for variable intervals, and also means you still get results for intervals with no data. To do this you will need a numbers table, since many people don't... | SQL statement that calculates per-interval growth | [
"",
"sql",
"sql-server",
"aggregate-functions",
"intervals",
""
] |
This is my first post in this forum so please be understanding.
I have following issue.
I want to two join two tables:
Table1:
```
Product | Start Date | End Date
-------------------------------------
Product1 | 01/01/2014 | 01/05/2015
Product2 | 01/03/2014 | 01/01/2015
```
Table2:
```
Product | Start Date ... | Just use WHERE NOT EXISTS to filter out everything but the latest date from TABLE2 (I am assuming that you are asking for the latest STARTDATE from TABLE2; also I add 'SomeOtherField' to Table1, because otherwise you could just query Table2):
SELECT t1.Product, t1.SomeOtherField, t2.StartDate, t2.EndDate, t2.Value
FR... | This is possible, the query will involve three steps:
1. Find all the max `start date` for each `product` in table 2. Hint: use group by.
2. Join table 2 with the result from #1 to get the `Value`.
3. Join table 1 with the result from #2 to filter out products that are not in table 1. | SQL - Join two tables without unique fields | [
"",
"sql",
""
] |
I have a date. I have to identify date of the monday in the week which my date lies. | ```
SET DATEFIRST 1
SELECT DATEADD(DAY,1-DATEPART(WEEKDAY,'2012-01-01'),'2012-01-01')
``` | **MSSQL**
```
SELECT CONVERT(varchar,DATEADD(day, DATEDIFF(day, 0, GETDATE()) /7*7, 0),100) AS weekstart
```
**MySql**
```
SELECT DATE_ADD(date, INTERVAL(1-DAYOFWEEK(date)) +1 DAY) AS weekStart
``` | How to find start date of a week | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table something like the following:
```
name | language | text
-----------------------------
greet | 1 | hello
greet | 2 | bonjour
blue | 1 | blue
blue | 2 | bleu
red | 1 | red
green | 1 | green
yellow | 1 | yellow
```
I need to retrieve... | Use `NOT EXISTS`:
```
SELECT t.*
FROM dbo.TableName t
WHERE t.language = 1
AND NOT EXISTS
(
SELECT 1 FROM dbo.TableName t2
WHERE t.name = t2.name
AND ( t2.language IS NULL OR t2.language <> 1 )
)
```
`DEMO`
I've included `t2.language IS NULL` to show you how to handle `NULL`-values, if it's a non-null colum... | Filter records using `NOT IN`
```
SELECT *
FROM TABLENAME
WHERE LANGUAGE = 1
AND NAME NOT IN
(
SELECT NAME FROM TABLENAME
WHERE LANGUAGE <> 1
)
``` | Sql self join where not exists? | [
"",
"sql",
"t-sql",
"join",
""
] |
My table `table1` has the column `date_txt` which includes `2/16/2011 12:00:00 AM` - column `date_txt` is `VARCHAR2 (250 Char)`.
My table `table1` also has the column `date` which is a `DATE`.
I would like to "update" my field:
The final output should be:
table1:
```
date
2/16/2011
```
So it takes from `table1... | You can use Oracle's [to\_date function](http://www.techonthenet.com/oracle/functions/to_date.php) to convert a string to a date:
```
update table1 set "date" = to_date(date_txt, 'MM/DD/YYYY HH:MI:ss AM')
```
[See it working at SQL Fiddle.](http://sqlfiddle.com/#!4/7ccd0/1) | > column date\_txt which includes 2/16/2011 12:00:00 AM
* Firstly, **DATE** doesn't have any **format**. What you see is for **display** purpose to interpret date value easily.
* Secondly, you should **never ever store DATE as VARCHAR2**. This is a big problem and a poor design.
Now that you have a bad design, it is ... | sql oracle update date | [
"",
"sql",
"oracle",
"date",
""
] |
I have three tables:
1. users: contains the registered users.
2. courses: contains available courses.
3. userscourses: has two columns: user\_id and course\_id. Whenever a user joins a course, a new record is created that relate that course with the user.
I want to create a mysql query that; given a user\_id, is goin... | Joining back on the userscourses table to get all the users on that course:-
```
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses2.userId) AS JoinedUsersNumber
FROM users
INNER JOIN usersCourses
ON users.id = usersCourses.userId
INNER JOIN courses
ON usersCourses.courseId = courses.id
INNER ... | Your join is in a deprecated style and probably wrong in content as well. Also, you need to add a Group by on courses id and name. Try this:
```
SELECT courses.id AS CourseID, courses.name AS Name, COUNT(usersCourses.userId) AS JoinedUsersNumber
FROM courses
INNER JOIN usersCourses ON usersCourses.courseId=courses.i... | Execute mysql query over multiple tables | [
"",
"mysql",
"sql",
""
] |
I need your help. I want to `union` data from the same table based on a second table with oracle SQL.
**Table 1**
```
id | au_id | data
------------------
1 | 33 | foo
2 | 44 | foo
3 | 34 | foo
4 | 55 | foobar
5 | 55 | fooo
```
**Table 2**
```
au_id | follow_au_id
-----------------------
33 |... | ```
select au_id, data from tbl
union all
select t2.au_id, t1.data from tbl t1 join tbl t2 on t1.au_id = t2.follow_au_id
```
[**SQLFiddle**](http://sqlfiddle.com/#!4/b7ec43/14) | you have to use a `join`
```
select t1.au_id, t3.data
from table1 t1
join table2 t2 on t1.au_id=t2.au_id
join table1 t3 on t2.follow_au_id = t3.au_id
union
select t1.au_id, t1.data
from table1 t1
``` | Select union table from same table based on key with oracle | [
"",
"sql",
"oracle",
"union",
""
] |
In `MyTable` is column named `Values` of `NVARCHAR` datatype. Here are placed many values like:
```
Alisa
20150111
Something 12
Etc 2222
4444
01/21/2015 11:01:12 AM
etc
```
I need select all values from this column but where format is like `mm/dd/yyyy hh:mm:ss AM/PM` I need to convert it to DATE (without time) `mm/dd... | Maybe try to check if string contains `/` as below:
```
SELECT CASE WHEN ISDATE(Values) = 1 and CHARINDEX('/',Values) > 0
THEN CONVERT(VARCHAR(20), Values, 101)
ELSE Values
END AS Val1
FROM MyTable
``` | try
```
SELECT CASE WHEN Values LIKE '__/__/____%' THEN CONVERT(VARCHAR(20), Values, 101)
ELSE Values
END AS Val1
FROM MyTable
``` | How to catch exact date format from value? | [
"",
"sql",
"sql-server",
"t-sql",
"format",
"case",
""
] |
Here's a sample data.
```
ID | Date
---------
1 | 4/21/2015 11:00:00 AM
1 | 4/21/2015 01:00:00 PM
```
Let's say it's currently 2 PM, I need to query ID number 1 only if the time difference between the Column `Date` and `Now` is >= 2 hours.
```
Select ID from Table where datediff(hour, Date, getdate()) >= 2 and ID ... | ```
select id, max(date) as date
from Table
where id = 1
group by id
having datediff(hh, max(date), getdate()) >= 2
```
Remove `where` clause and you will get all ids that satisfy condidion. | Use `MAX` with `GROUP BY` to get the latest date for an id and then check if it is greater than 2 hours. Something like this.
```
SELECT ID,Date
FROM
(Select ID,MAX(Date) Date
from Table
GROUP BY ID
)T
where datediff(hour, Date, getdate()) >= 2 and ID = 1
``` | Query to check if record has existed for more than X hours | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I currently have a `user_addresses` table:
```
id | name | address_type | address
---+------+--------------+----------
1 | John | HOME | home addr
1 | John | MAIL | mail addr
2 | Bill | HOME | home addr
3 | Rick | HOME | home addr
3 | Rick | MAIL | mail addr
```
I want to ... | Any particular reason not to use PIVOT?
[SQL Fiddle](http://sqlfiddle.com/#!4/2e6fd/6)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE t
("id" int, "name" varchar2(4), "address_type" varchar2(4), "address" varchar2(9))
;
INSERT ALL
INTO t ("id", "name", "address_type", "address")
VALUES (1, 'John... | One way to approach this is to take all ids with the "mail" record and then all the "home" record for all ids with no "mail" record:
```
select ua.*
from user_addresses us
where address_type = 'MAIL'
union all
select ua.*
from user_addresses ua
where address_type = 'HOME' and
not exists (select 1
... | Merge rows based on one column SQL | [
"",
"sql",
"oracle",
"plsql",
"oracle11g",
""
] |
I am receiving the above error when I try to execute a query on MS SQL Server 2005. It is a dynamic query built up in multiple parts. Here is the simplified structure and data:
```
CREATE TABLE [record_fields](
[field_id] [int] NOT NULL,
[campaign_id] [int] NOT NULL,
[record_import_type_id] [int] NOT NULL,
[fieldname]... | There were 2 errors. In constructing select query and campaignid in exec function:
```
DECLARE @campaignId INT
SET @campaignId = 2
DECLARE @FieldName VARCHAR(250)
DECLARE @ColumnName VARCHAR(250)
DECLARE @SelectQuery VARCHAR(2000)
DECLARE @InsertQuery VARCHAR(2000)
SET @SelectQuery = ''
SET @InsertQuery = ''
declar... | ```
SET @SelectQuery = @SelectQuery + '''"''+' + @FieldName + '+''"'', '
```
Change to
```
SET @SelectQuery = @SelectQuery + ' ' + @FieldName + ' ,'
```
If you want an often discouraged (but nonetheless very handy) shortcut to converting numbers to string, change the bit at the bottom from
```
@camp... | Conversion failed when converting the varchar value '"' to datatype int in dynamic query | [
"",
"sql",
"sql-server",
"dynamicquery",
""
] |
I have the following tables, in which I store the properties of my application (FYI I'm not directly using SQL in my app but Python Django which allows me to have a structure like that):
```
string_properties
id | name | value (type=string)
1 : module.ip : "127.0.0.1"
2 : module.name : "a_... | If you "don't want to lose the types", you can select the underlying type as a constant in the `UNION`:
```
CREATE VIEW all_properties AS
SELECT id, name, typ, value
FROM (
SELECT sp.id AS id
, sp.name AS name
, 'String' AS typ
, sp.value AS value
FROM string_properties sp
UN... | ```
SELECT id, name, value AS value_int, null AS value_string, null AS value_bool
FROM integer_properties
UNION ALL
SELECT id, name, null AS value_int, value AS value_string, null AS value_bool
FROM string_properties
UNION ALL
SELECT id, name, null AS value_int, null AS value_string, value AS value_bool
FROM boolean_pr... | SQL Union with tables with different types | [
"",
"mysql",
"sql",
"postgresql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.