Column alias for VALUES ( ) syntax - sql
Here's some SQL:
select T.*
FROM (
values ( '2014-05-30 17:26:32.749' , 'Casual shirt ' ) , ( '2014-05-30 17:26:32.749' , 'Casual shirt-White-Small ' ) , ( '2014-05-30 17:26:32.749' , 'Casual shirt-Blue-Medium ' ) , ( '2014-05-30 17:26:32.749' , 'Cords ' ) , ( '2014-05-30 17:26:32.749' , 'Bodysuit ' ) , ( '2014-05-30 17:26:32.749' , 'Cords-Black-29W x 28L ' ) , ( '2014-05-30 17:26:32.749' , 'Bodysuit-Black-Petit ' ) , ( '2014-05-30 17:26:32.749' , 'Cords-Brown-29W x 28L ' ) , ( '2014-05-30 17:26:32.749' , 'Classic pleated dress pant ' ) , ( '2014-05-30 17:26:32.749' , 'Classic pleated dress pant-Black-29W x 32L ' ) , ( '2014-05-30 17:26:32.749' , 'Dress shirt ' ) , ( '2014-05-30 17:26:32.749' , 'Dress shirt-White-15 ' ) , ( '2014-05-30 17:26:32.749' , 'Dress shirt-White-16 ' )
) T
;
It returns columns "1" and "2". How to change it so it returns named columns? Is it possible without using sysdummy1 ?
You can add the column names to T:
select T.*
FROM (values ( '2014-05-30 17:26:32.749' , 'Casual shirt ' ) ,
( '2014-05-30 17:26:32.749' , 'Casual shirt-White-Small ' ) ,
( '2014-05-30 17:26:32.749' , 'Casual shirt-Blue-Medium ' ) ,
( '2014-05-30 17:26:32.749' , 'Cords ' ) ,
( '2014-05-30 17:26:32.749' , 'Bodysuit ' ) ,
. . .
) T(col1, col2);
Related
Word Table to CSV file Macro
I'm new to Macros and teaching myself as I go. My goal is to populate a file with data from a Word table using CSV formatting. The table spans over 300 pages with no exact number of rows per page. A user prompt for selecting a file at the beginning has been created. What would be recommended process wise? I know a For loop would be needed for the row count. Dim fd As Office.FileDialog Dim strFile As String Set fd = Application.FileDialog(msoFileDialogFilePicker) With fd .Filters.Clear .Filters.Add "Word Files", "*.docx?", 1 .Title = "Choose a Word file" .AllowMultiSelect = False .InitialFileName = "C:\VBA Folder" If .Show = True Then strFile = .SelectedItems(1) End If End With Intended Output: Identifer, Artifact Type, Name, Red, Amber, White, Cust, IO_Type, M_680A, M_680_Phase, M_750, Left_Input, Right_Input, Input_Type, Source, Debounce, LOPI, TOPI, ESDI, EFI, BFI, On_gnd, In_air, FDRIO, Auto_test, Frome, Level, VerifiedBy, Status XXX , Module, X346, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, S003, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , XXX , Module, X301, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, X025, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, X511, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, X347, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, X514, , , , , None,6, , , , , , , , , , , , , , , , , SAS, , , XXX , Module, S050, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X021, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X517, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X599, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X022, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X521, , , , , None,6, ,7, , , , , , , , , , , , , , , ADD, , , XXX , Module, X523, , , , , None,6, ,7, , , , , , , , , , , , , , , ADD, , , XXX , Module, X019, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, X518, , , , , None,6, ,7, , , , , , , , , , , , , , , SAS, , , XXX , Module, M141, , , W, , None,6, ,7, , , ,,0, L, T, , , , , , ,, SAS, ,,
At close to its simplest, you can convert a table to CSV format with: Sub Demo() Application.ScreenUpdating = False Dim Rng As Range With Selection If .Information(wdWithInTable) = True Then Set Rng = .Tables(1).Range With .Tables(1) .ConvertToText Separator:="," End With Rng.Select End If End With Application.ScreenUpdating = True End Sub Simply place the selection point anywhere within the table. The converted range will be selected when the macro finishes. To save the converted range to a new file, you could use code like: Sub Demo() Application.ScreenUpdating = False Dim Rng As Range, DocSrc As Document, DocTgt As Document With Selection Set DocSrc = .Range.Document If .Information(wdWithInTable) = True Then Set Rng = .Tables(1).Range With .Tables(1) .ConvertToText Separator:="," End With Set DocTgt = Documents.Add With DocTgt.Range .FormattedText = Rng.FormattedText .Characters.Last.Previous.Text = vbNullString End With DocSrc.Undo With Application.Dialogs(wdDialogFileSaveAs) .Format = wdFormatText .Name = "C:\Users\" & Environ("Username") & "\Documents\MyFile" .AddToMru = False .Show End With End If End With Application.ScreenUpdating = True End Sub This will export the converted content to a new file and display the SaveAs dialogue box, with the user's 'Documents' folder selected. You can coose another folder, if you prefer. Then simply substitute your preferred filename, including the .csv extension, for the 'MyFile.txt' offered by the dialogue box. If you want to exclude particular columns, you could insert code to delete them at 'With .Tables(1)'. For example, to omit the third column: With .Tables(1) .Columns(3).Delete .ConvertToText Separator:="," End With
Replace NULL with "N/A"
I'm trying to use the Oracle NVL() function to replace NULL with "N/A": SELECT ID AS "Record ID", ( SELECT NVL( COMMENT , "N/A") FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Solar KW' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Solar", ( SELECT NVL( COMMENT, "N/A" ) FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Code Edition' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Coder" FROM RECORDS Note: I'm trying to replace NULL with "N/A," not an empty string, so it should work. However, in the result set, I'm still getting NULL values instead of "N/A". What am I doing wrong?
Just wrong place for NVL(), not that your subqueries may not return rows, so use NVL on subquery: SELECT ID AS "Record ID", NVL( ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Solar KW' AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) , 'N/A') AS "Solar", NVL( ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Code Edition' AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) , 'N/A' ) AS "Coder" FROM RECORDS But probably it would be better to use lateral or outer apply here: SELECT ID AS "Record ID", c.* FROM RECORDS outer apply( SELECT nvl(solar,'N/A') as solar, nvl(coder,'N/A') as coder FROM (select * from CHECKBOX WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition') AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) pivot( max("COMMENT") for B1_CHECKBOX_DESC in ( 'Solar KW' as Solar, 'Code Edition' as Coder ) ) ) c Full example with test data: DBFiddle with records(id,id1,id3) as ( select 1,1,1 from dual union all select 2,2,2 from dual ) ,CHECKBOX("COMMENT",id1,id3,B1_CHECKBOX_DESC) as ( select 'comment1-1',1,1, 'Solar KW' from dual union all select 'comment1-2',1,1, 'Code Edition' from dual union all select 'comment2-1',2,2, 'Solar KW' from dual ) SELECT ID AS "Record ID", c.* FROM RECORDS outer apply( SELECT nvl(solar,'N/A') as solar, nvl(coder,'N/A') as coder FROM (select * from CHECKBOX WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition') AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) pivot( max("COMMENT") for B1_CHECKBOX_DESC in ( 'Solar KW' as Solar, 'Code Edition' as Coder ) ) ) c; Results: Record ID SOLAR CODER ---------- ---------- ---------- 1 comment1-1 comment1-2 2 comment2-1 N/A
Optimize multiple query separated by condition
I have a stored procedures with three different queries, that querys return values depending of received variable. They basically return same data, just change WHERE clauses: Query: IF #DesignType = 'BDCD' BEGIN SELECT [DT].[DesignTypeGuid] , [DT].[Name] , [DT].[Abbreviation] , CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) AS [EnforceBaseOnPrevious] , [DT].[Order] FROM [DesignType] AS [DT] WHERE [DT].[IsActive] = 1 AND ([DT].[DesignTypeGuid] != IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument)) AND [DT].[DesignTypeGuid] != #ChangeOrder AND [DT].[DesignTypeGuid] != #AddedPart ORDER BY [DT].[Order] END ELSE BEGIN IF #DesignType = 'CO' BEGIN SELECT [DT].[DesignTypeGuid] , [DT].[Name] , [DT].[Abbreviation] , 0 AS [EnforceBaseOnPrevious] , [DT].[Order] FROM [DesignType] AS [DT] WHERE [DT].[IsActive] = 1 AND [DT].[DesignTypeGuid] = #ChangeOrder ORDER BY [DT].[Order] END ELSE BEGIN IF #DesignType = 'AP' BEGIN SELECT [DT].[DesignTypeGuid] , [DT].[Name] , [DT].[Abbreviation] , 0 AS [EnforceBaseOnPrevious] , [DT].[Order] FROM [DesignType] AS [DT] WHERE [DT].[IsActive] = 1 AND [DT].[DesignTypeGuid] = #AddedPart ORDER BY [DT].[Order] END Is there any way to optimize this and do it in a simple SELECT instead do 3 differents depending of DesignType variable? Regards
Not sure about the performance , but the query could definitely be written as SELECT [DT].[DesignTypeGuid] , [DT].[Name] , [DT].[Abbreviation] , CASE #DesignType WHEN 'BDCD' THEN CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) ELSE 0 END AS [EnforceBaseOnPrevious] , [DT].[Order] FROM [DesignType] AS [DT] WHERE [DT].[IsActive] = 1 AND ( ( #DesignType = 'BDCD' AND [DT].[DesignTypeGuid] NOT IN ( IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument),#ChangeOrder,#AddedPart) ) OR ( #DesignType = 'CO' AND [DT].[DesignTypeGuid] = #ChangeOrder ) OR ( #DesignType = 'AP' AND [DT].[DesignTypeGuid] = #AddedPart ) ) ORDER BY [DT].[Order]
Removing duplicates from select query output
Could anyone please suggest what is the error in the below query? Actually I want to remove all duplicates from the select query output and fetch only unique rows. Thanks in advance. select * from ( select ROW_NUMBER() over ( partition by Dep , tariffkode , LinkTariffType , poliata , poliatavia , podiata , podiatavia , PreCarriage , PortTerminalId , Product , RoutingOrder , PrepaidCollect , isnull(description, '') , ScaleCalcCode , isnull(scalefrom, 0) , isnull(scaleto, 0) , CurrencyCode , Base order by LinkTariffType desc ) Record , * from ( select tn.LinkTariffType , tn.Dep , tn.POLIata , tn.POLIatavia , tn.PODIata , tn.PODIatavia , tn.CurrencyCode , tn.LegalEntityID , tn.Rate , tn.Base , tn.Minimum , tn.NrDescription , tn.Description , tn.DateFrom , tn.DateUntil , tn.DateCreate , tn.DateMod , tn.ModName , tn.Tariffkode , tn.ExpiryDate , tn.PClass , tn.Maximum , tn.RoutingOrder , tn.TariffCompType , tn.PrePaidCollect , tn.Product , tn.IsDeleted , ( select distinct Location_IATA from Company where Called = 'KARL KING' and LegalEntityID = 1 and IsDeleted = 0 ) as PreCarriage , tn.PortTerminalID , tn.ScaleFrom , tn.ScaleTo , tn.ScaleCalcCode , tn.Mandatory , ( select CompanyID from PlaceOfReceipt where warehouse = 'KARL KING' and LegalEntityID = 1 and OfficeID = 13 and IsDeleted = 0 ) as WarehouseID , tn.TariffRelID , tn.FreeDescription , 0 , tn.ShipCode , tn.AgentID , tn.ContainerTypeID , tn.CommodityID , 0 as TempTable from TariffNew tn inner join hhInvoiceLines inv on tn.Tariffkode = inv.NrInvoiceLine where ( tn.PreCarriage is not null and tn.PreCarriage != '' ) and ( tn.POLIata is not null and tn.POLIata != '' ) and inv.OfficeID = 13 and inv.IsDeleted = 0 and inv.LegalEntityID = 1 and tn.LegalEntityID = 1 and tn.Dep = 'E' and tn.IsDeleted = 0 and tn.DateUntil = '2078-12-31 00:00:00' and tn.Description = 'kgl' ) ) as b where b.Record = 1
First, you have to define what you want to call "unique rows". Once you have the set of columns that determines a row is unique, that is the set of columns you use in the partition by part of row_number() In the code below, uncomment the column set that defines your "unique rows": select * from ( select ROW_NUMBER() over ( partition by Dep --, tariffkode --, LinkTariffType --, poliata --, poliatavia --, podiata --, podiatavia --, PreCarriage --, PortTerminalId --, Product --, RoutingOrder --, PrepaidCollect --, isnull(description, '') --, ScaleCalcCode --, isnull(scalefrom, 0) --, isnull(scaleto, 0) --, CurrencyCode --, Base order by LinkTariffType desc ) Record , * from ( select tn.LinkTariffType , tn.Dep , tn.POLIata , tn.POLIatavia , tn.PODIata , tn.PODIatavia , tn.CurrencyCode , tn.LegalEntityID , tn.Rate , tn.Base , tn.Minimum , tn.NrDescription , tn.Description , tn.DateFrom , tn.DateUntil , tn.DateCreate , tn.DateMod , tn.ModName , tn.Tariffkode , tn.ExpiryDate , tn.PClass , tn.Maximum , tn.RoutingOrder , tn.TariffCompType , tn.PrePaidCollect , tn.Product , tn.IsDeleted , ( select distinct Location_IATA from Company where Called = 'KARL KING' and LegalEntityID = 1 and IsDeleted = 0 ) as PreCarriage , tn.PortTerminalID , tn.ScaleFrom , tn.ScaleTo , tn.ScaleCalcCode , tn.Mandatory , ( select CompanyID from PlaceOfReceipt where warehouse = 'KARL KING' and LegalEntityID = 1 and OfficeID = 13 and IsDeleted = 0 ) as WarehouseID , tn.TariffRelID , tn.FreeDescription , 0 as UnnamedColumn , tn.ShipCode , tn.AgentID , tn.ContainerTypeID , tn.CommodityID , 0 as TempTable from TariffNew tn inner join hhInvoiceLines inv on tn.Tariffkode = inv.NrInvoiceLine where tn.PreCarriage is not null and tn.PreCarriage != '' and tn.POLIata is not null and tn.POLIata != '' and inv.OfficeID = 13 and inv.IsDeleted = 0 and inv.LegalEntityID = 1 and tn.LegalEntityID = 1 and tn.Dep = 'E' and tn.IsDeleted = 0 and tn.DateUntil = '2078-12-31 00:00:00' and tn.Description = 'kgl' ) as s ) as b where b.Record = 1
XML to SQL format
I'm trying to convert my XML string into some SQL elements unfortunately i have some modification problems my SQL string : select #xml --, #XML.query('Document/Content/Truncated') ff -- URL -- , #xml.value('(Document/Metadata/Fields/docid)[1]', 'varchar(100)') D_URL -- title -- , #xml.value('(Document/Metadata/Fields/title)[1]', 'varchar(100)') Title -- name -- , #xml.value('(Document/Metadata/Facets/Facet/_ne/person)[1]', 'varchar(100)') MD_Name -- address -- , left((substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Location & Contact%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 550)), CHARINDEX ('[MAP]' , (substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Location & Contact%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 550)) ))Office_Location -- gender-- , substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Years in Practice%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 10) Gender -- phone -- ,right(left((substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Location & Contact%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 550)), CHARINDEX ('Phone Number' , (substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Location & Contact%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 550)) )), CHARINDEX ('(' , (substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Location & Contact%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 550)) ))Phone -- speciality -- , substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Specialties & Qualifications%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 100) Specialities -- type-- , substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Doctor Type%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 15) Doctor_Type -- Explenation -- , substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Specialty:%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 400) Explenation -- certification -- , substring(#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') , 18+patindex('%Certifications & Licensure%', (#xml.value('(Document/Content/Text)[1]', 'nvarchar(4000)') )), 200) Board_Certifications I have a problem ouput in: output: i just can't catch the damn phone (+332) .... Specialty: i can't cut all the sentence any suggestions ?