I have the following query that runs in postgresql-9.6, I need to achieve the same output on a SQL Server DB.
Here is the query, I've replaced all fields from my DB with the string values that would come from them anyway (DB Fields are: "primary_key_fields", "primary_key_values", "table_name", "min_sequence"):
SELECT
UNNEST(STRING_TO_ARRAY(demo.primary_key_fields, ',')) AS primary_key_fields,
UNNEST(STRING_TO_ARRAY(demo.primary_key_values, ',')) AS primary_key_values,
table_name,
min_sequence,
ROW_NUMBER() OVER(partition by demo.primary_key_fields) AS rn
FROM (
SELECT
'Name,surname,age,location,id' AS primary_key_fields,
'Nash,Marley,27,South Africa,121' AS primary_key_values,
'person' AS table_name,
'1' AS min_sequence
UNION ALL
SELECT
'Name,surname,age,location,id' AS primary_key_fields,
'Paul,Scott,25,South America,999' AS primary_key_values,
'person' AS table_name,
'1' AS min_sequence
) demo
I'm expecting the following output:
Highly appreciate the assistance. I'm using SQL Server 2017.
No longer needed. This question can be closed. No solution was found, changed the source system to accomdate what was needed.
Related
I want a to write an SQL query in Microsoft SQL Server in PyQt of the type:
list=['Engineer', 'Doctor', 'Lawyer']
select * from Occupations where OccupationName in (list)
I have read various posts online but they seem to be for SQL Lite or MySQL databases. How would I do this for Microsoft SQL?
Also, in MS SQL the string values need to be enclosed in double quotes instead of single quotes used in the list items. How would I do this?
this topic should help you! T-SQL split string
btw:
You can write your params in CTE:
;with list as (
select 'Engineer' as [occupation] union
select 'Doctor' union
select 'Lawyer'
)
select * from Occupations where OccupationName in (select occupationfrom from list)
or very simple like this:
select * from Occupations where OccupationName in ('Engineer', 'Doctor', 'Lawyer')
I have an Oracle query using
SELECT REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA',',[^,]+,')
FROM DUAL;
It returns the output as below:
, Redwood Shores,
I am trying to get the exact same result in SQL Server. I tried to do it as below
substring(text, patindex, length)
But I struggled with length specification.
Can you please let me know how I can achieve this is in SQL Server?
You can try below query
WITH dual AS
(
SELECT '500 Oracle Parkway, Redwood Shores, CA' AS st
)
SELECT SUBSTRING(REVERSE(SUBSTRING(REVERSE(st),
CHARINDEX(',', REVERSE(st)),
LEN(st))),
CHARINDEX(',', st),
LEN(st)) str_value
FROM dual
Below is the result which I have got
Note: with clause is just for data preparation. Just make use of the substring part in select statement
Try this:
Declare #test varchar(max)='500 Oracle Parkway, Redwood Shores, CA'
select reverse(substring(reverse(substring(#test,charindex(',',#test),len(#test))),
charindex(',',reverse(substring(#test,charindex(',',#test),len(#test)))),
len(substring(#test,charindex(',',#test),len(#test)))))
Visual studio hangs on me when using the Slowly Changing Dimension Wizard.
I select the correct connection.
Then I try to open the dropdown 'Table or view' to select a destination table.
At this moment visual studio hangs on me..
I have this on all client machines and on different visual studio versions and only on this specific database. In activity monitor I noticed that the wizard does a select * on all tables in the database... I have one table that has +4billion rows (+300GB). It is the select * on this table that takes so long.
Does anybody have any idea what causes the select * on my database, or why they are doing this? And even better, how to fix this?
Don't use the slowly changing dimension wizard in SSIS at all. The data flow it creates performs really badly compared to what you can write with TSQL.
A couple of assumption; you need a type 2 SCD and you are using at least SQL Server 2008 with MERGE statements available.
Instead of SSIS use the OUTPUT clause of the MERGE statement within TSQL to perform the dimension update/insert. For example:
INSERT INTO Customer_Master
SELECT
Source_Cust_ID,
First_Name,
Last_Name,
Eff_Date,
End_Date,
Current_Flag
FROM
(
MERGE
Customer_Master CM
USING
Customer_Source CS
ON
CM.Source_Cust_ID = CS.Source_Cust_ID
WHEN NOT MATCHED
THEN
INSERT VALUES
(
CS.Source_Cust_ID,
CS.First_Name,
CS.Last_Name,
CONVERT(char(10), GETDATE()-1, 101),
'12/31/2199',
'y'
)
WHEN MATCHED
AND CM.Current_Flag = 'y'
AND (CM.Last_Name <> CS.Last_Name )
THEN
UPDATE
SET
CM.Current_Flag = 'n',
CM.End_date = convert(char(10), getdate()- 2, 101)
OUTPUT
$Action Action_Out,
CS.Source_Cust_ID,
CS.First_Name,
CS.Last_Name,
convert(char(10), getdate()-1, 101) Eff_Date,
'12/31/2199' End_Date,
'y' Current_Flag
) AS MERGE_OUT
WHERE
MERGE_OUT.Action_Out = 'UPDATE';
Source: http://www.kimballgroup.com/2008/11/design-tip-107-using-the-sql-merge-statement-for-slowly-changing-dimension-processing/
I wanted to know if there is any function or something to convert the SQL select query result to JSON string format?
For example, SQL select query result is,
current target
-----------------
500 1000
1500 2000
JSON result:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
Any ideas will be helpful.
Thanks.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
DECLARE #TABLE TABLE ([current] INT, [target] INT)
INSERT INTO #TABLE VALUES
(500 , 1000),
(1500 , 2000)
SELECT '[' + STUFF((SELECT ',{"current":' + CAST([current] AS VARCHAR(30))
+ ',"target":' + CAST([target] AS VARCHAR(30)) + '}'
FROM #TABLE
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') + ']'
Results:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
You don't specify version.
In SQL Server 2016 you will be able to do something like
SELECT [current],
target
FROM YourTable
ORDER BY [current]
FOR JSON AUTO;
More details here or in the official pre release documentation
I use
SELECT
JSON_QUERY(( SELECT
[current],target
FROM YourTable
FOR JSON PATH
))
Works well with minimal effort. I generally convert the output to a List<Dictionary<string,dynamic>> in C#/.Net (if I don't have an existing model).
DB: Sql Server 2008.
I have a really (fake) groovy query like this:-
SELECT CarId, NumberPlate
(SELECT Owner
FROM Owners b
WHERE b.CarId = a.CarId) AS Owners
FROM Cars a
ORDER BY NumberPlate
And this is what I'm trying to get...
=> 1 ABC123 John, Jill, Jane
=> 2 XYZ123 Fred
=> 3 SOHOT Jon Skeet, ScottGu
So, i tried using
AS [Text()] ... FOR XML PATH('') but that was inlcuding weird encoded characters (eg. carriage return). ... so i'm not 100% happy with that.
I also tried to see if there's a COALESCE solution, but all my attempts failed.
So - any suggestions?
Answering an old post, just thought it needed an update for newer versions of SQL Server:
For SQL Server 2017 use STRING_AGG(expression, seperator)
GROUP_CONCAT is MySQL.
Prior to SQL 2017, you can also do something like (snipped from our current code base on SQL Server 2016):
SELECT CarId, NumberPlate,
(STUFF(( SELECT ', ' + b.Owner
FROM Owners b
WHERE b.CarId = a.CarId
FOR XML PATH('')
)
,1,2,'')) AS Owners
FROM Cars a
ORDER BY NumberPlate
Links to STRING_AGG
https://database.guide/the-sql-server-equivalent-to-group_concat/
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017
Link to STUFF:
https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-2017
and finally links to FOR XML:
https://learn.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-2017
Try the solution to this question:
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?
:)
Use GROUP_CONCAT
SELECT CarId, NumberPlate
(SELECT GROUP_CONCAT(Owner)
FROM Owners b
WHERE b.CarId = a.CarId) AS Owners
FROM Cars a
ORDER BY NumberPlate