如何在SQL中的一个查询中显示具有不同条件的多列?

时间:2016-06-29 21:40:33

标签: sql-server

我想知道表TRANSPORTARCHIVE每月有多少不同的TRANSPORTNO。可能有更好的方法来做到这一点。

select COUNT(distinct TRANSPORTNO)
from TRANSPORTARCHIVE
where DATEASKED between '2015-01-01' and '2015-01-31'

select COUNT(distinct TRANSPORTNO)
from TRANSPORTARCHIVE
where DATEASKED between '2015-02-01' and '2015-02-28'

select COUNT(distinct TRANSPORTNO)
from TRANSPORTARCHIVE
where DATEASKED between '2015-03-01' and '2015-03-31'

依旧......

我想要一个输出显示12列,每个月有不同的TRANSPORTNO数

由于

3 个答案:

答案 0 :(得分:1)

试试这个:

select 
   COUNT(distinct TRANSPORTNO) as cnt,
   month(DATEASKED) as date_month
from TRANSPORTARCHIVE
group by month(DATEASKED)
where DATEASKED between '2015-01-01' and '2015-01-31';

答案 1 :(得分:0)

您希望按月分组。在MySQL中有类似的东西:

select
    EXTRACT(year from DATEASKED) 
    , EXTRACT(month from DATEASKED) 
    , COUNT(distinct TRANSPORTNO)
from 
    TRANSPORTARCHIVE
where 
    DATEASKED between '2015-01-01' and '2015-03-31'
group by 
    1,2

如果您正在使用SQL Server:

select
    YEAR(DATEASKED) 
    , MONTH(DATEASKED) 
    , COUNT(distinct TRANSPORTNO)
from 
    TRANSPORTARCHIVE
where 
    DATEASKED between '2015-01-01' and '2015-03-31'
group by 1,2

答案 2 :(得分:0)

Aleksey的答案基本上是正确的,除非你需要摆脱WHERE子句。

<table class="table table-striped table-advance table-hover">
    <tbody>
    <?php
        foreach ($notification as $key => $value) 
        {
    ?>

        <tr class="unread" data-messageid="1">
            <td class="view-message "> 
                <?php
                    echo '<a href='.base_url().'notification/notif/'.$value['notification_id'].'>'.$value['notification_message'].'</a><br>';
                ?>
            </td>
            <td class="view-message text-right"> <?php echo $this->time_elapsed_string($value['notification_created_date']); ?> </td>
        </tr>

    <?php
        }
    ?>
    </tbody>
</table>