October 27, 2010 at 11:51 am
Hi All,
I have to compare the values in the column of the table which is a resultset of two views.
The table is something like this-
field1 field2
position1 b
position1 b
position2 a
position2 a
position3 a
position3 b
The result should be-
( the logic is-
if position(field1) has all b's the flag should be 2
if position has all a's the flag should be 1
if position has the combination of a and b the flag should be 3
field1 field2 flag
position1 b 2
position1 b 2
position2 a 1
position2 a 1
position3 a 3
position3 b 3
I dont want to create one more view on top of the actual result set which is the combination of views( performance issue.. locking etc.)
I greatly appreciate the help.
Thank you,
Sravan
October 27, 2010 at 4:33 pm
Here is your test data in a readily consumable form, i.e. a CREATE TABLE statement and an INSERT statement. Supplying test data in this form will encourage people to assist you, and therefore tends to lead to a greater number of responses in a shorter time.
CREATE TABLE #t (
field1 varchar(20) NOT NULL,
field2 char(1) NOT NULL
)
INSERT INTO #t(field1, field2)
SELECT 'position1', 'b' UNION ALL
SELECT 'position1', 'b' UNION ALL
SELECT 'position2', 'a' UNION ALL
SELECT 'position2', 'a' UNION ALL
SELECT 'position3', 'a' UNION ALL
SELECT 'position3', 'b'
I'm not sure which version of SQL Server you are using, but the following queries should work on any version of SQL Server from 2000 or later. If the field2 column cannot possibly take any value other than 'a' or 'b', the query could be written as follows:
SELECT T.field1, T.field2, CASE
WHEN (AGG.CountA = AGG.CountAll) THEN 1
WHEN (AGG.CountB = AGG.CountAll) THEN 2
ELSE 3 END AS Flag
FROM #t AS T INNER JOIN (
SELECT field1,
COUNT(1) AS CountAll,
COUNT(CASE WHEN field2 = 'a' THEN 1 END) AS CountA,
COUNT(CASE WHEN field2 = 'b' THEN 1 END) AS CountB
FROM #t
GROUP BY field1
) AGG ON (T.field1 = AGG.field1)
This second version of the query will return NULL for the Flag column if there is any value of the field2 column in a group (grouped by field1) that is neither 'a' nor 'b'.
SELECT T.field1, T.field2, CASE
WHEN (AGG.CountA = AGG.CountAll) THEN 1
WHEN (AGG.CountB = AGG.CountAll) THEN 2
WHEN (AGG.CountA + AGG.CountB = AGG.CountAll) THEN 3
ELSE NULL END AS Flag
FROM #t AS T INNER JOIN (
SELECT field1,
COUNT(1) AS CountAll,
COUNT(CASE WHEN field2 = 'a' THEN 1 END) AS CountA,
COUNT(CASE WHEN field2 = 'b' THEN 1 END) AS CountB
FROM #t
GROUP BY field1
) AGG ON (T.field1 = AGG.field1)
October 27, 2010 at 6:52 pm
Thank you very much smith..
It was a great help.
October 28, 2010 at 12:49 pm
I have one more question regarding this..
Can we store the result set in a view.
If yes how and when will the temp table is dropped.
Please help.
Thank you,
Sravan
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply