我有一个关于计算同一个表中同一行中多个字段的问题。展示我需要的最简单的方法是提供一个例子。我有report_number
,writer1
,loc1
,writer2
,loc2
列。你可以打电话给我的表report_master。我的表看起来像这样:
Report_Number, writer1, loc1, writer2, loc2 1 123 1 456 2 2 456 2 789 3 3 789 3 123 1 4 789 3 123 1 5 456 2 789 3 6 123 1 456 2 7 123 1 789 3 8 456 2 123 1 9 789 3 123 1 10 123 1 456 2
输出:
Reports, writer 8 123 6 456 6 789
我已经尝试过并且无法弄清楚查询以获取作者参与的报告数量。如果报告在writer1或writer2字段中,则作者将获得报告。我想将我的查询基于日期范围和loc。因此,如果我输入一个日期范围(该表确实有一个日期字段)和一个loc#(包括搜索loc1和loc2),我会得到一些看起来像结果表的东西。
提前感谢您的帮助。我将在SQL SSRS中使用它。
答案 0 :(得分:1)
SELECT COUNT(*) AS Reports, q.writer
FROM (SELECT writer1 AS writer
FROM YourTable
WHERE loc1 = 1
UNION ALL
SELECT writer2 AS writer
FROM YourTable
WHERE loc2 = 1) q
GROUP BY q.writer
答案 1 :(得分:0)
最直接的方法是对每个作家字段的选择联合计数
SELECT COUNT(report_number) reports,
writer
FROM (SELECT report_number,
writer1 as writer
FROM table
UNION ALL
SELECT report_number
writer2 as writer
FROM table) t
GROUP BY writer
另一个选择是使用UNPIVOT
条款,但如果您的UNION SELECT不是微不足道的话,那么它真的是值得的
SELECT COUNT(report_number),
writer
FROM (SELECT report_number,
writer1,
writer2
FROM reports) p UNPIVOT (writer FOR writer_type IN (writer1, writer2)
)AS
unpvt
GROUP BY writer