Convert multiple rows in a table into one row based on the primary key
I have 2 tables
CREATE TABLE Files (FileID int, fileName varchar(20))
insert into Files values (1,'F1')
insert into Files values (2,'F2')
insert into Files values (3,'F3')
CREATE TABLE Versions (FileID int, VersionNum varchar(10))
insert into Versions values (1, 'V1')
insert into Versions values (1, 'V2')
insert into Versions values (1, 'V3')
insert into Versions values (2, 'V1')
The two tables join using FileID. I want a listing of the fileName and the all corresponding versions on one line. There may not be a version for a file or there may be multiple versions for the file. The output I want is
F1, V1, v2, v3
F2, V1
F3
Any help would be appreciated.
lg
gardner,
If you want them as different columns, you can PIVOT. However, this requires to know the max numebr of versions that may be there (here I have done with 3). If you dont have that info, then you might have to resort to dynamic SQL..
;with cte
as
select f.fileid,f.fileName,ISNULL(v.VersionNum,'') as VersionNum,row_number() over(partition by f.fileid order by f.filename,v.versionnum) rownum from #files f
left join #versions v
on f.fileid=v.fileid
select fileid,fileName,ISNULL([1],'') as [1],ISNULL([2],'') as [2],ISNULL([3],'') as [3]
from
select * from cte
) tab
PIVOT
Max(VersionNum) for rownum in ([1],[2],[3])
) pvt
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>
Similar Messages
-
Best approach to join multiple statistics tables into one
I have read different approaches to join multiple statistics tables into one, they all have a column "productobjectid".
I want to get all data for each product and put it to excel and output a jpg statistic with cfchart.
How would you do this, the sql part?
Thanks.A couple suggestions:
1) when joining tables, its best to list both table/fields that you are joining in the FROM clause:
FROM shopproductbehaviour_views INNER JOIN shopproductbehaviour_sails ON shopproductbehaviour_views.productobjectid = shopproductbehaviour_sails.productobjectid
2) You add tables to a SQL join by placing another join statement after the SQL above:
SELECT *
FROM TableA INNER JOIN TableB on TableA.myField = TableB.myField
INNER JOIN TableC on TableA.anotherField = TableC.anotherField
3) If you have columns in the tables that are named the same, you can use column aliases to change the way they appear in your record set:
SELECT TableA.datetimecreated 'tablea_create_date', TableB.datetimecreated 'tableb_create_date'
4) Certainly not a requirement, but you might want to look into using <cfqueryparam> in your where clause:
WHERE shopproductbehaviour_sails.productobjectid = <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#all.productobjectid#">
You might want to consider checking out one of the many tutorials on SQL available online. Many of the questions you posed in your post are covered in pretty much every basic SQL tutorial. Alternately, a good SQL book is worth its weight in gold for a beginning web applications developer. -
Export multiple tables into one flat file
I have data in multiple tables on a processing database that I need to move up to a production database. I want to export the data into a flat file, ftp it to the production server and have another job pick up the file and process it. I am looking for
design suggestions on how to get multiple tables into one flat file using SSIS?
Thank You.Hey,
Without a bit more detail, as per Russels response, its difficult to give an exact recommendation.
Essentially, you would first add a data flow task to your control flow. Create a source per table, then direct the output of each into an union all task. The output from the union all task would then be directed to a flat file destination.
Within the union all task you can map the various input columns into the appropriate outputs.
If the sources are different, it would probably be easiest to add a derived column task in-between the source and the union all, adding columns as appropriate and setting a default value that can be easily identified later (again depending on your requirements).
Hope that helps,
Jamie -
Convert multiple rows into single rows for the respective index name
Dear Experts,
I want to convert multiple rows into single rows for the respective index name,
Here is my query.
SELECT user_tables.table_name, user_indexes.index_name, user_ind_columns.column_name
FROM user_tables
JOIN user_indexes on user_indexes.table_name = user_tables.table_name
join USER_IND_COLUMNS on USER_INDEXES.INDEX_NAME = USER_IND_COLUMNS.INDEX_NAME
where user_indexes.index_name not like '%PK%' AND user_ind_columns.column_name NOT LIKE '%SYS%'
ORDER BY user_tables.table_name,user_indexes.index_name;
Result of previous query
TABLE_NAME
INDEX_NAME
COLUMN_NAME
T1
IDX_ACCNTYPCFG1
ENABLE_SERVICE
T1
IDX_ACCTTYPCFG1
ACC_CODE
T1
IDX_ACCTTYPCFG1
ACCTYPE
T2
IDX_ACCTTYPCFGAPP1
ACCTYPE
T3
IDX_ACTLG1
MOBILE_NO
T3
IDX_ACTLG1
ID
Desired output required is
TABLE_NAME
INDEX_NAME
COLUMN_NAME
T1
IDX_ACCNTYPCFG1
ENABLE_SERVICE,ACC_CODE,ACCTYPE
T2
IDX_ACCTTYPCFGAPP1
ACCTYPE
T3
IDX_ACTLG1
ACCTYPE,MOBILE_NO
please help.Maybe
with
user_tables as
(select 'T1' table_name,'IDX_ACCNTYPCFG1' index_name,'ENABLE_SERVICE' column_name from dual union all
select 'T1','IDX_ACCTTYPCFG1','ACC_CODE' from dual union all
select 'T1','IDX_ACCTTYPCFG1','ACCTYPE' from dual union all
select 'T2','IDX_ACCTTYPCFGAPP1','ACCTYPE' from dual union all
select 'T3','IDX_ACTLG1','MOBILE_NO' from dual union all
select 'T3','IDX_ACTLG1','ID' from dual
select table_name,
case index_name when 'IDX_ACCNTYPCFG1' then 'IDX_ACCTTYPCFG1' else index_name end index_name,
listagg(case column_name when 'ID' then 'ACCTYPE' else column_name end,',') within group (order by null) column_name
from user_tables
group by table_name,case index_name when 'IDX_ACCNTYPCFG1' then 'IDX_ACCTTYPCFG1' else index_name end
TABLE_NAME
INDEX_NAME
COLUMN_NAME
T1
IDX_ACCTTYPCFG1
ACCTYPE,ACC_CODE,ENABLE_SERVICE
T2
IDX_ACCTTYPCFGAPP1
ACCTYPE
T3
IDX_ACTLG1
ACCTYPE,MOBILE_NO
Regards
Etbin -
Importing 30 tables into one SQL Table (Help Required)
Dear Experts,
I am new in SQL server, actually i need to gather 30 different excel file in one sql server table and i have imported all excel file in different databases, all tables have 186 different columns and datatypes. I couldnt change data type while conversion.
Now all columns have different data type which are occupying extra space in my database.
Now the problem is that i need to convert all databases into one database or table. Although i have created a table but i dont have idea how to import all table into one table and defining datatype in new table while importing the old tables.
Please help me in this matter or if any body has skype or any other chatting id please do let me know so that i may explain it better.
Thanking you in advance.
Best Regards,
SQL_beginnerThere are several things you can try. If you have SSIS, take a look at this.
http://www.singhvikash.in/2013/06/ssis-how-to-load-multiple-excel-files.html
https://www.simple-talk.com/sql/ssis/importing-excel-data-into-sql-server-via-ssis-questions-you-were-too-shy-to-ask/
Also, if your files have virtually the same name, like files with dates in the name, you can loop through files in your folder, and increment the loop with each run through.
DECLARE @intFlag
INT
SET @intFlag
= 1
WHILE (@intFlag
<=30)
BEGIN
PRINT @intFlag
declare @fullpath1
varchar(1000)
select @fullpath1
= '''\\path to your files\'
+ convert(varchar,
getdate()- @intFlag
, 112)
+ '_your-text-file-name.txt'''
declare @cmd1
nvarchar(1000)
select @cmd1
= 'bulk insert [dbo].[your-table-name] from '
+ @fullpath1 +
' with (FIELDTERMINATOR = ''\t'', FIRSTROW = 2, ROWTERMINATOR=''0x0a'')'
exec (@cmd1)
SET @intFlag
= @intFlag + 1
END
GO
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it. -
Merging (Joining) two tables into one
Is it possible to merge two adjacent tables into one table in Pages? Also, how can you split one table into multiple tables?
If we use the exact meaning of the words, the response is no and no.
If we play a bit with the meanings we may do the trick.
(1) I create a table with 6 columns and 5 rows.
(2) select cells D1 …F5, copy, paste in the document but out of the table. We get the right half of the table.
From the tool bar, reduce the number of columns of table 1 fom 6 to 3. Bingo we have the two halves of the original table.
(3)Select the first half and increase the number of rows from 5 to 10
(4) copy the entire second half, select cell D1 in the enlarged table, paste.
Bingo, we have the merged table.
For sure, a merge and a split tables features would be welcome but as the table tool is the one used in the spreadsheet, I would be surprised if these features where introduced one day.
_Go to "Provide Pages Feedback" in the "Pages" menu_, describe what you wish.
Then, cross your fingers, and wait _at least_ for iWork'11
Yvan KOENIG (VALLAURIS, France) jeudi 22 avril 2010 17:28:48 -
Trying to drag pdf files i have and combine them into one pdf file in the account i just purchased with Adobe. when i drag a pdf file over Adobe doesn't accept it. says it can not convert this type of file. but it is an Adobe file. Do I need to change it in some other form befor dragging it?
Hello djensen1x,
Could you please let me know what version of Acrobat are you using.
Also, tell me your workflow of combining those PDF files?
Please share the screenshot of the error message that you get.
Hope to get your response.
Regards,
Anubha -
How to fill the data of two different tables into one?
Hi Experts,
I have two tables named CDHDR and CDSHW(structure). I have extracted the data from these two tables through two function modules named CHANGEDDOCUMENT_HEADER and CHANGEDOCUMENT_POSITION. Now I have the data in to different tables.
These two tables neither has relationship with each other through any field nor have any field which exist in both. Can anyone tell me in this case what should be the process to take the data of both the tables into one table. How can I match the record of one table to another?
thanks a ton in advance.
Edited by: Moni Bindal on Apr 28, 2008 4:16 PM
Edited by: Alvaro Tejada Galindo on Apr 28, 2008 1:42 PMHye Bindal,
without a relation, it is not possible to club the data of 2 internal tables. More over it depends on the requirement as to y u should club to non related quantities in an internal table.
if you wish to do so, one thing is it has internal table which includes the strucute of the 2.
data: begin of ty_out,
first type first_structure,
second type second_structure,
end of ty_out.
data: itab type standard table of ty_out.
data: wa type ty_out.
loop into it1 into wa1.
move corresponding wa to wa1.
append wa to itab.
endloop.
loop into it2 into wa2.
move corresponding wa to wa2.
append wa to itab.
endloop.
now the internal table itab will have all the contents of it1 and it2.
<REMOVED BY MODERATOR>
Thanks,
Imran.
Edited by: Alvaro Tejada Galindo on Apr 28, 2008 1:43 PM -
Collapsing two tables into one table or one queue
When you have data that exists in 2 tables A and B and B is essentially a child of A if you want to process these records such that you see all A's before their assoociated B how can you use either Streams or AQ to collapse these two tables into one? The data exists at it's source in database tables it will be replicated to another location and at that location I want to keep the data as it exists at the source but also process it in the ordered fashion I described above. My thinking is to publish the data to one queue but the challenge is to ensure that all A's are put on the queue before their B is. I don't just want a priority queue whereby all A's are processed before B's because if that happens B's will never be processed. but I simply want to avoid reading a B off the queue before I've read it's A.
No version number and no clarity of what you are trying to accomplish.
Without knowing that the problem is a nail ... I'd hardly be recommending using a hammer. -
Is it possible to deploy multiple sharepoint provider hosted apps into one azure website??
Rohit PasrijaI am faced with a similar requirement although the hosting environment for the provider hosted apps would be an IIS web server in our own infrastructure.
Would it be advisable to use a common IIS website to host multiple apps? The MVC web application which will provide functionality
for the apps is already in place which is why we are checking for options to use the same web project for multiple apps.
Can the web config file's clientID be shared by multiple apps? -
How can i add two table into one internal table
I WANT TO ADD THIS TWO DIFFERENT TABLE INTO ONE INTERNAL TABLE PLEASE HELP.
TABLES: J_1IEXCHDR, J_1IEXCDTL.
SELECT * FROM J_1IEXCHDR WHERE STATUS = 'P'.
WRITE: / J_1IEXCHDR-LIFNR,
J_1IEXCHDR-DOCNO,
J_1IEXCHDR-EXYEAR,
J_1IEXCHDR-BUDAT.
SELECT * FROM J_1IEXCDTL WHERE TRNTYP = J_1IEXCHDR-TRNTYP
AND DOCYR = J_1IEXCHDR-DOCYR
AND DOCNO = J_1IEXCHDR-DOCNO.
WRITE: / J_1IEXCDTL-EXBAS,
J_1IEXCDTL-EXBED,
J_1IEXCDTL-RDOC1,
J_1IEXCDTL-ECS.
ENDSELECT.
ENDSELECT.
THANKS IN ADVANCED.U have to link these 2 tables like this
<b>SELECT
J_1IEXCHDR~DOCNO
FROM J_1IEXCHDR inner join J_1IEXCDTL
on J_1IEXCHDRDOCYR = J_1IEXCDTLDOCYR
WHERE STATUS = 'P'.</b>
this is sample code only, and u have to check the F.key relationship.
Regards
Prabhu -
Reg: how to join more than one cluster table into one
Hi gurus
How to join more than one cluster table into one
amkHi,
You cannot join cluster tables
Best way is to select from the header table and then select from the item table table using for all entries of header table.
regards,
Advait -
Combining two tables into one result
Hi all, I am fairly inexperienced with Crystal but have gained good results from the reports I have created, I am fluent in SQL and Basic to an extent. I am interigating a Pronto database and I want concatenate two tables into one report.
Table One: Customer Orders
Fields: Customer No, Invoice Number, Invoice date, Invoice Amount, Cost Amount.
Table Two: Archived Customer Orders
Fields: Customer No, Invoice Number, Invoice date, Invoice Amount, Cost Amount.
I want to complete a report that will tell me the sales for a given period and the outstanding orders for each customer total for all fields in each table combined into one figure.
Any help would be greatly appreciated.
Thanks in advanceHi Grant,
As you said you are goot at writing SQL, in Crystal write a SQL statement in Add Command to join both table using Union / Union all
If you use Union then it will filter duplicate records and pull the data from database, If you use Union All then it will include all your duplicate records. Please use Union / Union All as required.
Once you get all data into the report create a parameter for date range and generate the summaries as required.
Thanks,
Sastry -
How to consolidate 4 internal table into one
how can we consolidate data from
two or more internal tables into one
please help
its a bit uegent
thanks in advanceHi,
If you want to combine two internal table,you can follow 2 approaches.
Case1: If both the internal table are of same structure,
append lines of itab1 to itab2.
The above statement will append all the records in itab1 to itab2.
Case2:If both the internal table are of differnt structure,
you need one or more common fields in the two tables to connect.
loop at itab1.
move-corresponding itab1 to itab.
loop at itab2 where f1 = itab1-f1.
move-corresponding itab2 to itab.
append itab.
clear : itab2, itab.
endloop.
clear itab1.
endloop.
Now itab will hold the entries from itab1 and itab2. -
Split single row in multiple rows based on date range
I need sql script that can split single row in multiple rows based on start date and end date column in table.
Thank youI agree to your suggestion of having a dates table permanently in the database. Thats how we also do for most of our projects as well
But in most projects the ownership of table creation etc lies with the client as they will be the DBAs and will be design approval authorities. What I've seen is the fact that though
many of them are in favour of having calendar table they dont generally prefer having a permanent table for numbers in the db. The best that they would agree is for creating a UDF which will have
tally table functionality built into it based on a number range and can be used in cases where we need to multiply records as above.
Wherever we have the freedom of doing design then I would also prefer creating it as a permanent table with required indexes as you suggested.
>> many of them are in favour of having calendar table they dont generally prefer having a permanent table
Those people do not understand about database and are not DBAs :-)
It is our job to tell them what is right or wrong.
** This is a real story! I had a client several years back, who was the CEO of a software company.
He use the query:
select * from table_name
In order to get the last ID!
The table_name was actually a view that took data from several tables, and the main table that he wanted to get the ID included several string columns, with lot of data!
he actually pulled all this data to the application, just to get the lat ID in a specific table!
It is our job as Consultants or DBAs to fix's his misunderstanding :-)
Ronen Ariely
[Personal Site] [Blog] [Facebook]
Maybe you are looking for
-
I'm having a problem with xslt transformations. I'm sending a DOMDocument to be transformed into a varchar2. The transformation was into html and I was then printing the returning varchar2 to a web page, along the lines of... htp.prn(Xslt.transform(d
-
Problem in ZIP file encryption
Hi Folks, I am facing a problem while encrypting and decrypting a ZIP file. The result file is corrupted. If i encrypt .txt and .doc files, i am able to get them in decryption. But problem with ZIP files. What could be the reasone? I am using AES alg
-
How can I replicate my iphoto contents with another user on my mac? Thanks.
Have to tried sharing files but to no avail
-
Regarding VA01/VA02/VA03 - Adding a new field column to the Overview table
Hi, Apologies if this is not the right forum, but I have a request to add an extra column into the main overview screen in VA01/VA02/VA03. The field I want to add is available from the Sales Header Data > Purchase Order Data tab (Ship-to party > Your
-
I purchased the monthly download offer for Photoshop and Lightroom The first installment has been taken from my bank account, but no Lightroom has been downloaded. I managed to get a 'free 30 day trial' for the photoshop!. How do I contact Adobe a