-2

我不小心删除了一个数据库表,不得不从过时的备份中恢复它。我在备份和恢复之间做了一些事情,改变了我从某个查询收到的结果。我想要五个结果,它给了我七个,因为结果行有不同Color的值。在我让它完美运行之前不知何故。这是我的 SQL:

select LocationID, SUM(TransAmount) as TotalSales, DBAName, Color 
from dbx.dbo.SampleData 
group by LocationID, DBAName, Color

它曾经给我:

LocationID      TotalSales  DBAName                Color
267529000000    7660.51     FASTWAY #1 TACO BELL   Red
267529000001    2681.801    FASTWAY #2 TACO BELL   Orange
267529000002    3020.57     FASTWAY #3 TACO BELL   Yellow
267529000003    3062.63     FASTWAY #4 TACO BELL   Green
267529000004    3401.36     FASTWAY #5 TACO BELL   Blue

但现在有了看似相同的数据,它给了我:

LocationID      TotalSales  DBAName                 Color
267529000000    2183.26     FASTWAY #1 TACO BELL    Indigo
267529000000    2901.48     FASTWAY #1 TACO BELL    Red
267529000000    2575.77     FASTWAY #1 TACO BELL    Violet
267529000001    2681.80     FASTWAY #2 TACO BELL    Orange
267529000002    3020.57     FASTWAY #3 TACO BELL    Yellow
267529000003    3062.63     FASTWAY #4 TACO BELL    Blue
267529000004    3401.36     FASTWAY #5 TACO BELL    Green

总是以靛蓝和紫罗兰色为颜色,但无视它们并使用红色作为主要颜色。有任何想法吗?解决这个令人沮丧的事件的技巧?谢谢!

4

1 回答 1

0

尚不清楚您想要什么,但如果只是要拥有IndigoViolet计算和显示,Red您可以使用带有简单CASE语句的内部查询来更改颜色,然后将其包装在执行聚合和分组的外部查询中。它会得到想要的结果:

SELECT LocationID, SUM(TransAmount) AS TotalSales, DBAName, Color 
FROM (
  SELECT LocationID, TransAmount, DBAName, 
    CASE Color 
     WHEN 'Indigo' THEN 'Red' 
     WHEN 'Violet' THEN 'Red' 
     ELSE Color END 
    AS Color 
  FROM dbx.dbo.SampleData 
) x
GROUP BY LocationID, DBAName, Color

但是,这可能不是一个好的解决方案。

编辑:获得第一个值的另一种方法。虽然可能不利于性能:

SELECT 
    s.LocationID, 
    SUM(TransAmount) AS TotalSales, 
    DBANAME_Color.DBAName, 
    DBANAME_Color.Color 
FROM dbx.dbo.SampleData s 
INNER JOIN (
    SELECT 
        LocationID, 
        ROW_NUMBER() OVER (PARTITION BY LocationID ORDER BY DBAName) AS Row, 
        DBAName, 
        Color
    FROM dbx.dbo.SampleData 
) DBANAME_Color ON s.LocationID = DBANAME_Color.LocationID
WHERE DBANAME_Color.Row = 1 
GROUP BY s.LocationID, DBANAME_Color.DBAName, DBANAME_Color.Color
于 2013-08-14T23:29:00.017 回答