我正在尝试在SQL Server中生成一个如下所示的表:
Name | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Total
Product1 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 4
Product2 | 2 | 1 | 0 | 1 | 0 | 0 | 0 | 4
Product3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1
我的数据目前位于以下三个表格中:
ProductName
ID | Name
1 | Product1
2 | Product2
3 | Product3
ProductSelection
PID | CID
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
3 | 2
4 | 1
5 | 2
6 | 1
ProductOrder
ID | Name | SubmitDate
1 | John Doe | 6/15/2015
2 | Jane Doe | 6/15/2015
3 | Sam Doe | 6/16/2015
4 | Mark Doe | 6/17/2015
5 | Bob Doe | 6/18/2015
6 | Adam Doe | 6/19/2015
现在我知道我需要使用类似于此的PIVOT:
PIVOT (COUNT(Name) FOR [Day] IN (Mon, Tue, Wed, Thu, Fri, Sat, Sun)) AS PivotTable
但我正在努力将其余的查询放在一起。我不知道如何获得总数,也许是内部加入?非常感谢任何帮助。
答案 0 :(得分:1)
除了使用PIVOT
之外,您还可以尝试使用条件聚合:
SELECT
Name = pn.Name,
[Mon] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Monday' THEN 1 ELSE 0 END),
[Tue] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Tuesday' THEN 1 ELSE 0 END),
[Wed] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Wednesday' THEN 1 ELSE 0 END),
[Thu] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Thursday' THEN 1 ELSE 0 END),
[Fri] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Friday' THEN 1 ELSE 0 END),
[Sat] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Saturday' THEN 1 ELSE 0 END),
[Sun] = SUM(CASE WHEN DATENAME(WEEKDAY, po.SubmitDate) = 'Sunday' THEN 1 ELSE 0 END),
[Total] = COUNT(*)
FROM ProductOrder po
INNER JOIN ProductSelection ps
ON ps.PID = po.ID
INNER JOIN ProductName pn
ON pn.ID = ps.CID
GROUP BY pn.Name
<强> RESULT 强>
| Name | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Total |
|----------|-----|-----|-----|-----|-----|-----|-----|-------|
| Product1 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 4 |
| Product2 | 2 | 1 | 0 | 1 | 0 | 0 | 0 | 4 |
| Product3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
答案 1 :(得分:0)
试试这个:
$("#divid").on("click", ".tableid", function(){
alert($(this).find('td:first').text());
});
您将获得每周产品销售计数的所有计数