I need a query that will sort data from Tab and put it into NewTab, which looks like this:
I'm using SQL Server 2008 R2 Express, and I've tried code:
INSERT INTO NewTab(Var1,Var2,Var3,DTime) VALUES (
(SELECT Value FROM Tab WHERE VarName='Var1'),
(SELECT Value FROM Tab WHERE VarName='Var2'),
(SELECT Value FROM Tab WHERE VarName='Var3'),
(SELECT DTime FROM Tab WHERE VarName='Var1')
)
But server is returning and error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
I'm quite new to SQL and I'll be grateful if someone help me with that.
INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table. Note that this INSERT multiple rows syntax is only supported in SQL Server 2008 or later. To insert multiple rows returned from a SELECT statement, you use the INSERT INTO SELECT statement.
You seems to be trying to pivot the data. There are other ways to do it (i.e using PIVOT operator), but I guess that using old-school aggregate functions help us get a better idea of how data is processed:
SELECT DTime
, SUM(CASE WHEN varname = 'Var1' THEN value ELSE NULL END) AS [Var1]
, SUM(CASE WHEN varname = 'Var2' THEN value ELSE NULL END) AS [Var2]
, SUM(CASE WHEN varname = 'Var3' THEN value ELSE NULL END) AS [Var3]
FROM Tab
GROUP BY DTime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With