Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
WITH T AS
(   SELECT Sno, Water, Milk
    FROM (VALUES (1, 50, 100), (2, 22, 120), (3, 11, 142)) t (Sno, Water, Milk)
)
SELECT  Sno = ROW_NUMBER() OVER(ORDER BY SUM(Upvt.Qnty)),
        upvt.Type,
        Qnty = SUM(Upvt.Qnty)
FROM    T
       UNPIVOT
        (   Qnty
            FOR Type IN ([Water], [Milk])
        ) upvt
GROUP BY upvt.Type
ORDER BY Qnty;



It works fine in http://sqlfiddle.com/#!3/d41d8/36356[^]

But in my sql is not excuting..it shows an "Incorrect syntax near the keyword 'VALUES'.
Posted
Comments
Andrius Leonavicius 8-Jul-14 2:46am    
Hi,

It works OK on my machine. Maybe you accidentally marked the keyboard 'VALUES' before execution?

1 solution

SQL Server 2008 does not support this kind of statement.
[EDIT]
Above statement is not true. Please see Andrius's comment to my answer.
Thank you, Andrius ;)


You can achieve that in 2 ways:
1) using temporary table (variable type table)
SQL
DECLARE @products TABLE(Sno INT, Water INT, Milk INT)

INSERT INTO @products
VALUES (1, 50, 100), (2, 22, 120), (3, 11, 142)


SELECT ROW_NUMBER() OVER(ORDER BY SUM(Qnty)) AS RowNo, Product, SUM(Qnty) AS Qnty
FROM (
    SELECT Product, Qnty
    FROM (
        SELECT *
        FROM @products
        ) AS pvt
    UNPIVOT (Qnty FOR Product IN ([Water],[Milk])) AS unpvt
) AS T
GROUP BY Product



or
2) using UNION ALL[^] statement
SQL
;WITH T AS
(
SELECT Sno, Water, Milk
  FROM (
      SELECT 1 AS Sno, 50 AS Water, 100 AS Milk
      UNION ALL
      SELECT 2, 22, 120
      UNION ALL
      SELECT 3, 11, 142
      ) t (Sno, Water, Milk))
SELECT  Sno = ROW_NUMBER() OVER(ORDER BY SUM(Upvt.Qnty)),
        upvt.Type,
        Qnty = SUM(Upvt.Qnty)
FROM    T
       UNPIVOT
        (   Qnty
            FOR Type IN ([Water], [Milk])
        ) upvt
GROUP BY upvt.Type
ORDER BY Qnty;


Please,refer MSDN documentation.
 
Share this answer
 
v2
Comments
Siva Hyderabad 8-Jul-14 5:56am    
Thanks,it's working fine..
Maciej Los 8-Jul-14 9:34am    
You're welcome ;)
Andrius Leonavicius 8-Jul-14 7:47am    
Hi,

Great examples, but I can't agree with this one: "SQL Server 2008 does not support this kind of statement.".

Table Value Constructor was introduced in SQL Server 2008. Also, I tried the original query in SQL Server 2008 and it works (it doesn't in SQL Server 2005)...
Maciej Los 8-Jul-14 9:40am    
Good to know. Thank you very much. I've been almost sure that TVC was introduced in MS SQL Server 2012. Personally, i jumped from 2005 to 2012 ;)
Andrius Leonavicius 8-Jul-14 11:06am    
You're welcome. :) +5 for alternative queries.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900