Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Helping here <a href="http://msdn.microsoft.com/en-us/library/aa172756%28SQL.80%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa172756%28SQL.80%29.aspx</a></p> <p>Actual Table:</p> <pre><code>Year Quarter Amount 1990 1 1.1 1990 2 1.2 1990 3 1.3 1990 4 1.4 1991 1 2.1 1991 2 2.2 1991 3 2.3 1991 4 2.4 1992 4 2.4 </code></pre> <p>Desired Output: (Here Q for Quarter)</p> <pre><code>Year Q-1 Q-2 Q-3 Q-4 1990 1.1 1.2 1.3 1.4 1991 2.1 2.2 2.3 2.4 1992 0.0 0.0 0.0 2.4 </code></pre> <p>Query:</p> <pre><code>Use Northwind GO CREATE TABLE Pivot ( Year SMALLINT, Quarter TINYINT, Amount DECIMAL(2,1) ) GO INSERT INTO Pivot VALUES (1990, 1, 1.1) INSERT INTO Pivot VALUES (1990, 2, 1.2) INSERT INTO Pivot VALUES (1990, 3, 1.3) INSERT INTO Pivot VALUES (1990, 4, 1.4) INSERT INTO Pivot VALUES (1991, 1, 2.1) INSERT INTO Pivot VALUES (1991, 2, 2.2) INSERT INTO Pivot VALUES (1991, 3, 2.3) INSERT INTO Pivot VALUES (1991, 4, 2.4) INSERT INTO Pivot VALUES (1992, 4, 2.4) GO SELECT * FROM Pivot GO SELECT Year, SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1, SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2, SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3, SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4 FROM Northwind.dbo.Pivot GROUP BY Year GO </code></pre> <p>Another Output:</p> <pre><code>SELECT P1.*, (P1.Q1 + P1.Q2 + P1.Q3 + P1.Q4) AS YearTotal FROM (SELECT Year, SUM(CASE P.Quarter WHEN 1 THEN P.Amount ELSE 0 END) AS Q1, SUM(CASE P.Quarter WHEN 2 THEN P.Amount ELSE 0 END) AS Q2, SUM(CASE P.Quarter WHEN 3 THEN P.Amount ELSE 0 END) AS Q3, SUM(CASE P.Quarter WHEN 4 THEN P.Amount ELSE 0 END) AS Q4 FROM Pivot AS P GROUP BY P.Year) AS P1 GO </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload