MSSQL: find records that has each value of column - sql

Let's say I have some the following table schema:
year|val1|val2
I want to get all the val1 and val2 columns that has all values of year column. I suspect I need grouping here, but I can't imagine how.
Let's say we have set of years from query: SELECT DISTINCT YEAR FROM table. Let's say it returned 2000,2001. So If I have to rows as 2000|1|2 and 2001|1|2 then the query should return single row 1|2

Something like this may work
select
value1
from
table as t1 inner join
(select distinct year from table) as t2
on t1.year=t2.year
group by
val1
having count(distinct t1.year)=(count(distinct t2.year) )

Not sure about your question. But I think you need all the values of val1 and val2 which are there for all the valid values of years.If that's the case then you have to do inner join with the table
something like this
select #yearcnt = count(distinct year) from table
or select val1,count(distint year) as totalyear from table
group by val1
having count(distinct year) = #yearcnt

Related

Select a row of the table with desired value, when a column's value which is not in the table is selected in where clause in keyword?

I have a table with one of the columns as ID. I have a set of values which I give in the where clause to compare the 'ID' column using 'in' keyword. I want to select the row if the value in that set of values has a record in the table. If not, the value that is not in the table has to be selected along with empty values other columns.
For example:
There is a table with columns ID & Animal. It has 8 records.
The table with all records
If I run the query:
SELECT ID, Animal from #Temp1 where ID in (4,8)
it will return the following result.
The table result filtered
But, if I run the query:
SELECT ID, Animal from #Temp1 where ID in (4,8,12)
it should return the following result.
The table result with desired values
Use a LEFT JOIN in concert with string_split() instead
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From string_split('4,8,12',',') A
Left Join YourTable B on A.value=B.ID
Results
ID Animal
4 Donkey
8 Hampster
12 ID Not Found
If by chance string_split() is not available
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From (values (4)
,(8)
,(12)
) A(value)
Left Join YourTable B on A.value=B.ID

Update a table in SQL Server 2008 R2 by a column in another table and also need a sum value

I am trying to update a table in SQL Server 2008 R2.
Table1:
id name value1
a 34 3
a 32 2
a - -
c 90 9
Table2:
id
a
expected table1:
id name value1
a 34 3
a 32 2
a - 5
c 90 9
I need to sum all value1 group by id that exists in table2.
My SQL query:
update table1
set value1 = cast(SUM(cast ([value1] as float)) as varchar(50))
GROUP BY id
where name = '-' and id in
(
select distinct id
from table2
)
I got error:
Incorrect syntax near the keyword 'GROUP'.
Any help would be appreciated.
UPDATE
update table1
set value1 = cast(SUM(cast ([value1] as float)) as varchar(50))
where name = '-' and id in
(
select distinct id
from table2
)
GROUP BY id
still :
Incorrect syntax near the keyword 'GROUP'.
You can't use that construct afaik. You need a subquery to calculate your values based on id, and update from that table:
UPDATE table1
SET value1 = SumTable.val
FROM (
SELECT T1.id, cast(SUM(cast (T1.[value1] as float)) as varchar(50)) as val
FROM table1 T1
WHERE T1.id in
(
select distinct T2.id
from table2 T2
)
GROUP BY T1.id
) AS SumTable
WHERE table1.id = SumTable.id
If you just want to return the grouped result, you can do this by running the following
SELECT ID, SUM(Value)
FROM Table1
WHERE ID IN (SELECT ID FROM Table2) GROUP BY ID
If, however, you want to replace the contents of table1, there's no trivial way of doing this in a single operation. You need 'cache' the intermediate result before recreating the original table:
DECLARE #TEMPTABLE TABLE (ID int, Value int);
INSERT INTO #TEMPTABLE SELECT ID, SUM(Value)
FROM Table1
WHERE ID IN (SELECT ID FROM Table2) GROUP BY ID
DROP TABLE Table1
SELECT * INTO Table1 FROM #TempTable
SELECT * FROM TABLE1
(note, that was from your first edit)
If you just want to add additional 'sum' lines to the table, then you should be able to avoid the temp table and instead issue an INSERT INTO statement using the SELECT statement I gave first as a sub-query.
I do think what you're doing is quite strange, however, and you may want to think about what you're doing with your tables.
Your casting back to a VARCHAR is also a little strange - if they're always going to be an integer, keep them as integers. If they're truly VARCHARS then SUM won't always work

Count the number of pairs in SQL

I have a column and I would like to count the number of unique pairings of the elements within the column in SQL, for example, in Col 1 the number of unique pairings should be 6: ([1,2],[1,3],[1,4],[2,3],[2,4],[3,4]). Thanks!
col 1,
1
2
3
4
Consider a scenario where in we have dulpicates values in the table say
col1
1
1
2
3
4
5
The total number of unique combinations is 10:([1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4][3,5],[4,5]).
But the given query below is giving me a count of 14 because of the dulplicate 1 which is counting 4 extra pairs [1,2],[1,3],[1,4],[1,5] twice.
select count(*)
from table t1 join
table t2
on t1.col1 < t2.col1;
To modify this defect I have the following query which ensures that the duplicates are removed and we get the correct output.The table name I have chosen is countunique which can store integer values in it in column named col1.
select count(*) from
(select distinct col1 from countunique) t1
join (select distinct col1 from countunique) t2
on t1.col1<t2.col1
SQL Fiddle for your reference SQLFIDDLE
Hope this answers to your question.
There are two ways. The cumbersome way is to generate the pairs and then count them:
select count(*)
from table t1 join
table t2
on t1.col1 < t2.col1;
The simpler way is to use a formula:
select count(*) * (count(*) - 1) / 2
from table t;

