Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 SQL script

Author  Topic 

Db_new
Starting Member

2 Posts

Posted - 2008-08-07 : 06:01:26
Hi Experts,

I am a newbie in T-sql Programming.
Please help me.

I have two tables as below

Table1 (Table1 has data that are constant datas)
Group Data1 Data2 Data3

Table2
Name, Group, Data1, Data2, Data3


My result set should be as

Name, Group, Data1, Data2, Data3

Condition is that, if in the table2 i.e if column Data1 or data2 or Data3 have a value 1, in the result it have to fetch the corresponding data from table 1

Please help me writing a query for this.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-08-07 : 06:08:35
Lookup LEFT JOIN.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

Db_new
Starting Member

2 Posts

Posted - 2008-08-07 : 06:52:00
Thanks for the reply

If the table2 data colum is 1, it should take the balue from table1 , if the value is 0, then it should be 0


Eg

Table 1
group data1 data2 data3
ONE 60 70 80
TWO 30 40 50

Table 2
Name group data1 data2 data3
SASY ONE 1 0 0
SANY TWO 0 1 0


Result

Name group data1 data2 data3
SASY ONE 60 0 0
SANY TWO 0 40 0

Please help me
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-08-07 : 08:07:19
Use a CASE statement..


DECLARE @table1 TABLE (
[group] VARCHAR(50)
, [data1] INT
, [data2] INT
, [data3] INT
)

DECLARE @table2 TABLE (
[name] VARCHAR(50)
, [group] VARCHAR(50)
, [data1] INT
, [data2] INT
, [data3] INT
)

INSERT INTO @table1
SELECT 'ONE', 60, 70, 80
UNION SELECT 'TWO', 30, 40, 50

INSERT INTO @table2
SELECT 'SASY', 'ONE', 1, 0, 0
UNION SELECT 'SANY', 'TWO', 0, 1, 0

SELECT
t2.[name]
, CASE t2.[data1] WHEN 1 THEN t1.[data1] ELSE 0 END
, CASE t2.[data2] WHEN 1 THEN t1.[data2] ELSE 0 END
, CASE t2.[data3] WHEN 1 THEN t1.[data3] ELSE 0 END
FROM
@table2 t2
JOIN @table1 t1 ON t1.[group] = t2.[group]



-------------
Charlie
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-08-07 : 13:33:23
quote:
Originally posted by Db_new

Thanks for the reply

If the table2 data colum is 1, it should take the balue from table1 , if the value is 0, then it should be 0


Eg

Table 1
group data1 data2 data3
ONE 60 70 80
TWO 30 40 50

Table 2
Name group data1 data2 data3
SASY ONE 1 0 0
SANY TWO 0 1 0


Result

Name group data1 data2 data3
SASY ONE 60 0 0
SANY TWO 0 40 0

Please help me


SELECT t2.Name,t2.group,
t2.data1*t1.data1 as data1,
t2.data2*t1.data2 as data2,
t2.data3*t1.data3 as data3
FROM Table2 t2
JOIN Table1 t1
ON t2.group=t1.group
Go to Top of Page
   

- Advertisement -