Select Two Columns At Same Time

Aug 27, 2007

 

how can i retrieve two columns from sqltable with - seperating the results and a common column name

someth like this

select id ,name from user

id     name

1         a

2         b

3         c

i need the result set to be

my_reports

1-a

2-b

3-c

is that possible, if so, could anyone tell me how to do?

 

View 3 Replies


ADVERTISEMENT

Transact SQL :: Select And Parse Json Data From 2 Columns Into Multiple Columns In A Table?

Apr 29, 2015

I have a business need to create a report by query data from a MS SQL 2008 database and display the result to the users on a web page. The report initially has 6 columns of data and 2 out of 6 have JSON data so the users request to have those 2 JSON columns parse into 15 additional columns (first JSON column has 8 key/value pairs and the second JSON column has 7 key/value pairs). Here what I have done so far:

I found a table value function (fnSplitJson2) from this link [URL]. Using this function I can parse a column of JSON data into a table. So when I use the function above against the first column (with JSON data) in my query (with CROSS APPLY) I got the right data back the but I got 8 additional rows of each of the row in my table. The reason for this side effect is because the function returned a table of 8 row (8 key/value pairs) for each json string data that it parsed.

1. First question: How do I modify my current query (see below) so that for each row in my table i got back one row with 19 columns.

SELECT A.ITEM1,A.ITEM2,A.ITEM3,A.ITEM4, B.*
FROM PRODUCT A
CROSS APPLY fnSplitJson2(A.ITEM5,NULL) B

If updated my query (see below) and call the function twice within the CROSS APPLY clause I got this error: "The multi-part identifier "A.ITEM6" could be be bound.

2. My second question: How to i get around this error?

SELECT A.ITEM1,A.ITEM2,A.ITEM3,A.ITEM4, B.*, C.*
FROM PRODUCT A
CROSS APPLY fnSplitJson2(A.ITEM5,NULL) B,  fnSplitJson2(A.ITEM6,NULL) C

I am using Microsoft SQL Server 2008 R2 version. Windows 7 desktop.

View 14 Replies View Related

T-SQL (SS2K8) :: Select Group On Multiple Columns When At Least One Of Non Grouped Columns Not Match

Aug 27, 2014

I'd like to first figure out the count of how many rows are not the Current Edition have the following:

Second I'd like to be able to select the primary key of all the rows involved

Third I'd like to select all the primary keys of just the rows not in the current edition

Not really sure how to describe this without making a dataset

