我有以下数据(我有更多行,这只是一个例子):
VALUE Location FLEET REGION
P Pocatello, ID 104 232
B Pocatello, ID 104 232
B Spokane, WA 107 232
B Spokane, WA 107 232
在报告服务或MSSQL中,我需要按舰队分组。如果它被分组,我希望它看到每个组包含的值。
如果该组包含值P和B,则其生产 如果该组仅包含B,那么它就是报告 如果该组包含P,那么其生产力
我想从这个例子中得到的是最后要返回的行。
VALUE LOCATION FLEET REGION
Production Pocatello,ID 104 232
Reporting Spokane, WAS 107 232
现在,SQL查询报告问题顶部的数据。我需要进行分组和计算是MSSQL还是SSRS任何一个都可以工作,但我如何去做这个列出的数据,就像我上面一样。
谢谢!
答案 0 :(得分:1)
没有表定义,很难说。您的示例数据中已经有完整的副本,表明表中没有主键。每个车队的位置总是一样的吗?那个地区怎么样?如果这实际上是来自另一个连接表的查询的结果集,那么您应该提及并包含各个表的表定义。
这是我最好的猜测,可能会指向正确的方向:
SELECT
CASE
WHEN MIN(value) = 'B' THEN
CASE
WHEN MAX(value) = 'P' THEN 'Production'
ELSE 'Reporting'
END
WHEN MAX(value) = 'P' THEN 'Productivity'
ELSE NULL
END,
location,
fleet,
region
FROM
Some_Table
GROUP BY
location,
fleet,
region
这依赖于它们唯一的两个可能的“价值”值,否则不容易适应。
答案 1 :(得分:1)
您可以对其他列进行分组,并在P
声明中检查B
或case
是否存在:
declare @t table (value char(1), Location varchar(50), fleet int, region int)
insert @t values
('P', 'Pocatello, ID', 104, 232),
('B', 'Pocatello, ID', 104, 232),
('B', 'Spokane, WA', 107, 232),
('B', 'Spokane, WA', 107, 232);
select case
when max(case when value = 'P' then 1 end) = 1
and max(case when value = 'B' then 1 end) = 1 then 'Production'
when max(case when value = 'P' then 1 end) = 1 then 'Productivity'
when max(case when value = 'B' then 1 end) = 1 then 'Reporting'
end
, location
, fleet
, region
from @t
group by
location
, fleet
, region
打印:
(No column name) location fleet region
Production Pocatello, ID 104 232
Reporting Spokane, WA 107 232
答案 2 :(得分:0)
Select Fleet
, Min(Case
When ValueCount.PCount = 1 And ValueCount.BCount = 1 Then 'Production'
When ValueCount.PCount = 1 And ValueCount.BCount = 0 Then 'Productivity'
Else 'Reporting'
End) As Value
, Min(Location) As Location
, Min(Region) As Region
From Table
Join (
Select Fleet
, Sum( Case When T2.Value = 'P' Then 1 Else 0 End ) As PCount
, Sum( Case When T2.Value = 'B' Then 1 Else 0 End ) As BCount
From Table As T2
Where T2.Value In('P','B')
Group By T2.Fleet
) As ValueCount
On ValueCount.Fleet = Table.Fleet
Group By Fleet