SQL Distinct value over joined tables

I am trying to get the DISTINCT value of one column in a table. This column however is INNER JOINED from another table through an id.
When I try to use the DISTINCT on the column, it produces the same results because DISTINCT also takes into account the unique identifier ID. Is there any work around for this to just get the DISTINCT value of a column from a joined table???
EG.
SELECT val1, b.val2, val3
FROM TABLE 1
JOIN (SELECT DISTINCT val2
FROM TABLE 2) AS b ON val1 = b.val2
Try throwing in a GROUP BY instead of a DISTINCT:
SELECT val1
, b.val2
, val3
FROM TABLE 1
JOIN (SELECT val2
FROM TABLE 2 GROUP BY val2) AS b ON val1 = b.val2
To provide my solution:
I ended up using a nested distinct through a join and all the unnested values (all 20+) of them had to be wrapped around a MIN(x), seeing as those values didnt matter that much, so long as only one distinct value was returned.

Select DISTINCT, return entire row

I have a table with 10 columns.
I want to return all rows for which Col006 is distinct, but return all columns...
How can I do this?
if column 6 appears like this:
| Column 6 |
| item1 |
| item1 |
| item2 |
| item1 |
I want to return two rows, one of the records with item1 and the other with item2, along with all other columns.
In SQL Server 2005 and above:
;WITH q AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY col6 ORDER BY id) rn
FROM mytable
)
SELECT *
FROM q
WHERE rn = 1
In SQL Server 2000, provided that you have a primary key column:
SELECT mt.*
FROM (
SELECT DISTINCT col6
FROM mytable
) mto
JOIN mytable mt
ON mt.id =
(
SELECT TOP 1 id
FROM mytable mti
WHERE mti.col6 = mto.col6
-- ORDER BY
-- id
-- Uncomment the lines above if the order matters
)
Update:
Check your database version and compatibility level:
SELECT ##VERSION
SELECT COMPATIBILITY_LEVEL
FROM sys.databases
WHERE name = DB_NAME()
The key word "DISTINCT" in SQL has the meaning of "unique value". When applied to a column in a query it will return as many rows from the result set as there are unique, different values for that column. As a consequence it creates a grouped result set, and values of other columns are random unless defined by other functions (such as max, min, average, etc.)
If you meant to say you want to return all rows for which Col006 has a specific value, then use the "where Col006 = value" clause.
If you meant to say you want to return all rows for which Col006 is different from all other values of Col006, then you still need to specify what that value is => see above.
If you want to say that the value of Col006 can only be evaluated once all rows have been retrieved, then use the "having Col006 = value" clause. This has the same effect as the "where" clause, but "where" gets applied when rows are retrieved from the raw tables, whereas "having" is applied once all other calculations have been made (i.e. aggregation functions have been run etc.) and just before the result set is returned to the user.
UPDATE:
After having seen your edit, I have to point out that if you use any of the other suggestions, you will end up with random values in all other 9 columns for the row that contains the value "item1" in Col006, due to the constraint further up in my post.
You can group on Col006 to get the distinct values, but then you have to decide what to do with the multiple records in each group.
You can use aggregates to pick a value from the records. Example:
select Col006, min(Col001), max(Col002)
from TheTable
group by Col006
order by Col006
If you want the values to come from a specific record in each group, you have to identify it somehow. Example of using Col002 to identify the record in each group:
select Col006, Col001, Col002
from TheTable t
inner join (
select Col006, min(Col002)
from TheTable
group by Col006
) x on t.Col006 = x.Col006 and t.Col002 = x.Col002
order by Col006
SELECT *
FROM (SELECT DISTINCT YourDistinctField FROM YourTable) AS A
CROSS APPLY
( SELECT TOP 1 * FROM YourTable B
WHERE B.YourDistinctField = A.YourDistinctField ) AS NewTableName
I tried the answers posted above with no luck... but this does the trick!
select * from yourTable where column6 in (select distinct column6 from yourTable);
SELECT *
FROM harvest
GROUP BY estimated_total;
You can use GROUP BY and MIN() to get more specific result.
Lets say that you have id as the primary_key.
And we want to get all the DISTINCT values for a column lets say estimated_total, And you also need one sample of complete row with each distinct value in SQL. Following query should do the trick.
SELECT *, min(id)
FROM harvest
GROUP BY estimated_total;
create table #temp
(C1 TINYINT,
C2 TINYINT,
C3 TINYINT,
C4 TINYINT,
C5 TINYINT,
C6 TINYINT)
INSERT INTO #temp
SELECT 1,1,1,1,1,6
UNION ALL SELECT 1,1,1,1,1,6
UNION ALL SELECT 3,1,1,1,1,3
UNION ALL SELECT 4,2,1,1,1,6
SELECT * FROM #temp
SELECT *
FROM(
SELECT ROW_NUMBER() OVER (PARTITION BY C6 Order by C1) ID,* FROM #temp
)T
WHERE ID = 1