我遇到了一个我想写的查询问题。 该查询应该向我提供客户编号,该客户的总收入以及收入的其他值(即' Gold',' Silver'或' Bronze&# 39)。 我有一个查询,为我提供每个客户的总收入:
CREATE PROCEDURE sp_klantOverzicht
DECLARE @beginDatum DATETIME
DECLARE @eindDatum DATETIME
--AS
SET @beginDatum = '2013-01-01 00:00:00.000';
SET @eindDatum = '2017-01-01 00:00:00.000';
SELECT KLANT_NR, SUM(PRIJS) AS OMZET
FROM (
SELECT kl.KLANT_NR, SUM(DATEDIFF(d, h.STARTDATUM, h.EINDDATUM)*a.PRIJS_PER_D) AS PRIJS
FROM HUUROVEREENKOMST AS h
LEFT JOIN ARTIKEL AS a
ON h.BARCODE = a.BARCODE
LEFT JOIN KLANT AS kl
ON kl.KLANT_NR = h.KLANT_NR
WHERE DATEPART(year, h.STARTDATUM) BETWEEN DATEPART(year, @beginDatum)
AND DATEPART(year, @eindDatum)
GROUP BY kl.KLANT_NR
UNION
SELECT kl.KLANT_NR, SUM(a.PRIJS) AS PRIJS
FROM ARTIKEL AS a
LEFT JOIN KOOPOVEREENKOMST AS k
ON k.BARCODE = a.BARCODE
LEFT JOIN KLANT AS kl
ON kl.KLANT_NR = k.KLANT_NR
WHERE DATEPART(year, k.DATUM) BETWEEN DATEPART(year, @beginDatum)
AND DATEPART(year, @eindDatum)
GROUP BY kl.KLANT_NR
) AS overzicht
GROUP BY KLANT_NR
ORDER BY OMZET DESC
它会给我一个这样的结果:
现在,我需要的是检查' OMZET'列高于50,100或150,然后添加' Bronze',' Silver'或者' Gold'在第三栏。
我试图在SELECT
语句中使用子查询来实现此目的,并创建一个计算第三列的函数。但没有结果。
任何人都可以帮我找到正确的解决方案吗?
所有帮助将不胜感激!
答案 0 :(得分:2)
使用CASE ... WHEN语句
SELECT KLANT_NR, SUM(PRIJS) AS OMZET,
CASE WHEN SUM(PRIJS) >= 150 THEN 'GOLD'
WHEN SUM(PRIJS) >= 100 THEN 'SILVER'
WHEN SUM(PRIJS) >= 50 THEN 'BRONZE'
END
FROM ( ....
将其作为选择元素
之一添加到您的查询中