CREATE TABLE [Project].[TestTable1](
[TestTable1_pk] [int] IDENTITY(1,1) NOT NULL,
[Source_ID] [int] NOT NULL,
[Edition_fk] [int] NOT NULL,
[Key1_fk] [int] NOT NULL,
[Key2_fk] [int] NOT NULL,

[Code] .....

Group by fails me because I only want the groups where the Edition_fk don't match...

View 4 Replies View Related

SELECT Query - Different Columns/Number Of Columns In Condition

Sep 10, 2007

I am working on a Statistical Reporting system where:


Data Repository: SQL Server 2005
Business Logic Tier: Views, User Defined Functions, Stored Procedures
Data Access Tier: Stored Procedures
Presentation Tier: Reporting ServicesThe end user will be able to slice & dice the data for the report by


different organizational hierarchies
different number of layers within a hierarchy
select a organization or select All of the organizations with the organizational hierarchy
combinations of selection criteria, where this selection criteria is independent of each other, and also differeBelow is an example of 2 Organizational Hierarchies:
Hierarchy 1


Country -> Work Group -> Project Team (Project Team within Work Group within Country)
Hierarchy 2


Client -> Contract -> Project (Project within Contract within Client)Based on 2 different Hierarchies from above - here are a couple of use cases:


Country = "USA", Work Group = "Network Infrastructure", Project Team = all teams
Country = "USA", Work Group = all work groups

Client = "Client A", Contract = "2007-2008 Maint", Project = "Accounts Payable Maintenance"
Client = "Client A", Contract = "2007-2008 Maint", Project = all
Client = "Client A", Contract = allI am totally stuck on:


How to implement the data interface (Stored Procs) to the Reports
Implement the business logic to handle the different hierarchies & different number of levelsI did get help earlier in this forum for how to handle a parameter having a specific value or NULL value (to select "all")
(WorkGroup = @argWorkGroup OR @argWorkGrop is NULL)

Any Ideas? Should I be doing this in SQL Statements or should I be looking to use Analysis Services.

Thanks for all your help!

View 1 Replies View Related

How To Select Columns When Columns Change

Aug 13, 2007

I have a scenario that reminds me of a pivot table and I am wondering if there is a way to handle this in SQL.

I have four tables. Product Line, Item, Property, and Value.

A Product Line has many items and an item can have many property's and a property can have many values.

I want to select a product line and show all the items with the Property's as column headers and the Values as the data. The thing I am having trouble with is the property's for an item are variable from a few to a whole bunch.

Any help would be appreciated.

Thanks,
vmon

View 2 Replies View Related

Updating Several Columns At The Same Time

Jun 18, 2002

Good morning,
I want to update two columns in the same time by making a select from another table. Some think like the following;

Update TBL1 o set (o.COL1,o.COL2) =
(select f.COL1,f.COL2 from TBL2 f where f.PKY = o.PKY)
where o.COL3 = 100;

Thinks to helping me .

View 1 Replies View Related

Updateing 2 Columns At The Same Time

Jul 3, 2007

Hi please help me out !!
I have to update the incidents table.
The initiator and initdept are two corresponding columns in incidents table whoes value I have to get from another table Employee where (initiator means Empname and initdept means title)
if i just do

select Empname,title from employee

it gives me correct output while

select initiator,initdept from incidents

It gives the initiator correct but instead of giving the initdept
it gives output as initaiator
The Output is given below

initiator initdept
Jeff C. Taylor Jeff C. Taylor
Randy S. Jonas Randy S. Jonas
Mike lewis Mike lewis

it should give the out put like

initiator initdept
Jeff C. Taylor Software Engg
Randy S. Jonas Tester

I hope you got my question!
now I hav to update incidents table such that it should give initiator as well as its corrosponding initdept

thanks

View 5 Replies View Related

How To Add Columns And Use Them At Run Time Using VB 2005

Sep 11, 2007

In order to allow my customers to use their existing data and install updated application, I want to be able to add columns to existing CE tables at startup time, and allow the user to enter data into the new column(s) immediately. I used the ALTER TABLE command as shown in the example below:

cmd.CommandText = "ALTER TABLE tblStores ADD dtDemoDate datetime, dtDemoMode int"

cmdexe = cmd.ExecuteNonQuery()
To add the column, But this does not set the columns in the attached dataset. The program sees the columns and data is able to be added, but is not then in the underlying table? What else do I need to do?

Thank you - b2bMan

View 1 Replies View Related

ODB Datareader Time Columns

May 26, 2006

I am using an ODBC Datareader to connect to a proprietary DB (Epex) and I need help on column mappings.

The Epex database has a number of time columns which we successfully imported using SQL 2000 DTS by defining these as varchar(5).

When using SSIS (Service Pack 1) these fields are shown as 'eight-byte signed integer [DT_I8]'.

I have attempted to these columns to both [DT_WSTR] and [DT_STR]' without success.

I can change the External Column type to [DT_WSTR] but I am unable to alter the Output Coulmns, when doing so I get the following error message:

Error at Data Flow Task [DataReader Source [1]]: The data type of output columns on the component "DataReader Source" (1) cannot be changed.

Does anyone know how to resolve this issue?

Regards

JLF







View 11 Replies View Related

How Can I Update 2 Columns At A Time In 2 Tables

Mar 11, 2002

Hi
I have a 2 Tables EMP, STU
In EMP Table there is a Column "Country"
In STU Table there is a Column "City"
Where the EMPID = STUID
on this conditon how can i update those 2 columns

This is for one Table one column update how can i do 2 at a time
I don't want to do in 2 seperate UPDATE statements

UPDATE EMP
SET EMP.Country = 'USA'
WHERE EMP.EMPID = STU.STUID


Can some one can help me to fix this issue..


From
Madhavi

View 2 Replies View Related

How To Replace Values In Different Columns At The Same Time

May 14, 2004

HI,

I AM HAVING A TABLE WHICH HAS INCREMENTAL COLUMNS,WHERE COLUMNS GETS ADDED EVERY MONTH TO THE TABLE AND THE TABLE THEN CONTAINS PREVIOUS MONTH AND PRESENT MONTH DATA ABOUT CUSTOMERS ,DETAILS AND TRANSACTIONS.
THE PROBLEM WITH THIS DATA IS ,IF THE CUSTOMER IS NEW ,THEN IN PREVIOUS MONTHS HIS INFORMATION IS NULL,WHICH HAVE TO BE CODED HAS "NOT PRESENT".

NOW,
HOW DO WE CONVERT ALL THE PREVIOUS COLUMNS FOR A PARTICULAR CUSTOMER HAS NULL AT THE SAME TIME ?.

HERE IS HOW THE PROC WRITTENED FOR IT GOES :-


DROP PROCEDURE DE_NAT
CREATE PROCEDURE DE_NAT
AS
BEGIN
DECLARE @MONMIN1 NVARCHAR(100),MON NVARCHAR(100),@YEAR NVARCHAR(100) , @MONYEAR NVARCHAR(100)
SET @MONMIN1 = DATENAME((MONTH),DATEADD(MONTH,-1,GETDATE()))
SET @MON = MONTH(GETDATE())
SET @YEAR = YEAR(GETDATE())
SET @MONYEAR = @MON + @YEAR

EXEC('select A.CUSTOMERS,B.*,CAST(A.RFM_40D AS FLOAT) AS R40
INTO TSD_' + @MONYEAR
+ ' from TSD_20 A
LEFT OUTER JOIN SD20 ' + @MONMIN1 + ' B
ON A.CUSTOMERS = B.CUSTOMER')
END


THIS PROC JUST ADDS THE PRESENT MONTHS DATA TILL LAST MONTHS DATA.

BUT IF A CUSTOMER IS NEW, THEN HOW DO I REPLACE THE NULL VALUES FOR THE PREVIOUS DATA TO 'NOT PRESENT'

FOR EG :- IF THERE IS A NEW CUSTOMER ,HOW DO WE CHANGE :-

CUSTOMERS ERTYYTRE RTYUUYTR TYUIIUYT QWERREWQ DFGHHGFD
----------- ---------- ---------- ---------- ----------- ----------
101023 <NULL> <NULL> <NULL> <NULL> 1.0
102022 1.0 1.62.3 3.4 4.5


NOW, AS YOU CAN SEE, THAT FOR CUSTOMERS = '101023'.
THE COLUMN DFGHHGFD IS, THIS MONTHS DATA , I WANT TO CHANGE ALL NULL VALUES PRESIDING IT AS "INACTIVE"

CAN I CHANGE , ALL COLUMNS FROM NULL TO "INACTIVE" , AT THE SAME TIME. ?


AS NEXT MONTH, AGAIN THE COLUMNS IS GONNA INCREASE WHICH WILL
AGAIN CAUSE A PROBLEM .

PLS TELL ME A METHOD , SO THAT I CAN DO THE NEEDFUL.

View 6 Replies View Related

Adding Columns With Different Time Unit

Oct 29, 2014

I have three different columns, hour(s), min(s), sec(s)

I can add it up, but will like to convert it into. hrs, mins and sec.

this is how, i am adding it up into seconds.

SELECT ((TotalTimeSpentHrs*60*60)+(TotalTimeSpentMin*60)+(TotalTimeSpentSec))AS totaltime
FROM EST1

How can I convert the total seconds, so that i can input the result in a new column.

View 1 Replies View Related

How To Alter Multiple Columns At Time

Dec 4, 2006

Hi all

ALTER TABLE <Table_Name> ALTER COLUMN <column_name> <Data_type>

above query alters the sigle column but how to alter multiple columns at time

saivyshnav
Junior DBA

View 7 Replies View Related

Combine 2 Columns To Get Date Time

Aug 28, 2007

adate atime
08-21-2007 11:09
08-20-2007 16:49
08-03-2007 00:39

I would like to combine adate with atime to get adatetime

View 5 Replies View Related

Can I Use OUTER JOIN On 2 Columns At The Same Time?

Sep 12, 2007



I have Table1 with 2 columns Label_ID and Athlete_ID, I have another Table2 with 3 columns Label_ID, Athlete_ID, Data.
I need join this tables so the result table will have the same number of rows as Table1 and have extra column add Data which will correspond to Data in Table2 if Label_ID an Athlete_ID are matched and NULL if no matches found.
I have following query which does not produce desired result


SELECT Table1.label_id, Table1.athlete_id, data FROM Table1 LEFT OUTER JOIN Table2 on (Table1.label_id = Table2.label_id AND Table1.athlete_id = Table2.athlete_id)




The end result of this is table with only rows where label_id and athlete_id are matched between tables but no results when they are not. I expected OUTER JOIN to have those result but it's not working for whatever reason.
I'm pretty sure it's simple solution but can not figure out myself.

View 4 Replies View Related

Dynamic Time On Columns With Reporting Services

May 17, 2005

Hi all!

If I have some mdx I'm using in reporting services like this:

select
{ [TimeByMinute].[All TimeByMinute].[2005].[May].[1] : [TimeByMinute].[All TimeByMinute].[2005].[May].[6] } on columns,
{A_list_of_measures } on rows
from ACD_Calls

The column names are unique to the day of month- which means when I use a table to display this in reporting services, the field names change dynamically when the date parameters change which means the table stops working.

I'll post this in reporting services too but I thought maybe I could alias the column names in mdx shielding the reporting services table from changes in dates.

What do you think? Would a matrix be more flexible in this case?

Richard

View 7 Replies View Related

Get Latest Records When Date And Time Are Separate Columns?

Mar 26, 2012

I have 2 tables:

TransactionsImport (which is the destination table)
TransactionsImportDelta

I need to do the following:

Get the records with the latest date and time in the destination table TransactionsImport
Get the records with the latest date and time in the destination table TransactionsImportDelta table
Insert the records from the TransactionsImportDelta table into TransactionsImport that have a greater date & time than the current records in TransactionsImport table.

Problem is date & time are in separate columns:

Table structure:

Date Time ID
2011121305154107142201008300100
2011121305154122B1L13ZY0000A07YD
2011121304504735142201090002600
2011121304504737142201095008300
2011121304504737142201090002600

View 2 Replies View Related

T-SQL (SS2K8) :: Matching Closest Time Between Two Columns Between Tables?

Mar 10, 2014

I have a temperature table with a column that shows the how many hours old a newborn was when his/her temperature was taken.

Example lets say once per hour.

I want to join to a table called Weight that records the newborns weight at any given time.

Example lets say 3x during the day.

1 @ 8:45am
2 @ 11:15am
3 @ 4:30pm

I want to figure out which weight recording is the closest to a given temperature recording and return that one row.

View 2 Replies View Related

Transact SQL :: Represent Time Interval Between 2 Date Columns

May 20, 2015

I have a simple table as shown:

I want to have values on the last column to represent the time interval between the 2 date columns (visits); i.e for event-ID 2 for example, I will have

entry(EventID = 2)  - exit(EventID = 1), and so on

View 7 Replies View Related

Is There A Way To Drop All The Columns Called Some_name In All The Tables At The Same Time

May 15, 2008

Hi,

In my DB, many of my tables have a column named upsize_ts I have already been told that it is not linked in any way with the data in the DB. The data type of these columns is timestamp and every record in those colum is this : "<Binary>"
Now maybe it's because the whole DB comes from an export from an Access DB, or maybe not. I just had a few questions:

1/ Does anyone know why that column got generated and what it means? (optional)
2/Now the real question: is there any statement allowing me to "mass-drop" all those columns named "upsize_ts" in every table of my DB at the same time? Or at least any way not to do it one drop table at a time?


Thanks.

View 8 Replies View Related

SELECT Field &> 1 Time

Dec 15, 2006

hello !

for MS SQL 2000

how can I get something like

SELECT name from users WHERE Count(name) > 1

i want to return only the rows where name appears more than 1 time

thank you

View 12 Replies View Related

Select Permssion On Certain Columns

Dec 20, 2006

I know you can restrict/grant select rights to certain columns in SQL Server table. My question is if in a select query, where you list out the columns (select colum1, column2...) that you have select rights on do you also have to have select rights on columns that apear in where clause or the columns in a join? For example say I have select rights on column1 and column2 of test table, but not on column3. If I run a select statement like this: select column1, column2 from test where column3 = 'abc'  Will I get a select persmission denied because the query is using column3 in the where clause. David 

View 2 Replies View Related

SELECT Columns Programatically

Jul 31, 2007

Hi, I've written a SELECT statement that returns columns dependant on a bitwise parameter @Populate.SELECTCASE WHEN (1 & @Populate) = 1 THEN [Column1] ELSE Null END AS [Column1],CASE WHEN (2 & @Populate) = 2 THEN [Column2] ELSE Null END AS [Column2],CASE WHEN (4 & @Populate) = 4 THEN [Column3] ELSE Null END AS [Column3],CASE WHEN (8 & @Populate) = 8 THEN [Column4] ELSE Null END AS [Column4],etcIs this the most efficient way to acheive this since I am only seeing a small performance gain. It still returns all columns but depending on @Populate will leave some columns with Null values.Any help much appreciated, thanks. 

View 7 Replies View Related

Select From Two Different Field Columns.

May 22, 2006

OK, i'm sure this is an easy one, but can't seem to figure it out. Basically need to search against two database columns (fields) to see if either contain the work "test". Here is an example of the statement but of course dosn't work correctly:
SELECT * FROM tbl_db WHERE skills LIKE 'test' AND title LIKE 'test' 
Please note the AND is incorrect.
What i need to accomplish:
if one record contains 'test' in its skills field then SELECT it.
if one record contains 'test' in the title field the SELECT it.
I need to make sure that is 'test' is in both skills and title fields then only display once.
Thanks,
Jake
 
 

View 5 Replies View Related

Select Columns That May Exist

Jul 16, 2007

I am working with several similar tables that for the most part contain the same columns. I need to export these tables to different csv files, and the csv file needs to have all possible column names and blank fields if the column does not exist in the table. Basically a set and subset thing.

for example
TABLE AA has three columns A, B, C
and
TABLE AB has 2 columns B, D

I am working with over 200 tables, and am planning on automating this with c#. I could use the information_schema to create the SQL statement for each tabel but it sems like I should also be able to do this using one select statement.

I want to write a select statement that combines this.
SELECT
[A],
[B],
[C],
'' AS [D]
FROM
[AA]

SELECT
'' AS [A],
[B],
'' AS [C],
[D]
FROM
[AB]

View 1 Replies View Related

How To Put Select Output Into Different Columns?

Oct 27, 2004

I have a table like:

ID Disc
----------------
1 BUSH
2 JOHN
1 GOLE
2 MIKE

I would like output depending on ID to put Disc into two columns. Like:

ID Disc1 Disc2
----------------------------
1 BUSH NULL
2 NULL JOHN
1 GOLE NULL
2 NULL MIKE

Any help will be appreciated. Thanks

ZYT

View 2 Replies View Related

Select Where LIKE From Multiple Columns

May 20, 2008

I am using mySQL and the following query works fine:

SELECT * from listings where name LIKE "%$trimmed%" order by name";

and so does this query:

SELECT * from listings where keywords LIKE "%$trimmed%" order by name";

however, I can't seem to combine the two with an OR statement as this query only returns the results from the first LIKE column

select * from listings where name LIKE "%$trimmed%" or keywords LIKE "%$trimmed%" order by name

I want to be able to search both columns and return a row if the NAME column or the KEYWORDS columns contains a string.

View 1 Replies View Related

Select Max Int Column And Other Columns

Feb 27, 2015

I have three records, with one column that is an identity/PK. I want the last record inserted and the whole record's information from the query, using a where clause to limit the record returned from the table.

I get an error if I do not have the group by added. However, with this query, I still get three records returned.

SELECT max([tablePK])
,[orderGUID]
,[tblPeopleFK]
,[tbl_shippingAddressFK]
,[tblBillingMethodFK]
,[shippingMethod]

[Code] ....

View 1 Replies View Related

Select Data From Top N Columns

Aug 8, 2005

Suppose you have table with many columns and often you need data from first 15 or 20 columns. In that case you have to specify all the columns in your select statement. This procedure will select top N columns you want. All you have to do is to supply table name and number of columns you want

Here is the procedure



Create procedure TopNcolumns (@tableName varchar(100),@n int)
as
Declare @s varchar(2000)
set @s=''
If exists(Select * from information_Schema.tables where table_name=@tablename and table_type='Base Table')
Begin
If @n>=0
Begin
set rowcount @n
Select @s=@s+','+ column_name from information_schema.columns
where table_name=@tablename order by ordinal_position
Set rowcount 0
Set @s=substring(@s,2,len(@s)-1)
Exec('Select '+@s+' from '+@tablename)
End
else
Select 'Negative values are not allowed' as Error
End
else
Select 'Table '+@tableName+' does not exist' as Error



Madhivanan

Failing to plan is Planning to fail

View 3 Replies View Related

Combine Columns In Select

Aug 20, 2007

I would appreciate any help with my following problem... lets say
i have...

select A.firstname + '' + B.lastname as fullname, 'Their Home is ' + A.City + ' ' + (select top 1 C.State from States C where C.City = A.City) as Location
from tableA A, TableB B
Where A.id = b.id

This is not the actual statement but follows the same kinda logic... the problem that i get is that some of the rows in both my fullname column and in my location column show up as null... how would i fix it so for instance even if the state is missing it would still show: their home is LA or if just the last name is available it would show the lastname?

Thank you

View 2 Replies View Related

Insert First N Columns From Select

Mar 1, 2006

I have to insert data from about 30 tables into a single table (Users),to do so i used a cursor and a bit of dynamic sql, this should workfine if the tables have to do the select from had the same number ofcolumns, how ever they don't.I only need the first 5 columns from each the table, in the case wherethey have more than the 5 i need for my 'Users' table i get this error:'An explicit value for the identity column in table 'Users' can only bespecified when a column list is used and IDENTITY_INSERT is ON.'.Is there a way to select only the first five columns from a table, ifnot is there another solution for my problem?My Sql query is the following:DROP TABLE UsersCreate Table Users(ID INT identity PRIMARY KEY,TIPO VARCHAR(255),NOME VARCHAR(255),USERNAME VARCHAR(255),EMAIL VARCHAR(255),GROUPID VARCHAR(255))DECLARE @Table VARCHAR(255)DECLARE @Sql VARCHAR(8000)DECLARE sysCursor CURSORFORSELECT name FROM sysobjects where xtype='U'OPEN sysCursorFETCH NEXT FROM SysCursor into @Tablewhile @@FETCH_STATUS<>-1BEGIN/** INSERE VALORES NA TABELA DE TESTE*/SET @SQL = 'INSERT INTO UsersSELECT * FROM ['+ @Table +']'EXECUTE (@SQL)SET @SQL = 'UPDATE Users SET GROUPID=' + @Table +'WHERE GROUPID IS NULL'EXECUTE (@SQL)print @tableFETCH NEXT FROM SysCursor INTO @TableENDCLOSE sysCursor/** APAGA VALORES INVÁLIDOS DA TABELA DE TESTE*/DELETE FROM Users WHERE TIPO IS NULLDELETE FROM Users WHERE NOME='Nome'DEALLOCATE sysCursorI hope you can give me hand, thank you in advance.

View 8 Replies View Related

How Can I Select Numeric Columns Only?

Oct 3, 2006

hi all,


how can i select numeric (int, money, numeric, etc) columns only

from syscolumns.

i need to run a sum() aggregate on all numeric columns
thanks,

joey

View 4 Replies View Related

Three Different Select Statements In SP - Cant Get All Columns

Sep 3, 2007



Hi,

I have a SP having three differnet select statements like,

IF @reporttype ='A'

SELECT Column1, column2
FROM table1

IF @reporttype = 'B'

SELECT Column3, column4
FROM table2

IF @reporttype = 'C'

SELECT column5, Column6
FROM table3


Now I need three different reports for all three reporttypes.
If i creating first report for @reporttype A, it is executing fine and giving me the Columns which i need.
But while creating reprots for reporttype B and C, I m getting columns column1 and column2 . Its not displaying Column3, Column4, Column5, Column6.

Can anybody help me with this?

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved