如何使用表中的组获取​​这些查询?

时间:2013-06-15 22:10:50

标签: sql sql-server count group-by

如何在表格中使用该组获取这些查询? " SaveDate"即使第I列中的日期想要按天分组。如下:

+---+------------+------------+---+------------+
|Day|queryresult1|queryresult2|...|queryresult5|
+---+------------+------------+---+------------+
|1  |count       |count       |...|count       |
+---+------------+------------+---+------------+
|2  |count       |count       |...|count       |
+---+------------+------------+---+------------+
|...|...         |...         |...|...         |
+---+------------+------------+---+------------+
|...|...         |...         |...|...         |
+---+------------+------------+---+------------+
|...|...         |...         |...|...         |
+---+------------+------------+---+------------+
|30 |count       |count       |...|count       |
+---+------------+------------+---+------------+

1-15天,以保存表格列中的数据。我如何显示30天?

Select 
(Select Count(*) from Document Where LineID=45 and Esitlendi=1) result1,
(Select Count(*) from Document Where LineID=45 and Esitlendi=1 and TutanakUserID is not null) as result2,
(Select Count(*) from Document Where LineID=45 and Esitlendi=1 and BayiEksik=0 and SahaEksik=0) as result3,
(Select Count(*) from Document Where LineID=45 and Esitlendi=1 and BayiEksik=1 and SahaEksik=0) as result4,
(Select Count(*) from Document Where LineID=45 and Esitlendi=1 and BayiEksik=1 and SahaEksik=1) as result5

由于

1 个答案:

答案 0 :(得分:1)

一系列CASE陈述将起到作用:

SELECT SUM(CASE WHEN LINEID=45 AND Esitlendi=1 THEN 1 ELSE 0 END) Result1
     , SUM(CASE WHEN LineID=45 and Esitlendi=1 and TutanakUserID is not null THEN 1 ELSE 0 END) Result2
     , SUM(CASE WHEN LineID=45 and Esitlendi=1 and BayiEksik=0 and SahaEksik=0 THEN 1 ELSE 0 END) Result3
     , SUM(CASE WHEN LineID=45 and Esitlendi=1 and BayiEksik=1 and SahaEksik=0 THEN 1 ELSE 0 END) Result4
     , SUM(CASE WHEN LineID=45 and Esitlendi=1 and BayiEksik=1 and SahaEksik=1 THEN 1 ELSE 0 END) Result5
FROM Document

由于您有一些共同的标准,您可以将它们移动到WHERE子句:

编辑:我没有在您的示例中看到日期字段,但如果表中有一个日期字段,要显示每天的记录,您需要每天列出的日历表:

SELECT SaveDate
     , COUNT(*) Result1
     , SUM(CASE WHEN TutanakUserID is not null THEN 1 ELSE 0 END) Result2
     , SUM(CASE WHEN BayiEksik=0 and SahaEksik=0 THEN 1 ELSE 0 END) Result3
     , SUM(CASE WHEN BayiEksik=1 and SahaEksik=0 THEN 1 ELSE 0 END) Result4
     , SUM(CASE WHEN BayiEksik=1 and SahaEksik=1 THEN 1 ELSE 0 END) Result5
FROM CalTable a
LEFT JOIN Document b
     ON a.date = b.SaveDate
WHERE LineID=45 and Esitlendi=1
GROUP BY SaveDate
ORDER BY SaveDate