Case in the Group By clause

时间:2016-10-20 12:53:26

标签: sql tsql

First post on here.

The query below runs OK and is getting me the figures i need. The problem is that I must have the oh.paid column in the GROUP BY clause for the query to run. This gives me two results per oh.unitname, I would only like one.

I have searched around and have found some related problems but the solutions didn't work on my query.

Hope some friendly souls out there can point me in the correct direction.

    SELECT oh.unitname,
   oh.CostCode,
   CASE
      WHEN oh.Paid = 1
       THEN 'Kr '+CONVERT( VARCHAR(50), CAST(SUM(oh.paidsum * oh.ExchangeRate) AS MONEY), -1)
       ELSE 'Kr '+CONVERT(VARCHAR(50), CAST(SUM(oh.totalprice * oh.ExchangeRate) AS MONEY), -1)
   END AS Price
    FROM dbo.OrderHead oh
    WHERE oh.RowDeleted = 0
  AND oh.UnitName LIKE '%%'
  AND oh.DateCreated >= '2016-01-01'
  AND oh.DateCreated < '2016-12-30'
  AND oh.CostCode = 1
  GROUP BY oh.UnitName,
     oh.CostCode,
     oh.Paid
  ORDER BY oh.UnitName;

3 个答案:

答案 0 :(得分:0)

I think you want this:

SELECT oh.unitname, oh.CostCode,
       ('Kr ' +
        CONVERT( VARCHAR(50), CAST(SUM(CASE WHEN oh.PAID = 1 THEN oh.paidsum * oh.ExchangeRate ELSE 0 END) AS MONEY), -1)
       ) as PaidSum,
       ('Kr ' +
        CONVERT( VARCHAR(50), CAST(SUM(CASE WHEN oh.PAID <> 1 THEN oh.paidsum * oh.ExchangeRate ELSE 0 END) AS MONEY), -1)
       ) as NotPaidSum
FROM dbo.OrderHead oh
WHERE oh.RowDeleted = 0 AND
      oh.UnitName LIKE '%%' AND
      oh.DateCreated >= '2016-01-01' AND
      oh.DateCreated < '2016-12-30'
      oh.CostCode = 1
GROUP BY oh.UnitName, oh.CostCode,
ORDER BY oh.UnitName;

This splits the sums into two columns. It assumes that oh.Paid is not NULL. If that is possible, it is easy to modify the second condition.

答案 1 :(得分:0)

For the 2 values to be converted to one would you want to SUM them? If so try this:

select a.Unitname,a.CostCode, SUM(a.Price) as Price
from
(
SELECT oh.unitname,
oh.CostCode,
CASE
  WHEN oh.Paid = 1
   THEN 'Kr '+CONVERT( VARCHAR(50), CAST(SUM(oh.paidsum * oh.ExchangeRate) AS MONEY), -1)
   ELSE 'Kr '+CONVERT(VARCHAR(50), CAST(SUM(oh.totalprice * oh.ExchangeRate) AS MONEY), -1)
END AS Price
FROM dbo.OrderHead oh
WHERE oh.RowDeleted = 0
AND oh.UnitName LIKE '%%'
AND oh.DateCreated >= '2016-01-01'
AND oh.DateCreated < '2016-12-30'
AND oh.CostCode = 1
)
GROUP BY a.UnitName,
 a.CostCode
ORDER BY a.UnitName

This will allow you to sum the paid column after the initial changes done in the case statement.

I hope this makes sense

答案 2 :(得分:0)

May be because for some of your oh.unitname and/or oh.costname the oh.paid is different. So it will group for paid =1 separate and else separate